Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat!: share saved queries with per-object VIEWER/EDITOR grants (#21178)
Danny Xua497427f53e2
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex a7e99ae10b..50e51fc600 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -5775,10 +5775,11 @@ paths:- bytebase.v1.SavedQueryServicesummary: BatchUpdateSavedQueriesdescription: |-- Batch re-file saved queries into a folder. The update mask supports- `folder` only; only rows the caller may re-file are updated (their own,- or any in scope for admins).- Permissions required: creator, or bb.savedQueries.manage in scope+ Re-file saved queries into a folder in bulk; the update mask supports+ `folder` only. An EDITOR binding does not carry re-filing, so matched+ saved queries the caller cannot re-file are skipped rather than rejected,+ and the response counts what actually changed.+ Permissions required: creator, or bb.savedQueries.manageoperationId: bytebase.v1.SavedQueryService.BatchUpdateSavedQueriesparameters:- name: Connect-Protocol-Version@@ -5815,8 +5816,8 @@ paths:- bytebase.v1.SavedQueryServicesummary: CreateSavedQuerydescription: |-- Creates a personal saved query used in SQL Editor. The creator becomes- the fixed owner.+ Create a saved query. The creator becomes its fixed owner, and the saved+ query starts private.Permissions required: bb.savedQueries.create on the parent projectoperationId: bytebase.v1.SavedQueryService.CreateSavedQueryparameters:@@ -5854,9 +5855,10 @@ paths:- bytebase.v1.SavedQueryServicesummary: DeleteSavedQuerydescription: |-- Delete a saved query. Only the creator (or an admin) can delete.- Returns NotFound for saved queries the caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: bytebase.v1.SavedQueryService.DeleteSavedQueryparameters:- name: Connect-Protocol-Version@@ -5893,9 +5895,9 @@ paths:- bytebase.v1.SavedQueryServicesummary: GetSavedQuerydescription: |-- Get a saved query by name. Returns NotFound for saved queries the- caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: bytebase.v1.SavedQueryService.GetSavedQueryparameters:- name: Connect-Protocol-Version@@ -5926,17 +5928,58 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.SavedQuery'+ /bytebase.v1.SavedQueryService/GetSavedQueryPolicy:+ post:+ tags:+ - bytebase.v1.SavedQueryService+ summary: 'Get a saved query''s sharing policy: who it is shared with, at what level.'+ 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+ operationId: bytebase.v1.SavedQueryService.GetSavedQueryPolicy+ parameters:+ - name: Connect-Protocol-Version+ in: header+ required: true+ schema:+ $ref: '#/components/schemas/connect-protocol-version'+ - name: Connect-Timeout-Ms+ in: header+ schema:+ $ref: '#/components/schemas/connect-timeout-header'+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.GetSavedQueryPolicyRequest'+ required: true+ responses:+ default:+ description: Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/connect.error'+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'/bytebase.v1.SavedQueryService/ListSavedQueries:post:tags:- bytebase.v1.SavedQueryServicesummary: ListSavedQueriesdescription: |-- List saved queries: the grant-independent governance surface. Supports- listing in a project, or across all projects by using `projects/-`, with- whole statements rather than the previews Search returns — e.g. an- offboarding review filtering by creator.- Permissions required: bb.savedQueries.list+ 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/-"operationId: bytebase.v1.SavedQueryService.ListSavedQueriesparameters:- name: Connect-Protocol-Version@@ -5971,11 +6014,16 @@ paths:post:tags:- bytebase.v1.SavedQueryService- summary: SearchSavedQueries+ summary: |-+ Search saved queries in one project: the SQL Editor's list path, returning+ content previews.description: |-- Search for saved queries in a project: the SQL Editor's hot list path,- returning only rows the caller can read, with content previews.- Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ 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.+ Permissions required: bb.savedQueries.search on the projectoperationId: bytebase.v1.SavedQueryService.SearchSavedQueriesparameters:- name: Connect-Protocol-Version@@ -6010,14 +6058,18 @@ paths:post:tags:- bytebase.v1.SavedQueryService- summary: SearchSavedQueryFolders+ 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: |-- Search the folder paths of the caller's saved queries in a project.- Folders are a derived view over the `folder` field rather than a- resource collection, so this is a custom method on savedQueries and- shares SearchSavedQueries' caller-scoped semantics — not the- cross-creator reach of ListSavedQueries.- Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ 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`).+ Permissions required: bb.savedQueries.search on the projectoperationId: bytebase.v1.SavedQueryService.SearchSavedQueryFoldersparameters:- name: Connect-Protocol-Version@@ -6048,16 +6100,58 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.SearchSavedQueryFoldersResponse'+ /bytebase.v1.SavedQueryService/SetSavedQueryPolicy:+ post:+ tags:+ - bytebase.v1.SavedQueryService+ 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+ operationId: bytebase.v1.SavedQueryService.SetSavedQueryPolicy+ parameters:+ - name: Connect-Protocol-Version+ in: header+ required: true+ schema:+ $ref: '#/components/schemas/connect-protocol-version'+ - name: Connect-Timeout-Ms+ in: header+ schema:+ $ref: '#/components/schemas/connect-timeout-header'+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.SetSavedQueryPolicyRequest'+ required: true+ responses:+ default:+ description: Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/connect.error'+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'/bytebase.v1.SavedQueryService/UpdateSavedQuery:post:tags:- bytebase.v1.SavedQueryServicesummary: UpdateSavedQuerydescription: |-- Update a saved query. `title`, `content`, and `database` require write- access; `folder` re-files the saved query and is creator/admin only.- Returns NotFound for saved queries the caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: bytebase.v1.SavedQueryService.UpdateSavedQueryparameters:- name: Connect-Protocol-Version@@ -6094,12 +6188,10 @@ paths:- bytebase.v1.SavedQueryServicesummary: UpdateSavedQueryStardescription: |-- Star or unstar a saved query for the caller. A star is always the- caller's own per-user marker — invisible to others and carrying no- access. The only requirement is that the caller can read the saved- query being starred (which also keeps private saved query names- unprobeable).- Permissions required: read access to the saved query+ Star or unstar a saved query for the caller. A star is a per-user marker:+ invisible to everyone else and granting nothing. Read access is the gate+ only so unreadable saved queries stay unprobeable.+ Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageoperationId: bytebase.v1.SavedQueryService.UpdateSavedQueryStarparameters:- name: Connect-Protocol-Version@@ -9297,31 +9389,26 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource whose saved queries are updated.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the batch update target.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Select the saved queries to update, in CEL. See+ https://github.com/google/cel-spec- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support exact "==" operator.+ Supported fields:+ - name: the saved query name. Supports "==" and "in [...]".+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ - starred: whether the caller starred it. Supports "==".+ - folder: the exact folder path. Supports "==".savedQuery:title: saved_query- description: The fields to apply to every matched saved query.+ description: The values to apply to every matched saved query.$ref: '#/components/schemas/bytebase.v1.SavedQuery'updateMask:title: update_mask- description: |-- The list of fields to be updated.- Only support update the following fields for now:- - `folder`+ description: 'Fields to update. Supported: `folder`.'$ref: '#/components/schemas/google.protobuf.FieldMask'title: BatchUpdateSavedQueriesRequestadditionalProperties: false@@ -9332,7 +9419,9 @@ components:type: integertitle: updated_countformat: int32- description: The number of saved queries updated.+ description: |-+ How many saved queries were updated, which may be fewer than the filter+ matched.title: BatchUpdateSavedQueriesResponseadditionalProperties: falsebytebase.v1.BillingInterval:@@ -10167,7 +10256,7 @@ components:type: stringtitle: parentdescription: |-- The parent resource where this saved query will be created.+ The project to create the saved query in.Format: projects/{project}savedQuery:title: saved_query@@ -11191,9 +11280,7 @@ components:name:type: stringtitle: name- description: |-- The name of the saved query to delete.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'title: DeleteSavedQueryRequestadditionalProperties: falsebytebase.v1.DeleteServiceAccountRequest:@@ -12301,15 +12388,22 @@ components:Format: projects/{project}/plans/{plan}/rollouttitle: GetRolloutRequestadditionalProperties: false+ bytebase.v1.GetSavedQueryPolicyRequest:+ type: object+ properties:+ resource:+ type: string+ title: resource+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'+ title: GetSavedQueryPolicyRequest+ additionalProperties: falsebytebase.v1.GetSavedQueryRequest:type: objectproperties:name:type: stringtitle: name- description: |-- The name of the saved query to retrieve.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'title: GetSavedQueryRequestadditionalProperties: falsebytebase.v1.GetSchemaStringRequest:@@ -14470,40 +14564,34 @@ components:type: stringtitle: parentdescription: |-- The parent resource of the saved queries.+ The project to list saved queries in, or "projects/-" for every project.Format: projects/{project}- Use "projects/-" to list saved queries across all projects.filter:type: stringtitle: filterdescription: |-- To filter the list result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Filter the result, in CEL. See https://github.com/google/cel-spec- Supported filter:- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ Supported fields:+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".For example:- creator == "users/{email}"- creator != "users/{email}"+ creator == "users/[email protected]"pageSize:type: integertitle: page_sizeformat: int32description: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.pageToken:type: stringtitle: page_tokendescription: |-- A page token, received from a previous `ListSavedQueries` call.- Provide this to retrieve the subsequent page.-- When paginating, all other parameters provided to `ListSavedQueries` must match- the call that provided the page token.+ 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.title: ListSavedQueriesRequestadditionalProperties: falsebytebase.v1.ListSavedQueriesResponse:@@ -14514,14 +14602,12 @@ components:items:$ref: '#/components/schemas/bytebase.v1.SavedQuery'title: saved_queries- description: The saved queries from the specified parent.nextPageToken:type: stringtitle: next_page_tokendescription: |-- A token to retrieve next page of saved queries.- Pass this value in the page_token field in the subsequent call to- `ListSavedQueries` method to retrieve the next page of saved queries.+ Pass to the next ListSavedQueries call to fetch the following page. Empty+ on the last page.title: ListSavedQueriesResponseadditionalProperties: falsebytebase.v1.ListServiceAccountsRequest:@@ -17686,22 +17772,20 @@ components:type: stringtitle: namedescription: |-- The name of the saved query resource, generated by the server.- Canonical parent is project.+ Server-generated.Format: projects/{project}/savedQueries/{savedQuery}project:type: stringtitle: project- description: |-- The project resource name.- Format: projects/{project}+ description: 'Format: projects/{project}'database:type: stringtitle: databasedescription: |-- The database resource name.+ The connected database, which must belong to the saved query's own+ project. Empty when none is connected, or when the database no longer+ exists.Format: instances/{instance}/databases/{database}- If the database parent doesn't exist, the database field is empty.title:type: stringtitle: title@@ -17711,46 +17795,104 @@ components:type: stringtitle: creatordescription: |-- The creator of the SavedQuery — the fixed owner; ownership does not- transfer.+ The fixed owner. Ownership does not transfer.Format: users/{email}createTime:title: create_time- description: The create time of the saved query.$ref: '#/components/schemas/google.protobuf.Timestamp'updateTime:title: update_time- description: The last update time of the saved query.$ref: '#/components/schemas/google.protobuf.Timestamp'content:type: stringtitle: contentformat: bytedescription: |-- The content of the saved query.- By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can- use GetSavedQuery() request to retrieve the full content.+ The SQL text. SearchSavedQueries truncates it; when it is shorter than+ `content_size`, GetSavedQuery returns the whole thing.contentSize:type:- integer- stringtitle: content_sizeformat: int64- description: content_size is the full size of the content, may not match the size of the `content` field.+ description: The full size of the content, which may exceed the `content` returned.starred:type: booleantitle: starred- description: starred indicates whether the saved query is starred by the current authenticated user.+ description: Whether the calling user starred it.folder:type: stringtitle: foldermaxLength: 256description: |-- The folder path this saved query lives in, set by its creator (or an- admin). Empty means unfiled. A saved query lives in exactly one folder;- a folder is a path on saved queries, e.g. "a/b/c".+ The folder holding this saved query, set by its creator or an admin. A+ path like "a/b/c"; empty means unfiled.title: SavedQueryadditionalProperties: false+ bytebase.v1.SavedQueryBinding:+ type: object+ properties:+ level:+ title: level+ $ref: '#/components/schemas/bytebase.v1.SavedQueryBinding.Level'+ members:+ type: array+ items:+ type: string+ 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.++ 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.+ 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.+ bytebase.v1.SavedQueryBinding.Level:+ type: string+ title: Level+ enum:+ - LEVEL_UNSPECIFIED+ - VIEWER+ - EDITOR+ description: |-+ Nested because bytebase.v1 already defines a package-scoped EDITOR+ (DatabaseChangeMode), and enum values live in the enclosing scope.+ bytebase.v1.SavedQueryPolicy:+ type: object+ properties:+ bindings:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryBinding'+ title: bindings+ description: |-+ At most one binding per level. A member listed under two levels is+ rejected rather than resolved to the higher one.+ etag:+ type: string+ title: etag+ description: |-+ The etag of the policy as read. SetSavedQueryPolicy requires it and fails+ with ABORTED when it no longer matches.+ 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.bytebase.v1.SchemaCatalog:type: objectproperties:@@ -18220,45 +18362,50 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource of the saved queries.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the search result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Filter the result, in CEL. See https://github.com/google/cel-spec- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - title: the saved query title, support "contains" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support "==" operator.+ Supported fields:+ - 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 "==".+ - 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.For example:- creator == "users/{email}"- title.contains("saved query title")- creator != "users/{email}"+ creator == "users/[email protected]"+ shared == truestarred == true- starred == false+ title.contains("weekly report")folder == "foo/bar"pageSize:type: integertitle: page_sizeformat: int32description: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.pageToken:type: stringtitle: page_tokendescription: |-- A page token, received from a previous `SearchSavedQueries` call.- Provide this to retrieve the subsequent page.+ 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.title: SearchSavedQueriesRequestadditionalProperties: falsebytebase.v1.SearchSavedQueriesResponse:@@ -18269,14 +18416,12 @@ components:items:$ref: '#/components/schemas/bytebase.v1.SavedQuery'title: saved_queries- description: The saved queries that matched the search criteria.nextPageToken:type: stringtitle: next_page_tokendescription: |-- A token to retrieve next page of saved queries.- Pass this value in the page_token field in the subsequent call to- `SearchSavedQueries` method to retrieve the next page of saved queries.+ Pass to the next SearchSavedQueries call to fetch the following page.+ Empty on the last page.title: SearchSavedQueriesResponseadditionalProperties: falsebytebase.v1.SearchSavedQueryFoldersRequest:@@ -18285,22 +18430,14 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource whose saved query folders are searched.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the folders by the saved queries they hold. Takes the same- fields and syntax as `SearchSavedQueries.filter`, except `title`. A- folder is returned when at least one saved query the caller can read- matches, so the caller-scoping is the same as SearchSavedQueries: your- own saved queries, plus everyone's for the admin backstop.-- For example, to split a folder tree into your own and everyone else's:- creator == "users/{email}"- creator != "users/{email}"+ Filter folders by the saved queries they hold. Takes the same fields and+ syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ when at least one saved query the caller can read matches.title: SearchSavedQueryFoldersRequestadditionalProperties: falsebytebase.v1.SearchSavedQueryFoldersResponse:@@ -18312,9 +18449,8 @@ components:type: stringtitle: foldersdescription: |-- The caller's folder paths, including every ancestor prefix, sorted.- A folder is a path on saved queries ("a/b/c"), so empty folders cannot- exist.+ Folder paths, every ancestor prefix included, sorted. A folder is a path+ on saved queries ("a/b/c"), so empty folders cannot exist.title: SearchSavedQueryFoldersResponseadditionalProperties: falsebytebase.v1.SemanticTypeSetting:@@ -18483,6 +18619,21 @@ components:title: SetIamPolicyRequestadditionalProperties: falsedescription: Request message for setting an IAM policy.+ bytebase.v1.SetSavedQueryPolicyRequest:+ type: object+ properties:+ resource:+ type: string+ title: resource+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'+ 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.+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'+ title: SetSavedQueryPolicyRequest+ additionalProperties: falsebytebase.v1.Setting:type: objectproperties:@@ -20634,22 +20785,14 @@ components:savedQuery:title: saved_querydescription: |-- The saved query to update.-- The saved query's `name` field is used to identify the saved query to update.+ `saved_query.name` identifies the saved query to update.Format: projects/{project}/savedQueries/{savedQuery}$ref: '#/components/schemas/bytebase.v1.SavedQuery'updateMask:title: update_maskdescription: |-- The list of fields to be updated.- Fields are specified relative to the saved query.- (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)- Only support update the following fields for now:- - `title`- - `content`- - `database`- - `folder`+ Fields to update, relative to the saved query (`title`, not+ `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.$ref: '#/components/schemas/google.protobuf.FieldMask'title: UpdateSavedQueryRequestadditionalProperties: false@@ -20659,9 +20802,7 @@ components:name:type: stringtitle: name- description: |-- The name of the saved query to star or unstar.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'starred:type: booleantitle: starred@@ -22705,11 +22846,14 @@ tags:description: |-SavedQueryService manages saved queries for SQL Editor query development.- A saved query is private to its creator; `bb.savedQueries.manage` is the- admin backstop that can reach any saved query in scope. Per-object- VIEWER/EDITOR grants arrive with the access-model redesign, which brings- its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages- them.+ 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.- name: bytebase.v1.ServiceAccountServicedescription: ServiceAccountService manages service accounts for API integrations.- name: bytebase.v1.SheetServicediff --git a/backend/api/v1/saved_query_service.go b/backend/api/v1/saved_query_service.goindex 6ca0c0b250..36757ec626 100644--- a/backend/api/v1/saved_query_service.go+++ b/backend/api/v1/saved_query_service.go@@ -3,7 +3,6 @@ package v1import ("context""fmt"- "log/slog""slices""strings"@@ -15,6 +14,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/permission""github.com/bytebase/bytebase/backend/component/iam"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect""github.com/bytebase/bytebase/backend/store"@@ -115,11 +115,11 @@ func (s *SavedQueryService) GetSavedQuery(return nil, err}- ok, err := s.canReadSavedQuery(ctx, savedQuery)+ access, err := s.savedQueryAccess(ctx, savedQuery)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))+ return nil, err}- if !ok {+ if !access.canRead() {// 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"))@@ -234,24 +234,24 @@ func (s *SavedQueryService) SearchSavedQueryFolders(return nil, err}- filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, request.Filter, false /* allowTitleContains */)+ accessMembers, err := s.iamManager.PrincipalMembers(ctx, common.GetWorkspaceIDFromContext(ctx), user)if err != nil {- return nil, connect.NewError(connect.CodeInvalidArgument, err)+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve principals: %v", err))}- // Folders are derived from rows, so they inherit the rows' read rule.- // Without the admin backstop the caller only ever sees folders holding- // their own saved queries, whatever the filter asks for.- canManage, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesManage, user, common.GetWorkspaceIDFromContext(ctx), projectID)+ filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, accessMembers, request.Filter, false /* allowTitleContains */)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))- }- creator := &user.Email- if canManage {- creator = nil+ return nil, connect.NewError(connect.CodeInvalidArgument, err)}- paths, err := s.store.ListSavedQueryFolderPaths(ctx, projectID, creator, filterQ)+ // 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)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to search saved query folders: %v", err))}@@ -318,7 +318,23 @@ func (s *SavedQueryService) SearchSavedQueries(Offset: &offset.offset,}- filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, request.Filter, true /* allowTitleContains */)+ // 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 */)if err != nil {return nil, connect.NewError(connect.CodeInvalidArgument, err)}@@ -336,18 +352,9 @@ func (s *SavedQueryService) SearchSavedQueries(savedQueryList = savedQueryList[:offset.limit]}- var v1pbSavedQueries []*v1pb.SavedQuery+ v1pbSavedQueries := make([]*v1pb.SavedQuery, 0, len(savedQueryList))for _, savedQuery := range savedQueryList {- ok, err := s.canReadSavedQuery(ctx, savedQuery)- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))- }- if !ok {- slog.Warn("cannot access saved query", slog.String("name", savedQuery.Title))- continue- }- v1pbSavedQuery := convertToAPISavedQuery(savedQuery)- v1pbSavedQueries = append(v1pbSavedQueries, v1pbSavedQuery)+ v1pbSavedQueries = append(v1pbSavedQueries, convertToAPISavedQuery(savedQuery))}return connect.NewResponse(&v1pb.SearchSavedQueriesResponse{SavedQueries: v1pbSavedQueries,@@ -384,17 +391,19 @@ func (s *SavedQueryService) UpdateSavedQuery(if err != nil {return nil, err}- ok, err = s.canWriteSavedQuery(ctx, savedQuery)+ access, err := s.savedQueryAccess(ctx, savedQuery)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))+ return nil, err}- if !ok {- // Write access and read access are one predicate today, so failing it- // means the caller cannot see this row either -- answer as if it were- // missing. Once per-object grants land, a VIEWER who cannot write gets- // PermissionDenied here, because they can already see the row.+ if !access.canRead() {+ // Invisible to this caller, so answer as if it were missing rather+ // than confirming the name exists.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,@@ -407,6 +416,11 @@ func (s *SavedQueryService) UpdateSavedQuery(statement := string(request.SavedQuery.Content)savedQueryPatch.Statement = &statementcase "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)@@ -442,6 +456,10 @@ func (s *SavedQueryService) UpdateSavedQuery(ProjectIDs: []string{savedQuery.ProjectID},ResourceID: &savedQueryID,PrincipalEmail: user.Email,+ // Only Search truncates. The client caches this response as its FULL+ // view, so returning a cut-off statement would silently shorten a+ // script larger than common.MaxSheetSize.+ LoadFull: true,})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get saved query: %v", err))@@ -467,17 +485,18 @@ func (s *SavedQueryService) DeleteSavedQuery(if err != nil {return nil, err}- ok, err := s.canWriteSavedQuery(ctx, savedQuery)+ access, err := s.savedQueryAccess(ctx, savedQuery)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))+ return nil, err}- if !ok {- // Write access and read access are one predicate today, so failing it- // means the caller cannot see this row either -- answer as if it were- // missing. Once per-object grants land, a VIEWER who cannot write gets- // PermissionDenied here, because they can already see the row.+ if !access.canRead() {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 {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to delete saved query: %v", err))@@ -499,15 +518,15 @@ func (s *SavedQueryService) UpdateSavedQueryStar(return nil, connect.NewError(connect.CodeInvalidArgument, err)}- savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)+ savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, true /* loadFull */)if err != nil {return nil, err}- ok, err := s.canReadSavedQuery(ctx, savedQuery)+ access, err := s.savedQueryAccess(ctx, savedQuery)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))+ return nil, err}- if !ok {+ if !access.canRead() {return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))}@@ -568,7 +587,12 @@ func (s *SavedQueryService) BatchUpdateSavedQueries(return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))}- filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, request.Filter, false /* allowTitleContains */)+ accessMembers, err := s.iamManager.PrincipalMembers(ctx, common.GetWorkspaceIDFromContext(ctx), user)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve principals: %v", err))+ }++ filterQ, err := store.GetSearchSavedQueryFilter(ctx, s.store, user.Email, accessMembers, request.Filter, false /* allowTitleContains */)if err != nil {return nil, connect.NewError(connect.CodeInvalidArgument, err)}@@ -583,11 +607,14 @@ func (s *SavedQueryService) BatchUpdateSavedQueries(var savedQueryIDs []stringfor _, savedQuery := range savedQueryList {- ok, err := s.canWriteSavedQuery(ctx, savedQuery)+ access, err := s.savedQueryAccess(ctx, savedQuery)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check access with error: %v", err))+ return nil, err}- if !ok {+ // Re-filing is creator/admin only, and matched rows the caller may not+ // re-file are skipped rather than failing the batch — so the response+ // count is what changed, not what matched.+ if !access.canManage() {continue}savedQueryIDs = append(savedQueryIDs, savedQuery.ResourceID)@@ -620,17 +647,19 @@ func (s *SavedQueryService) checkProjectWide(ctx context.Context, user *store.Us}func (s *SavedQueryService) checkDiscoverSavedQueries(ctx context.Context, user *store.UserMessage, projectID string) error {- workspaceID := common.GetWorkspaceIDFromContext(ctx)- for _, p := range []permission.Permission{permission.SavedQueriesSearch, permission.SavedQueriesManage} {- ok, err := s.iamManager.CheckProjectWidePermission(ctx, p, user, workspaceID, projectID)- if err != nil {- return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err))- }- if ok {- return nil- }+ // 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)+ if err != nil {+ return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err))}- return connect.NewError(connect.CodePermissionDenied, errors.Errorf("permission denied: %s", permission.SavedQueriesSearch))+ 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) {@@ -695,32 +724,256 @@ func (s *SavedQueryService) validateSavedQueryDatabase(ctx context.Context, projreturn name, nil}-// canWriteSavedQuery check if the principal can write the saved query.-// Saved queries are private: only the creator, or a caller holding-// "bb.savedQueries.manage" in scope (the admin backstop), can write.-func (s *SavedQueryService) canWriteSavedQuery(ctx context.Context, savedQuery *store.SavedQueryMessage) (bool, error) {- return s.canAccessSavedQuery(ctx, savedQuery)+// 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.+func (s *SavedQueryService) GetSavedQueryPolicy(+ ctx context.Context,+ req *connect.Request[v1pb.GetSavedQueryPolicyRequest],+) (*connect.Response[v1pb.SavedQueryPolicy], error) {+ projectID, savedQueryID, err := common.GetProjectIDSavedQueryID(req.Msg.Resource)+ if err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)+ }++ savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)+ if err != nil {+ return nil, err+ }+ access, err := s.savedQueryAccess(ctx, savedQuery)+ if err != nil {+ return nil, err+ }+ if !access.canRead() {+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))+ }++ policy, err := convertToAPISavedQueryPolicy(savedQuery.Bindings)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to build policy: %v", err))+ }+ return connect.NewResponse(policy), nil+}++// SetSavedQueryPolicy replaces a saved query's grants under compare-and-swap.+func (s *SavedQueryService) SetSavedQueryPolicy(+ ctx context.Context,+ req *connect.Request[v1pb.SetSavedQueryPolicyRequest],+) (*connect.Response[v1pb.SavedQueryPolicy], error) {+ request := req.Msg+ if request.Policy == nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("policy cannot be empty"))+ }+ projectID, savedQueryID, err := common.GetProjectIDSavedQueryID(request.Resource)+ if err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)+ }++ savedQuery, err := s.findSavedQuery(ctx, projectID, savedQueryID, false /* loadFull */)+ if err != nil {+ return nil, err+ }+ access, err := s.savedQueryAccess(ctx, savedQuery)+ if err != nil {+ return nil, err+ }+ if !access.canRead() {+ 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 {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)+ }++ applied, err := s.store.SetSavedQueryBindings(ctx, projectID, savedQuery.ResourceID, bindings, request.Policy.Etag)+ if err != nil {+ if errors.Is(err, store.ErrSavedQueryEtagMismatch) {+ // The policy moved under this write. Aborted tells the caller to+ // refetch and reapply rather than clobber a concurrent revocation.+ return nil, connect.NewError(connect.CodeAborted, errors.Errorf("the saved query policy was modified; refetch and retry"))+ }+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to set policy: %v", err))+ }+ if !applied {+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot find the saved query"))+ }++ policy, err := convertToAPISavedQueryPolicy(bindings)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to build policy: %v", err))+ }+ return connect.NewResponse(policy), nil+}++// convertToAPISavedQueryPolicy converts stored bindings to the API shape,+// stamping the etag the next compare-and-swap write must present.+func convertToAPISavedQueryPolicy(bindings []*storepb.SavedQueryBinding) (*v1pb.SavedQueryPolicy, error) {+ etag, err := store.SavedQueryPolicyEtag(bindings)+ if err != nil {+ return nil, err+ }+ policy := &v1pb.SavedQueryPolicy{Etag: etag}+ for _, binding := range bindings {+ members := make([]string, 0, len(binding.Members))+ for _, member := range binding.Members {+ members = append(members, convertToV1SavedQueryMember(member))+ }+ policy.Bindings = append(policy.Bindings, &v1pb.SavedQueryBinding{+ Level: v1pb.SavedQueryBinding_Level(binding.Level),+ Members: members,+ })+ }+ return policy, nil+}++// convertToStoreSavedQueryMember maps a submitted member to the resource name+// the store holds. Only users and groups are accepted; serviceAccount:,+// workloadIdentity:, and allUsers are not grantees on a saved query.+func convertToStoreSavedQueryMember(member string) (string, error) {+ if email, ok := strings.CutPrefix(member, common.UserBindingPrefix); ok && email != "" {+ return common.FormatUserEmail(email), nil+ }+ if email, ok := strings.CutPrefix(member, common.GroupBindingPrefix); ok && email != "" {+ return common.FormatGroupEmail(email), nil+ }+ return "", errors.Errorf("invalid member %q: only %q and %q are supported", member, common.UserBindingPrefix, common.GroupBindingPrefix)+}++func convertToV1SavedQueryMember(member string) string {+ if email, ok := strings.CutPrefix(member, common.UserNamePrefix); ok {+ return common.UserBindingPrefix + email+ }+ if email, ok := strings.CutPrefix(member, common.GroupPrefix); ok {+ return common.GroupBindingPrefix + email+ }+ return member+}++// convertToStoreSavedQueryBindings validates a submitted policy and converts it+// 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.+//+// 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+// project and workspace IAM use in validateMember, narrowed to the two types a+// saved query accepts. A service account named under a "user:" prefix is inert+// rather than rejected: a caller's members come from their principal type, so+// such a binding matches nobody.+func convertToStoreSavedQueryBindings(bindings []*v1pb.SavedQueryBinding) ([]*storepb.SavedQueryBinding, error) {+ var converted []*storepb.SavedQueryBinding+ seenLevel := make(map[v1pb.SavedQueryBinding_Level]bool, len(bindings))+ seenMember := make(map[string]bool)+ for _, binding := range bindings {+ switch binding.Level {+ case v1pb.SavedQueryBinding_VIEWER, v1pb.SavedQueryBinding_EDITOR:+ default:+ return nil, errors.Errorf("invalid level %q", binding.Level)+ }+ if seenLevel[binding.Level] {+ return nil, errors.Errorf("duplicate binding for level %q", binding.Level)+ }+ seenLevel[binding.Level] = true++ if len(binding.Members) == 0 {+ return nil, errors.Errorf("binding for level %q has no members", binding.Level)+ }+ members := make([]string, 0, len(binding.Members))+ for _, member := range binding.Members {+ if seenMember[member] {+ return nil, errors.Errorf("member %q appears at more than one binding", member)+ }+ seenMember[member] = true+ stored, err := convertToStoreSavedQueryMember(member)+ if err != nil {+ return nil, err+ }+ members = append(members, stored)+ }++ converted = append(converted, &storepb.SavedQueryBinding{+ Level: storepb.SavedQueryBinding_Level(binding.Level),+ Members: members,+ })+ }+ 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}-// canReadSavedQuery check if the principal can read the saved query.-// The access is the same as canWriteSavedQuery.-func (s *SavedQueryService) canReadSavedQuery(ctx context.Context, savedQuery *store.SavedQueryMessage) (bool, error) {- return s.canAccessSavedQuery(ctx, savedQuery)+// 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 (s *SavedQueryService) canAccessSavedQuery(ctx context.Context, savedQuery *store.SavedQueryMessage) (bool, error) {+func (a savedQueryAccess) canWrite() bool {+ return a.isCreator || a.isAdmin || a.level >= storepb.SavedQueryBinding_EDITOR+}++// 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+}++func (s *SavedQueryService) savedQueryAccess(ctx context.Context, savedQuery *store.SavedQueryMessage) (savedQueryAccess, error) {user, ok := GetUserFromContext(ctx)if !ok {- return false, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))+ return savedQueryAccess{}, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))}- if savedQuery.Creator == user.Email {- return true, nil+ 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}- ok, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesManage, user, common.GetWorkspaceIDFromContext(ctx), savedQuery.ProjectID)++ workspaceID := common.GetWorkspaceIDFromContext(ctx)+ isAdmin, err := s.iamManager.CheckProjectWidePermission(ctx, permission.SavedQueriesManage, user, workspaceID, savedQuery.ProjectID)if err != nil {- return false, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))+ return savedQueryAccess{}, connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))+ }+ access.isAdmin = isAdmin++ 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))+ }+ principalSet := make(map[string]bool, len(principals))+ for _, principal := range principals {+ principalSet[principal] = true+ }+ for _, binding := range savedQuery.Bindings {+ if binding.Level <= access.level {+ continue+ }+ for _, member := range binding.Members {+ if principalSet[member] {+ access.level = binding.Level+ break+ }+ }+ }}- return ok, nil+ return access, nil}// convertToAPISavedQuery converts a store message to the API shape. Thediff --git a/backend/component/iam/manager.go b/backend/component/iam/manager.goindex 26a8a116cc..3a191bdf38 100644--- a/backend/component/iam/manager.go+++ b/backend/component/iam/manager.go@@ -120,6 +120,23 @@ func (m *Manager) GetUserGroups(ctx context.Context, workspaceID string, email sreturn 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)diff --git a/backend/generated-go/store/saved_query.pb.go b/backend/generated-go/store/saved_query.pb.goindex 9eb2d477b8..d0a62fc4d9 100644--- a/backend/generated-go/store/saved_query.pb.go+++ b/backend/generated-go/store/saved_query.pb.go@@ -21,6 +21,55 @@ const (_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20))+type SavedQueryBinding_Level int32++const (+ SavedQueryBinding_LEVEL_UNSPECIFIED SavedQueryBinding_Level = 0+ SavedQueryBinding_VIEWER SavedQueryBinding_Level = 1+ SavedQueryBinding_EDITOR SavedQueryBinding_Level = 2+)++// Enum value maps for SavedQueryBinding_Level.+var (+ SavedQueryBinding_Level_name = map[int32]string{+ 0: "LEVEL_UNSPECIFIED",+ 1: "VIEWER",+ 2: "EDITOR",+ }+ SavedQueryBinding_Level_value = map[string]int32{+ "LEVEL_UNSPECIFIED": 0,+ "VIEWER": 1,+ "EDITOR": 2,+ }+)++func (x SavedQueryBinding_Level) Enum() *SavedQueryBinding_Level {+ p := new(SavedQueryBinding_Level)+ *p = x+ return p+}++func (x SavedQueryBinding_Level) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (SavedQueryBinding_Level) Descriptor() protoreflect.EnumDescriptor {+ return file_store_saved_query_proto_enumTypes[0].Descriptor()+}++func (SavedQueryBinding_Level) Type() protoreflect.EnumType {+ return &file_store_saved_query_proto_enumTypes[0]+}++func (x SavedQueryBinding_Level) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use SavedQueryBinding_Level.Descriptor instead.+func (SavedQueryBinding_Level) EnumDescriptor() ([]byte, []int) {+ return file_store_saved_query_proto_rawDescGZIP(), []int{1, 0}+}+type SavedQueryPayload struct {state protoimpl.MessageState `protogen:"open.v1"`// The connected database, stored as its canonical resource name:@@ -71,13 +120,82 @@ func (x *SavedQueryPayload) GetDatabase() string {return ""}+// One grant on a saved query. Stored in saved_query.bindings, which holds a+// protojson array of these messages at the jsonb root rather than a wrapper+// object, so the `@>` containment probes the access queries run hit the GIN+// index directly.+type SavedQueryBinding struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Level SavedQueryBinding_Level `protobuf:"varint,1,opt,name=level,proto3,enum=bytebase.store.SavedQueryBinding_Level" json:"level,omitempty"`+ // Principals in the same resource-name form the IAM policy payloads use:+ // "users/{email}" and "groups/{email}". The v1 API takes the binding form+ // ("user:", "group:") and converts once on write, as the project policy+ // does. Groups are named by reference and never expanded.+ Members []string `protobuf:"bytes,2,rep,name=members,proto3" json:"members,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SavedQueryBinding) Reset() {+ *x = SavedQueryBinding{}+ mi := &file_store_saved_query_proto_msgTypes[1]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SavedQueryBinding) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SavedQueryBinding) ProtoMessage() {}++func (x *SavedQueryBinding) ProtoReflect() protoreflect.Message {+ mi := &file_store_saved_query_proto_msgTypes[1]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SavedQueryBinding.ProtoReflect.Descriptor instead.+func (*SavedQueryBinding) Descriptor() ([]byte, []int) {+ return file_store_saved_query_proto_rawDescGZIP(), []int{1}+}++func (x *SavedQueryBinding) GetLevel() SavedQueryBinding_Level {+ if x != nil {+ return x.Level+ }+ return SavedQueryBinding_LEVEL_UNSPECIFIED+}++func (x *SavedQueryBinding) GetMembers() []string {+ if x != nil {+ return x.Members+ }+ return nil+}+var File_store_saved_query_proto protoreflect.FileDescriptorconst file_store_saved_query_proto_rawDesc = "" +"\n" +"\x17store/saved_query.proto\x12\x0ebytebase.store\"/\n" +"\x11SavedQueryPayload\x12\x1a\n" +- "\bdatabase\x18\x01 \x01(\tR\bdatabaseB\x92\x01\n" ++ "\bdatabase\x18\x01 \x01(\tR\bdatabase\"\xa4\x01\n" ++ "\x11SavedQueryBinding\x12=\n" ++ "\x05level\x18\x01 \x01(\x0e2'.bytebase.store.SavedQueryBinding.LevelR\x05level\x12\x18\n" ++ "\amembers\x18\x02 \x03(\tR\amembers\"6\n" ++ "\x05Level\x12\x15\n" ++ "\x11LEVEL_UNSPECIFIED\x10\x00\x12\n" ++ "\n" ++ "\x06VIEWER\x10\x01\x12\n" ++ "\n" ++ "\x06EDITOR\x10\x02B\x92\x01\n" +"\x12com.bytebase.storeB\x0fSavedQueryProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"var (@@ -92,16 +210,20 @@ func file_store_saved_query_proto_rawDescGZIP() []byte {return file_store_saved_query_proto_rawDescData}-var file_store_saved_query_proto_msgTypes = make([]protoimpl.MessageInfo, 1)+var file_store_saved_query_proto_enumTypes = make([]protoimpl.EnumInfo, 1)+var file_store_saved_query_proto_msgTypes = make([]protoimpl.MessageInfo, 2)var file_store_saved_query_proto_goTypes = []any{- (*SavedQueryPayload)(nil), // 0: bytebase.store.SavedQueryPayload+ (SavedQueryBinding_Level)(0), // 0: bytebase.store.SavedQueryBinding.Level+ (*SavedQueryPayload)(nil), // 1: bytebase.store.SavedQueryPayload+ (*SavedQueryBinding)(nil), // 2: bytebase.store.SavedQueryBinding}var file_store_saved_query_proto_depIdxs = []int32{- 0, // [0:0] is the sub-list for method output_type- 0, // [0:0] is the sub-list for method input_type- 0, // [0:0] is the sub-list for extension type_name- 0, // [0:0] is the sub-list for extension extendee- 0, // [0:0] is the sub-list for field type_name+ 0, // 0: bytebase.store.SavedQueryBinding.level:type_name -> bytebase.store.SavedQueryBinding.Level+ 1, // [1:1] is the sub-list for method output_type+ 1, // [1:1] is the sub-list for method input_type+ 1, // [1:1] is the sub-list for extension type_name+ 1, // [1:1] is the sub-list for extension extendee+ 0, // [0:1] is the sub-list for field type_name}func init() { file_store_saved_query_proto_init() }@@ -114,13 +236,14 @@ func file_store_saved_query_proto_init() {File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_saved_query_proto_rawDesc), len(file_store_saved_query_proto_rawDesc)),- NumEnums: 0,- NumMessages: 1,+ NumEnums: 1,+ NumMessages: 2,NumExtensions: 0,NumServices: 0,},GoTypes: file_store_saved_query_proto_goTypes,DependencyIndexes: file_store_saved_query_proto_depIdxs,+ EnumInfos: file_store_saved_query_proto_enumTypes,MessageInfos: file_store_saved_query_proto_msgTypes,}.Build()File_store_saved_query_proto = out.Filediff --git a/backend/generated-go/store/saved_query_equal.pb.go b/backend/generated-go/store/saved_query_equal.pb.goindex 4a8603389c..e48ea5a8df 100644--- a/backend/generated-go/store/saved_query_equal.pb.go+++ b/backend/generated-go/store/saved_query_equal.pb.go@@ -15,3 +15,24 @@ func (x *SavedQueryPayload) Equal(y *SavedQueryPayload) bool {}return true}++func (x *SavedQueryBinding) Equal(y *SavedQueryBinding) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Level != y.Level {+ return false+ }+ if len(x.Members) != len(y.Members) {+ return false+ }+ for i := 0; i < len(x.Members); i++ {+ if x.Members[i] != y.Members[i] {+ return false+ }+ }+ return true+}diff --git a/backend/generated-go/v1/saved_query_service.pb.go b/backend/generated-go/v1/saved_query_service.pb.goindex 1bc54c45dd..064acfa096 100644--- a/backend/generated-go/v1/saved_query_service.pb.go+++ b/backend/generated-go/v1/saved_query_service.pb.go@@ -26,9 +26,63 @@ 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.+type SavedQueryBinding_Level int32++const (+ SavedQueryBinding_LEVEL_UNSPECIFIED SavedQueryBinding_Level = 0+ // Open and read the saved query.+ SavedQueryBinding_VIEWER SavedQueryBinding_Level = 1+ // VIEWER, plus write the title, content, and connected database. Sharing+ // and deletion stay with the creator and admins.+ SavedQueryBinding_EDITOR SavedQueryBinding_Level = 2+)++// Enum value maps for SavedQueryBinding_Level.+var (+ SavedQueryBinding_Level_name = map[int32]string{+ 0: "LEVEL_UNSPECIFIED",+ 1: "VIEWER",+ 2: "EDITOR",+ }+ SavedQueryBinding_Level_value = map[string]int32{+ "LEVEL_UNSPECIFIED": 0,+ "VIEWER": 1,+ "EDITOR": 2,+ }+)++func (x SavedQueryBinding_Level) Enum() *SavedQueryBinding_Level {+ p := new(SavedQueryBinding_Level)+ *p = x+ return p+}++func (x SavedQueryBinding_Level) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (SavedQueryBinding_Level) Descriptor() protoreflect.EnumDescriptor {+ return file_v1_saved_query_service_proto_enumTypes[0].Descriptor()+}++func (SavedQueryBinding_Level) Type() protoreflect.EnumType {+ return &file_v1_saved_query_service_proto_enumTypes[0]+}++func (x SavedQueryBinding_Level) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use SavedQueryBinding_Level.Descriptor instead.+func (SavedQueryBinding_Level) EnumDescriptor() ([]byte, []int) {+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{13, 0}+}+type CreateSavedQueryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The parent resource where this saved query will be created.+ // The project to create the saved query in.// Format: projects/{project}Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`// The saved query to create.@@ -83,7 +137,6 @@ func (x *CreateSavedQueryRequest) GetSavedQuery() *SavedQuery {type GetSavedQueryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The name of the saved query to retrieve.// Format: projects/{project}/savedQueries/{savedQuery}Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`unknownFields protoimpl.UnknownFields@@ -129,30 +182,24 @@ func (x *GetSavedQueryRequest) GetName() string {type ListSavedQueriesRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The parent resource of the saved queries.+ // The project to list saved queries in, or "projects/-" for every project.// Format: projects/{project}- // Use "projects/-" to list saved queries across all projects.Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`- // To filter the list result.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Filter the result, in CEL. See https://github.com/google/cel-spec//- // Supported filter:- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ // Supported fields:+ // - creator: the creator in "users/{email}" format. Supports "==" and "!=".//// For example:- // creator == "users/{email}"- // creator != "users/{email}"+ // creator == "users/[email protected]"Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`- // The maximum number of saved queries to return. The service may return fewer than- // this value.- // If unspecified, at most 10 saved queries will be returned.- // The maximum value is 1000; values above 1000 will be coerced to 1000.+ // 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, received from a previous `ListSavedQueries` call.- // Provide this to retrieve the subsequent page.- //- // When paginating, all other parameters provided to `ListSavedQueries` must match- // the call that provided the page token.+ // 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.PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -217,12 +264,10 @@ func (x *ListSavedQueriesRequest) GetPageToken() string {}type ListSavedQueriesResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- // The saved queries from the specified parent.- SavedQueries []*SavedQuery `protobuf:"bytes,1,rep,name=saved_queries,json=savedQueries,proto3" json:"saved_queries,omitempty"`- // A token to retrieve next page of saved queries.- // Pass this value in the page_token field in the subsequent call to- // `ListSavedQueries` method to retrieve the next page of saved queries.+ state protoimpl.MessageState `protogen:"open.v1"`+ SavedQueries []*SavedQuery `protobuf:"bytes,1,rep,name=saved_queries,json=savedQueries,proto3" json:"saved_queries,omitempty"`+ // Pass to the next ListSavedQueries call to fetch the following page. Empty+ // on the last page.NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -274,18 +319,11 @@ func (x *ListSavedQueriesResponse) GetNextPageToken() string {type SearchSavedQueryFoldersRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The parent resource whose saved query folders are searched.// Format: projects/{project}Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`- // To filter the folders by the saved queries they hold. Takes the same- // fields and syntax as `SearchSavedQueries.filter`, except `title`. A- // folder is returned when at least one saved query the caller can read- // matches, so the caller-scoping is the same as SearchSavedQueries: your- // own saved queries, plus everyone's for the admin backstop.- //- // For example, to split a folder tree into your own and everyone else's:- // creator == "users/{email}"- // creator != "users/{email}"+ // Filter folders by the saved queries they hold. Takes the same fields and+ // syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ // when at least one saved query the caller can read matches.Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -337,9 +375,8 @@ func (x *SearchSavedQueryFoldersRequest) GetFilter() string {type SearchSavedQueryFoldersResponse struct {state protoimpl.MessageState `protogen:"open.v1"`- // The caller's folder paths, including every ancestor prefix, sorted.- // A folder is a path on saved queries ("a/b/c"), so empty folders cannot- // exist.+ // Folder paths, every ancestor prefix included, sorted. A folder is a path+ // on saved queries ("a/b/c"), so empty folders cannot exist.Folders []string `protobuf:"bytes,1,rep,name=folders,proto3" json:"folders,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -384,19 +421,11 @@ func (x *SearchSavedQueryFoldersResponse) GetFolders() []string {type UpdateSavedQueryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The saved query to update.- //- // The saved query's `name` field is used to identify the saved query to update.+ // `saved_query.name` identifies the saved query to update.// Format: projects/{project}/savedQueries/{savedQuery}SavedQuery *SavedQuery `protobuf:"bytes,1,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"`- // The list of fields to be updated.- // Fields are specified relative to the saved query.- // (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)- // Only support update the following fields for now:- // - `title`- // - `content`- // - `database`- // - `folder`+ // Fields to update, relative to the saved query (`title`, not+ // `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -448,7 +477,6 @@ func (x *UpdateSavedQueryRequest) GetUpdateMask() *fieldmaskpb.FieldMask {type UpdateSavedQueryStarRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The name of the saved query to star or unstar.// Format: projects/{project}/savedQueries/{savedQuery}Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`// Whether the caller stars the saved query.@@ -503,23 +531,20 @@ func (x *UpdateSavedQueryStarRequest) GetStarred() bool {type BatchUpdateSavedQueriesRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The parent resource whose saved queries are updated.// Format: projects/{project}Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`- // To filter the batch update target.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Select the saved queries to update, in CEL. See+ // https://github.com/google/cel-spec//- // Supported filter:- // - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- // - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- // - folder: the saved query folder path, support exact "==" operator.+ // Supported fields:+ // - name: the saved query name. Supports "==" and "in [...]".+ // - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ // - starred: whether the caller starred it. Supports "==".+ // - folder: the exact folder path. Supports "==".Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`- // The fields to apply to every matched saved query.+ // The values to apply to every matched saved query.SavedQuery *SavedQuery `protobuf:"bytes,3,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"`- // The list of fields to be updated.- // Only support update the following fields for now:- // - `folder`+ // Fields to update. Supported: `folder`.UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,4,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -585,7 +610,8 @@ func (x *BatchUpdateSavedQueriesRequest) GetUpdateMask() *fieldmaskpb.FieldMasktype BatchUpdateSavedQueriesResponse struct {state protoimpl.MessageState `protogen:"open.v1"`- // The number of saved queries updated.+ // How many saved queries were updated, which may be fewer than the filter+ // matched.UpdatedCount int32 `protobuf:"varint,1,opt,name=updated_count,json=updatedCount,proto3" json:"updated_count,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -628,9 +654,233 @@ func (x *BatchUpdateSavedQueriesResponse) GetUpdatedCount() int32 {return 0}+type GetSavedQueryPolicyRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Format: projects/{project}/savedQueries/{savedQuery}+ Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetSavedQueryPolicyRequest) Reset() {+ *x = GetSavedQueryPolicyRequest{}+ mi := &file_v1_saved_query_service_proto_msgTypes[10]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetSavedQueryPolicyRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetSavedQueryPolicyRequest) ProtoMessage() {}++func (x *GetSavedQueryPolicyRequest) ProtoReflect() protoreflect.Message {+ mi := &file_v1_saved_query_service_proto_msgTypes[10]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetSavedQueryPolicyRequest.ProtoReflect.Descriptor instead.+func (*GetSavedQueryPolicyRequest) Descriptor() ([]byte, []int) {+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{10}+}++func (x *GetSavedQueryPolicyRequest) GetResource() string {+ if x != nil {+ return x.Resource+ }+ return ""+}++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.+ Policy *SavedQueryPolicy `protobuf:"bytes,2,opt,name=policy,proto3" json:"policy,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SetSavedQueryPolicyRequest) Reset() {+ *x = SetSavedQueryPolicyRequest{}+ mi := &file_v1_saved_query_service_proto_msgTypes[11]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SetSavedQueryPolicyRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SetSavedQueryPolicyRequest) ProtoMessage() {}++func (x *SetSavedQueryPolicyRequest) ProtoReflect() protoreflect.Message {+ mi := &file_v1_saved_query_service_proto_msgTypes[11]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SetSavedQueryPolicyRequest.ProtoReflect.Descriptor instead.+func (*SetSavedQueryPolicyRequest) Descriptor() ([]byte, []int) {+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{11}+}++func (x *SetSavedQueryPolicyRequest) GetResource() string {+ if x != nil {+ return x.Resource+ }+ return ""+}++func (x *SetSavedQueryPolicyRequest) GetPolicy() *SavedQueryPolicy {+ if x != nil {+ return x.Policy+ }+ 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.+type SavedQueryPolicy struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // At most one binding per level. A member listed under two levels is+ // rejected rather than resolved to the higher one.+ Bindings []*SavedQueryBinding `protobuf:"bytes,1,rep,name=bindings,proto3" json:"bindings,omitempty"`+ // The etag of the policy as read. SetSavedQueryPolicy requires it and fails+ // with ABORTED when it no longer matches.+ Etag string `protobuf:"bytes,2,opt,name=etag,proto3" json:"etag,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SavedQueryPolicy) Reset() {+ *x = SavedQueryPolicy{}+ mi := &file_v1_saved_query_service_proto_msgTypes[12]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SavedQueryPolicy) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SavedQueryPolicy) ProtoMessage() {}++func (x *SavedQueryPolicy) ProtoReflect() protoreflect.Message {+ mi := &file_v1_saved_query_service_proto_msgTypes[12]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SavedQueryPolicy.ProtoReflect.Descriptor instead.+func (*SavedQueryPolicy) Descriptor() ([]byte, []int) {+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{12}+}++func (x *SavedQueryPolicy) GetBindings() []*SavedQueryBinding {+ if x != nil {+ return x.Bindings+ }+ return nil+}++func (x *SavedQueryPolicy) GetEtag() string {+ if x != nil {+ return x.Etag+ }+ 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.+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.+ //+ // 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.+ Members []string `protobuf:"bytes,2,rep,name=members,proto3" json:"members,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SavedQueryBinding) Reset() {+ *x = SavedQueryBinding{}+ mi := &file_v1_saved_query_service_proto_msgTypes[13]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SavedQueryBinding) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SavedQueryBinding) ProtoMessage() {}++func (x *SavedQueryBinding) ProtoReflect() protoreflect.Message {+ mi := &file_v1_saved_query_service_proto_msgTypes[13]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SavedQueryBinding.ProtoReflect.Descriptor instead.+func (*SavedQueryBinding) Descriptor() ([]byte, []int) {+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{13}+}++func (x *SavedQueryBinding) GetLevel() SavedQueryBinding_Level {+ if x != nil {+ return x.Level+ }+ return SavedQueryBinding_LEVEL_UNSPECIFIED+}++func (x *SavedQueryBinding) GetMembers() []string {+ if x != nil {+ return x.Members+ }+ return nil+}+type DeleteSavedQueryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The name of the saved query to delete.// Format: projects/{project}/savedQueries/{savedQuery}Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`unknownFields protoimpl.UnknownFields@@ -639,7 +889,7 @@ type DeleteSavedQueryRequest struct {func (x *DeleteSavedQueryRequest) Reset() {*x = DeleteSavedQueryRequest{}- mi := &file_v1_saved_query_service_proto_msgTypes[10]+ mi := &file_v1_saved_query_service_proto_msgTypes[14]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -651,7 +901,7 @@ func (x *DeleteSavedQueryRequest) String() string {func (*DeleteSavedQueryRequest) ProtoMessage() {}func (x *DeleteSavedQueryRequest) ProtoReflect() protoreflect.Message {- mi := &file_v1_saved_query_service_proto_msgTypes[10]+ mi := &file_v1_saved_query_service_proto_msgTypes[14]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -664,7 +914,7 @@ func (x *DeleteSavedQueryRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use DeleteSavedQueryRequest.ProtoReflect.Descriptor instead.func (*DeleteSavedQueryRequest) Descriptor() ([]byte, []int) {- return file_v1_saved_query_service_proto_rawDescGZIP(), []int{10}+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{14}}func (x *DeleteSavedQueryRequest) GetName() string {@@ -676,34 +926,40 @@ func (x *DeleteSavedQueryRequest) GetName() string {type SearchSavedQueriesRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // The parent resource of the saved queries.// Format: projects/{project}Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"`- // To filter the search result.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Filter the result, in CEL. See https://github.com/google/cel-spec+ //+ // Supported fields:+ // - 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 "==".+ // - starred: whether the caller starred it. Supports "==".+ // - folder: the exact folder path. Supports "==".//- // Supported filter:- // - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- // - title: the saved query title, support "contains" operator.- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- // - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- // - folder: the saved query folder path, support "==" operator.+ // 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.//// For example:- // creator == "users/{email}"- // title.contains("saved query title")- // creator != "users/{email}"+ // creator == "users/[email protected]"+ // shared == true// starred == true- // starred == false+ // title.contains("weekly report")// folder == "foo/bar"Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`- // The maximum number of saved queries to return. The service may return fewer than- // this value.- // If unspecified, at most 10 saved queries will be returned.- // The maximum value is 1000; values above 1000 will be coerced to 1000.+ // 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, received from a previous `SearchSavedQueries` call.- // Provide this to retrieve the subsequent page.+ // 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.PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -711,7 +967,7 @@ type SearchSavedQueriesRequest struct {func (x *SearchSavedQueriesRequest) Reset() {*x = SearchSavedQueriesRequest{}- mi := &file_v1_saved_query_service_proto_msgTypes[11]+ mi := &file_v1_saved_query_service_proto_msgTypes[15]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -723,7 +979,7 @@ func (x *SearchSavedQueriesRequest) String() string {func (*SearchSavedQueriesRequest) ProtoMessage() {}func (x *SearchSavedQueriesRequest) ProtoReflect() protoreflect.Message {- mi := &file_v1_saved_query_service_proto_msgTypes[11]+ mi := &file_v1_saved_query_service_proto_msgTypes[15]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -736,7 +992,7 @@ func (x *SearchSavedQueriesRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use SearchSavedQueriesRequest.ProtoReflect.Descriptor instead.func (*SearchSavedQueriesRequest) Descriptor() ([]byte, []int) {- return file_v1_saved_query_service_proto_rawDescGZIP(), []int{11}+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{15}}func (x *SearchSavedQueriesRequest) GetParent() string {@@ -768,12 +1024,10 @@ func (x *SearchSavedQueriesRequest) GetPageToken() string {}type SearchSavedQueriesResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- // The saved queries that matched the search criteria.- SavedQueries []*SavedQuery `protobuf:"bytes,1,rep,name=saved_queries,json=savedQueries,proto3" json:"saved_queries,omitempty"`- // A token to retrieve next page of saved queries.- // Pass this value in the page_token field in the subsequent call to- // `SearchSavedQueries` method to retrieve the next page of saved queries.+ state protoimpl.MessageState `protogen:"open.v1"`+ SavedQueries []*SavedQuery `protobuf:"bytes,1,rep,name=saved_queries,json=savedQueries,proto3" json:"saved_queries,omitempty"`+ // Pass to the next SearchSavedQueries call to fetch the following page.+ // Empty on the last page.NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -781,7 +1035,7 @@ type SearchSavedQueriesResponse struct {func (x *SearchSavedQueriesResponse) Reset() {*x = SearchSavedQueriesResponse{}- mi := &file_v1_saved_query_service_proto_msgTypes[12]+ mi := &file_v1_saved_query_service_proto_msgTypes[16]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -793,7 +1047,7 @@ func (x *SearchSavedQueriesResponse) String() string {func (*SearchSavedQueriesResponse) ProtoMessage() {}func (x *SearchSavedQueriesResponse) ProtoReflect() protoreflect.Message {- mi := &file_v1_saved_query_service_proto_msgTypes[12]+ mi := &file_v1_saved_query_service_proto_msgTypes[16]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -806,7 +1060,7 @@ func (x *SearchSavedQueriesResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use SearchSavedQueriesResponse.ProtoReflect.Descriptor instead.func (*SearchSavedQueriesResponse) Descriptor() ([]byte, []int) {- return file_v1_saved_query_service_proto_rawDescGZIP(), []int{12}+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{16}}func (x *SearchSavedQueriesResponse) GetSavedQueries() []*SavedQuery {@@ -825,38 +1079,32 @@ func (x *SearchSavedQueriesResponse) GetNextPageToken() string {type SavedQuery struct {state protoimpl.MessageState `protogen:"open.v1"`- // The name of the saved query resource, generated by the server.- // Canonical parent is project.+ // Server-generated.// Format: projects/{project}/savedQueries/{savedQuery}Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`- // The project resource name.// Format: projects/{project}Project string `protobuf:"bytes,2,opt,name=project,proto3" json:"project,omitempty"`- // The database resource name.+ // The connected database, which must belong to the saved query's own+ // project. Empty when none is connected, or when the database no longer+ // exists.// Format: instances/{instance}/databases/{database}- // If the database parent doesn't exist, the database field is empty.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 creator of the SavedQuery — the fixed owner; ownership does not- // transfer.+ // The fixed owner. Ownership does not transfer.// Format: users/{email}- Creator string `protobuf:"bytes,5,opt,name=creator,proto3" json:"creator,omitempty"`- // The create time of the saved query.+ 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"`- // The last update time of the saved query.UpdateTime *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`- // The content of the saved query.- // By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can- // use GetSavedQuery() request to retrieve the full content.+ // The SQL text. SearchSavedQueries truncates it; when it is shorter than+ // `content_size`, GetSavedQuery returns the whole thing.Content []byte `protobuf:"bytes,8,opt,name=content,proto3" json:"content,omitempty"`- // content_size is the full size of the content, may not match the size of the `content` field.+ // 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"`- // starred indicates whether the saved query is starred by the current authenticated user.+ // Whether the calling user starred it.Starred bool `protobuf:"varint,11,opt,name=starred,proto3" json:"starred,omitempty"`- // The folder path this saved query lives in, set by its creator (or an- // admin). Empty means unfiled. A saved query lives in exactly one folder;- // a folder is a path on saved queries, e.g. "a/b/c".+ // The folder holding this saved query, set by its creator or an admin. A+ // path like "a/b/c"; empty means unfiled.Folder string `protobuf:"bytes,13,opt,name=folder,proto3" json:"folder,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -864,7 +1112,7 @@ type SavedQuery struct {func (x *SavedQuery) Reset() {*x = SavedQuery{}- mi := &file_v1_saved_query_service_proto_msgTypes[13]+ mi := &file_v1_saved_query_service_proto_msgTypes[17]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -876,7 +1124,7 @@ func (x *SavedQuery) String() string {func (*SavedQuery) ProtoMessage() {}func (x *SavedQuery) ProtoReflect() protoreflect.Message {- mi := &file_v1_saved_query_service_proto_msgTypes[13]+ mi := &file_v1_saved_query_service_proto_msgTypes[17]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -889,7 +1137,7 @@ func (x *SavedQuery) ProtoReflect() protoreflect.Message {// Deprecated: Use SavedQuery.ProtoReflect.Descriptor instead.func (*SavedQuery) Descriptor() ([]byte, []int) {- return file_v1_saved_query_service_proto_rawDescGZIP(), []int{13}+ return file_v1_saved_query_service_proto_rawDescGZIP(), []int{17}}func (x *SavedQuery) GetName() string {@@ -1014,7 +1262,26 @@ const file_v1_saved_query_service_proto_rawDesc = "" +"\vupdate_mask\x18\x04 \x01(\v2\x1a.google.protobuf.FieldMaskB\x03\xe0A\x02R\n" +"updateMask\"F\n" +"\x1fBatchUpdateSavedQueriesResponse\x12#\n" +- "\rupdated_count\x18\x01 \x01(\x05R\fupdatedCount\"N\n" ++ "\rupdated_count\x18\x01 \x01(\x05R\fupdatedCount\"Y\n" ++ "\x1aGetSavedQueryPolicyRequest\x12;\n" ++ "\bresource\x18\x01 \x01(\tB\x1f\xe0A\x02\xfaA\x19\n" ++ "\x17bytebase.com/SavedQueryR\bresource\"\x95\x01\n" ++ "\x1aSetSavedQueryPolicyRequest\x12;\n" ++ "\bresource\x18\x01 \x01(\tB\x1f\xe0A\x02\xfaA\x19\n" ++ "\x17bytebase.com/SavedQueryR\bresource\x12:\n" ++ "\x06policy\x18\x02 \x01(\v2\x1d.bytebase.v1.SavedQueryPolicyB\x03\xe0A\x02R\x06policy\"b\n" ++ "\x10SavedQueryPolicy\x12:\n" ++ "\bbindings\x18\x01 \x03(\v2\x1e.bytebase.v1.SavedQueryBindingR\bbindings\x12\x12\n" ++ "\x04etag\x18\x02 \x01(\tR\x04etag\"\xb3\x01\n" ++ "\x11SavedQueryBinding\x12?\n" ++ "\x05level\x18\x01 \x01(\x0e2$.bytebase.v1.SavedQueryBinding.LevelB\x03\xe0A\x02R\x05level\x12%\n" ++ "\amembers\x18\x02 \x03(\tB\v\xe0A\x02\xbaH\x05\x92\x01\x02\b\x01R\amembers\"6\n" ++ "\x05Level\x12\x15\n" ++ "\x11LEVEL_UNSPECIFIED\x10\x00\x12\n" ++ "\n" ++ "\x06VIEWER\x10\x01\x12\n" ++ "\n" ++ "\x06EDITOR\x10\x02\"N\n" +"\x17DeleteSavedQueryRequest\x123\n" +"\x04name\x18\x01 \x01(\tB\x1f\xe0A\x02\xfaA\x19\n" +"\x17bytebase.com/SavedQueryR\x04name\"\xa5\x01\n" +@@ -1027,7 +1294,7 @@ const file_v1_saved_query_service_proto_rawDesc = "" +"page_token\x18\x04 \x01(\tR\tpageToken\"\x82\x01\n" +"\x1aSearchSavedQueriesResponse\x12<\n" +"\rsaved_queries\x18\x01 \x03(\v2\x17.bytebase.v1.SavedQueryR\fsavedQueries\x12&\n" +- "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x9f\x04\n" ++ "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x8a\x04\n" +"\n" +"SavedQuery\x12\x1a\n" +"\x04name\x18\x01 \x01(\tB\x06\xe0A\x02\xe0A\x05R\x04name\x12\x1d\n" +@@ -1044,8 +1311,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\rR\n" +- "visibilityR\afolders2\xda\f\n" ++ "\x10\vJ\x04\b\f\x10\r2\xbe\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" +@@ -1055,7 +1321,9 @@ const file_v1_saved_query_service_proto_rawDesc = "" +"\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\xda\x01\n" +"\x17BatchUpdateSavedQueries\x12+.bytebase.v1.BatchUpdateSavedQueriesRequest\x1a,.bytebase.v1.BatchUpdateSavedQueriesResponse\"d\xdaA\x1eparent,saved_query,update_mask\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x025:\x01*\"0/v1/{parent=projects/*}/savedQueries:batchUpdate\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/*}B\xac\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" +"\x0fcom.bytebase.v1B\x16SavedQueryServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"var (@@ -1070,59 +1338,72 @@ func file_v1_saved_query_service_proto_rawDescGZIP() []byte {return file_v1_saved_query_service_proto_rawDescData}-var file_v1_saved_query_service_proto_msgTypes = make([]protoimpl.MessageInfo, 14)+var file_v1_saved_query_service_proto_enumTypes = make([]protoimpl.EnumInfo, 1)+var file_v1_saved_query_service_proto_msgTypes = make([]protoimpl.MessageInfo, 18)var file_v1_saved_query_service_proto_goTypes = []any{- (*CreateSavedQueryRequest)(nil), // 0: bytebase.v1.CreateSavedQueryRequest- (*GetSavedQueryRequest)(nil), // 1: bytebase.v1.GetSavedQueryRequest- (*ListSavedQueriesRequest)(nil), // 2: bytebase.v1.ListSavedQueriesRequest- (*ListSavedQueriesResponse)(nil), // 3: bytebase.v1.ListSavedQueriesResponse- (*SearchSavedQueryFoldersRequest)(nil), // 4: bytebase.v1.SearchSavedQueryFoldersRequest- (*SearchSavedQueryFoldersResponse)(nil), // 5: bytebase.v1.SearchSavedQueryFoldersResponse- (*UpdateSavedQueryRequest)(nil), // 6: bytebase.v1.UpdateSavedQueryRequest- (*UpdateSavedQueryStarRequest)(nil), // 7: bytebase.v1.UpdateSavedQueryStarRequest- (*BatchUpdateSavedQueriesRequest)(nil), // 8: bytebase.v1.BatchUpdateSavedQueriesRequest- (*BatchUpdateSavedQueriesResponse)(nil), // 9: bytebase.v1.BatchUpdateSavedQueriesResponse- (*DeleteSavedQueryRequest)(nil), // 10: bytebase.v1.DeleteSavedQueryRequest- (*SearchSavedQueriesRequest)(nil), // 11: bytebase.v1.SearchSavedQueriesRequest- (*SearchSavedQueriesResponse)(nil), // 12: bytebase.v1.SearchSavedQueriesResponse- (*SavedQuery)(nil), // 13: bytebase.v1.SavedQuery- (*fieldmaskpb.FieldMask)(nil), // 14: google.protobuf.FieldMask- (*timestamppb.Timestamp)(nil), // 15: google.protobuf.Timestamp- (*emptypb.Empty)(nil), // 16: google.protobuf.Empty+ (SavedQueryBinding_Level)(0), // 0: bytebase.v1.SavedQueryBinding.Level+ (*CreateSavedQueryRequest)(nil), // 1: bytebase.v1.CreateSavedQueryRequest+ (*GetSavedQueryRequest)(nil), // 2: bytebase.v1.GetSavedQueryRequest+ (*ListSavedQueriesRequest)(nil), // 3: bytebase.v1.ListSavedQueriesRequest+ (*ListSavedQueriesResponse)(nil), // 4: bytebase.v1.ListSavedQueriesResponse+ (*SearchSavedQueryFoldersRequest)(nil), // 5: bytebase.v1.SearchSavedQueryFoldersRequest+ (*SearchSavedQueryFoldersResponse)(nil), // 6: bytebase.v1.SearchSavedQueryFoldersResponse+ (*UpdateSavedQueryRequest)(nil), // 7: bytebase.v1.UpdateSavedQueryRequest+ (*UpdateSavedQueryStarRequest)(nil), // 8: bytebase.v1.UpdateSavedQueryStarRequest+ (*BatchUpdateSavedQueriesRequest)(nil), // 9: bytebase.v1.BatchUpdateSavedQueriesRequest+ (*BatchUpdateSavedQueriesResponse)(nil), // 10: bytebase.v1.BatchUpdateSavedQueriesResponse+ (*GetSavedQueryPolicyRequest)(nil), // 11: bytebase.v1.GetSavedQueryPolicyRequest+ (*SetSavedQueryPolicyRequest)(nil), // 12: bytebase.v1.SetSavedQueryPolicyRequest+ (*SavedQueryPolicy)(nil), // 13: bytebase.v1.SavedQueryPolicy+ (*SavedQueryBinding)(nil), // 14: bytebase.v1.SavedQueryBinding+ (*DeleteSavedQueryRequest)(nil), // 15: bytebase.v1.DeleteSavedQueryRequest+ (*SearchSavedQueriesRequest)(nil), // 16: bytebase.v1.SearchSavedQueriesRequest+ (*SearchSavedQueriesResponse)(nil), // 17: bytebase.v1.SearchSavedQueriesResponse+ (*SavedQuery)(nil), // 18: bytebase.v1.SavedQuery+ (*fieldmaskpb.FieldMask)(nil), // 19: google.protobuf.FieldMask+ (*timestamppb.Timestamp)(nil), // 20: google.protobuf.Timestamp+ (*emptypb.Empty)(nil), // 21: google.protobuf.Empty}var file_v1_saved_query_service_proto_depIdxs = []int32{- 13, // 0: bytebase.v1.CreateSavedQueryRequest.saved_query:type_name -> bytebase.v1.SavedQuery- 13, // 1: bytebase.v1.ListSavedQueriesResponse.saved_queries:type_name -> bytebase.v1.SavedQuery- 13, // 2: bytebase.v1.UpdateSavedQueryRequest.saved_query:type_name -> bytebase.v1.SavedQuery- 14, // 3: bytebase.v1.UpdateSavedQueryRequest.update_mask:type_name -> google.protobuf.FieldMask- 13, // 4: bytebase.v1.BatchUpdateSavedQueriesRequest.saved_query:type_name -> bytebase.v1.SavedQuery- 14, // 5: bytebase.v1.BatchUpdateSavedQueriesRequest.update_mask:type_name -> google.protobuf.FieldMask- 13, // 6: bytebase.v1.SearchSavedQueriesResponse.saved_queries:type_name -> bytebase.v1.SavedQuery- 15, // 7: bytebase.v1.SavedQuery.create_time:type_name -> google.protobuf.Timestamp- 15, // 8: bytebase.v1.SavedQuery.update_time:type_name -> google.protobuf.Timestamp- 0, // 9: bytebase.v1.SavedQueryService.CreateSavedQuery:input_type -> bytebase.v1.CreateSavedQueryRequest- 1, // 10: bytebase.v1.SavedQueryService.GetSavedQuery:input_type -> bytebase.v1.GetSavedQueryRequest- 2, // 11: bytebase.v1.SavedQueryService.ListSavedQueries:input_type -> bytebase.v1.ListSavedQueriesRequest- 11, // 12: bytebase.v1.SavedQueryService.SearchSavedQueries:input_type -> bytebase.v1.SearchSavedQueriesRequest- 4, // 13: bytebase.v1.SavedQueryService.SearchSavedQueryFolders:input_type -> bytebase.v1.SearchSavedQueryFoldersRequest- 6, // 14: bytebase.v1.SavedQueryService.UpdateSavedQuery:input_type -> bytebase.v1.UpdateSavedQueryRequest- 7, // 15: bytebase.v1.SavedQueryService.UpdateSavedQueryStar:input_type -> bytebase.v1.UpdateSavedQueryStarRequest- 8, // 16: bytebase.v1.SavedQueryService.BatchUpdateSavedQueries:input_type -> bytebase.v1.BatchUpdateSavedQueriesRequest- 10, // 17: bytebase.v1.SavedQueryService.DeleteSavedQuery:input_type -> bytebase.v1.DeleteSavedQueryRequest- 13, // 18: bytebase.v1.SavedQueryService.CreateSavedQuery:output_type -> bytebase.v1.SavedQuery- 13, // 19: bytebase.v1.SavedQueryService.GetSavedQuery:output_type -> bytebase.v1.SavedQuery- 3, // 20: bytebase.v1.SavedQueryService.ListSavedQueries:output_type -> bytebase.v1.ListSavedQueriesResponse- 12, // 21: bytebase.v1.SavedQueryService.SearchSavedQueries:output_type -> bytebase.v1.SearchSavedQueriesResponse- 5, // 22: bytebase.v1.SavedQueryService.SearchSavedQueryFolders:output_type -> bytebase.v1.SearchSavedQueryFoldersResponse- 13, // 23: bytebase.v1.SavedQueryService.UpdateSavedQuery:output_type -> bytebase.v1.SavedQuery- 13, // 24: bytebase.v1.SavedQueryService.UpdateSavedQueryStar:output_type -> bytebase.v1.SavedQuery- 9, // 25: bytebase.v1.SavedQueryService.BatchUpdateSavedQueries:output_type -> bytebase.v1.BatchUpdateSavedQueriesResponse- 16, // 26: bytebase.v1.SavedQueryService.DeleteSavedQuery:output_type -> google.protobuf.Empty- 18, // [18:27] is the sub-list for method output_type- 9, // [9:18] is the sub-list for method input_type- 9, // [9:9] is the sub-list for extension type_name- 9, // [9:9] is the sub-list for extension extendee- 0, // [0:9] is the sub-list for field type_name+ 18, // 0: bytebase.v1.CreateSavedQueryRequest.saved_query:type_name -> bytebase.v1.SavedQuery+ 18, // 1: bytebase.v1.ListSavedQueriesResponse.saved_queries:type_name -> bytebase.v1.SavedQuery+ 18, // 2: bytebase.v1.UpdateSavedQueryRequest.saved_query:type_name -> bytebase.v1.SavedQuery+ 19, // 3: bytebase.v1.UpdateSavedQueryRequest.update_mask:type_name -> google.protobuf.FieldMask+ 18, // 4: bytebase.v1.BatchUpdateSavedQueriesRequest.saved_query:type_name -> bytebase.v1.SavedQuery+ 19, // 5: bytebase.v1.BatchUpdateSavedQueriesRequest.update_mask:type_name -> google.protobuf.FieldMask+ 13, // 6: bytebase.v1.SetSavedQueryPolicyRequest.policy:type_name -> bytebase.v1.SavedQueryPolicy+ 14, // 7: bytebase.v1.SavedQueryPolicy.bindings:type_name -> bytebase.v1.SavedQueryBinding+ 0, // 8: bytebase.v1.SavedQueryBinding.level:type_name -> bytebase.v1.SavedQueryBinding.Level+ 18, // 9: bytebase.v1.SearchSavedQueriesResponse.saved_queries:type_name -> bytebase.v1.SavedQuery+ 20, // 10: bytebase.v1.SavedQuery.create_time:type_name -> google.protobuf.Timestamp+ 20, // 11: bytebase.v1.SavedQuery.update_time:type_name -> google.protobuf.Timestamp+ 1, // 12: bytebase.v1.SavedQueryService.CreateSavedQuery:input_type -> bytebase.v1.CreateSavedQueryRequest+ 2, // 13: bytebase.v1.SavedQueryService.GetSavedQuery:input_type -> bytebase.v1.GetSavedQueryRequest+ 3, // 14: bytebase.v1.SavedQueryService.ListSavedQueries:input_type -> bytebase.v1.ListSavedQueriesRequest+ 16, // 15: bytebase.v1.SavedQueryService.SearchSavedQueries:input_type -> bytebase.v1.SearchSavedQueriesRequest+ 5, // 16: bytebase.v1.SavedQueryService.SearchSavedQueryFolders:input_type -> bytebase.v1.SearchSavedQueryFoldersRequest+ 7, // 17: bytebase.v1.SavedQueryService.UpdateSavedQuery:input_type -> bytebase.v1.UpdateSavedQueryRequest+ 8, // 18: bytebase.v1.SavedQueryService.UpdateSavedQueryStar:input_type -> bytebase.v1.UpdateSavedQueryStarRequest+ 9, // 19: bytebase.v1.SavedQueryService.BatchUpdateSavedQueries:input_type -> bytebase.v1.BatchUpdateSavedQueriesRequest+ 15, // 20: bytebase.v1.SavedQueryService.DeleteSavedQuery:input_type -> bytebase.v1.DeleteSavedQueryRequest+ 11, // 21: bytebase.v1.SavedQueryService.GetSavedQueryPolicy:input_type -> bytebase.v1.GetSavedQueryPolicyRequest+ 12, // 22: bytebase.v1.SavedQueryService.SetSavedQueryPolicy:input_type -> bytebase.v1.SetSavedQueryPolicyRequest+ 18, // 23: bytebase.v1.SavedQueryService.CreateSavedQuery:output_type -> bytebase.v1.SavedQuery+ 18, // 24: bytebase.v1.SavedQueryService.GetSavedQuery:output_type -> bytebase.v1.SavedQuery+ 4, // 25: bytebase.v1.SavedQueryService.ListSavedQueries:output_type -> bytebase.v1.ListSavedQueriesResponse+ 17, // 26: bytebase.v1.SavedQueryService.SearchSavedQueries:output_type -> bytebase.v1.SearchSavedQueriesResponse+ 6, // 27: bytebase.v1.SavedQueryService.SearchSavedQueryFolders:output_type -> bytebase.v1.SearchSavedQueryFoldersResponse+ 18, // 28: bytebase.v1.SavedQueryService.UpdateSavedQuery:output_type -> bytebase.v1.SavedQuery+ 18, // 29: bytebase.v1.SavedQueryService.UpdateSavedQueryStar:output_type -> bytebase.v1.SavedQuery+ 10, // 30: bytebase.v1.SavedQueryService.BatchUpdateSavedQueries:output_type -> bytebase.v1.BatchUpdateSavedQueriesResponse+ 21, // 31: bytebase.v1.SavedQueryService.DeleteSavedQuery:output_type -> google.protobuf.Empty+ 13, // 32: bytebase.v1.SavedQueryService.GetSavedQueryPolicy:output_type -> bytebase.v1.SavedQueryPolicy+ 13, // 33: bytebase.v1.SavedQueryService.SetSavedQueryPolicy:output_type -> bytebase.v1.SavedQueryPolicy+ 23, // [23:34] is the sub-list for method output_type+ 12, // [12:23] is the sub-list for method input_type+ 12, // [12:12] is the sub-list for extension type_name+ 12, // [12:12] is the sub-list for extension extendee+ 0, // [0:12] is the sub-list for field type_name}func init() { file_v1_saved_query_service_proto_init() }@@ -1136,13 +1417,14 @@ func file_v1_saved_query_service_proto_init() {File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_saved_query_service_proto_rawDesc), len(file_v1_saved_query_service_proto_rawDesc)),- NumEnums: 0,- NumMessages: 14,+ NumEnums: 1,+ NumMessages: 18,NumExtensions: 0,NumServices: 1,},GoTypes: file_v1_saved_query_service_proto_goTypes,DependencyIndexes: file_v1_saved_query_service_proto_depIdxs,+ EnumInfos: file_v1_saved_query_service_proto_enumTypes,MessageInfos: file_v1_saved_query_service_proto_msgTypes,}.Build()File_v1_saved_query_service_proto = out.Filediff --git a/backend/generated-go/v1/saved_query_service.pb.gw.go b/backend/generated-go/v1/saved_query_service.pb.gw.goindex 9ba6cd6d00..03732a6a7a 100644--- a/backend/generated-go/v1/saved_query_service.pb.gw.go+++ b/backend/generated-go/v1/saved_query_service.pb.gw.go@@ -472,6 +472,90 @@ func local_request_SavedQueryService_DeleteSavedQuery_0(ctx context.Context, marreturn msg, metadata, err}+func request_SavedQueryService_GetSavedQueryPolicy_0(ctx context.Context, marshaler runtime.Marshaler, client SavedQueryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq GetSavedQueryPolicyRequest+ metadata runtime.ServerMetadata+ err error+ )+ val, ok := pathParams["resource"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "resource")+ }+ protoReq.Resource, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "resource", err)+ }+ if req.Body != nil {+ _, _ = io.Copy(io.Discard, req.Body)+ }+ msg, err := client.GetSavedQueryPolicy(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err+}++func local_request_SavedQueryService_GetSavedQueryPolicy_0(ctx context.Context, marshaler runtime.Marshaler, server SavedQueryServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq GetSavedQueryPolicyRequest+ metadata runtime.ServerMetadata+ err error+ )+ val, ok := pathParams["resource"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "resource")+ }+ protoReq.Resource, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "resource", err)+ }+ msg, err := server.GetSavedQueryPolicy(ctx, &protoReq)+ return msg, metadata, err+}++func request_SavedQueryService_SetSavedQueryPolicy_0(ctx context.Context, marshaler runtime.Marshaler, client SavedQueryServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq SetSavedQueryPolicyRequest+ metadata runtime.ServerMetadata+ err error+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ val, ok := pathParams["resource"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "resource")+ }+ protoReq.Resource, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "resource", err)+ }+ if req.Body != nil {+ _, _ = io.Copy(io.Discard, req.Body)+ }+ msg, err := client.SetSavedQueryPolicy(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err+}++func local_request_SavedQueryService_SetSavedQueryPolicy_0(ctx context.Context, marshaler runtime.Marshaler, server SavedQueryServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq SetSavedQueryPolicyRequest+ metadata runtime.ServerMetadata+ err error+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ val, ok := pathParams["resource"]+ if !ok {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "resource")+ }+ protoReq.Resource, err = runtime.String(val)+ if err != nil {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "resource", err)+ }+ msg, err := server.SetSavedQueryPolicy(ctx, &protoReq)+ return msg, metadata, err+}+// RegisterSavedQueryServiceHandlerServer registers the http handlers for service SavedQueryService to "mux".// UnaryRPC :call SavedQueryServiceServer directly.// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.@@ -658,6 +742,46 @@ func RegisterSavedQueryServiceHandlerServer(ctx context.Context, mux *runtime.Se}forward_SavedQueryService_DeleteSavedQuery_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodGet, pattern_SavedQueryService_GetSavedQueryPolicy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SavedQueryService/GetSavedQueryPolicy", runtime.WithHTTPPathPattern("/v1/{resource=projects/*/savedQueries/*}:getPolicy"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_SavedQueryService_GetSavedQueryPolicy_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SavedQueryService_GetSavedQueryPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })+ mux.Handle(http.MethodPost, pattern_SavedQueryService_SetSavedQueryPolicy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.SavedQueryService/SetSavedQueryPolicy", runtime.WithHTTPPathPattern("/v1/{resource=projects/*/savedQueries/*}:setPolicy"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_SavedQueryService_SetSavedQueryPolicy_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SavedQueryService_SetSavedQueryPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })return nil}@@ -851,6 +975,40 @@ func RegisterSavedQueryServiceHandlerClient(ctx context.Context, mux *runtime.Se}forward_SavedQueryService_DeleteSavedQuery_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodGet, pattern_SavedQueryService_GetSavedQueryPolicy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SavedQueryService/GetSavedQueryPolicy", runtime.WithHTTPPathPattern("/v1/{resource=projects/*/savedQueries/*}:getPolicy"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_SavedQueryService_GetSavedQueryPolicy_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SavedQueryService_GetSavedQueryPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })+ mux.Handle(http.MethodPost, pattern_SavedQueryService_SetSavedQueryPolicy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.SavedQueryService/SetSavedQueryPolicy", runtime.WithHTTPPathPattern("/v1/{resource=projects/*/savedQueries/*}:setPolicy"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_SavedQueryService_SetSavedQueryPolicy_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_SavedQueryService_SetSavedQueryPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })return nil}@@ -864,6 +1022,8 @@ var (pattern_SavedQueryService_UpdateSavedQueryStar_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "projects", "savedQueries", "name"}, "updateStar"))pattern_SavedQueryService_BatchUpdateSavedQueries_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2, 2, 3}, []string{"v1", "projects", "parent", "savedQueries"}, "batchUpdate"))pattern_SavedQueryService_DeleteSavedQuery_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "projects", "savedQueries", "name"}, ""))+ pattern_SavedQueryService_GetSavedQueryPolicy_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "projects", "savedQueries", "resource"}, "getPolicy"))+ pattern_SavedQueryService_SetSavedQueryPolicy_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 2, 2, 1, 0, 4, 4, 5, 3}, []string{"v1", "projects", "savedQueries", "resource"}, "setPolicy")))var (@@ -876,4 +1036,6 @@ var (forward_SavedQueryService_UpdateSavedQueryStar_0 = runtime.ForwardResponseMessageforward_SavedQueryService_BatchUpdateSavedQueries_0 = runtime.ForwardResponseMessageforward_SavedQueryService_DeleteSavedQuery_0 = runtime.ForwardResponseMessage+ forward_SavedQueryService_GetSavedQueryPolicy_0 = runtime.ForwardResponseMessage+ forward_SavedQueryService_SetSavedQueryPolicy_0 = runtime.ForwardResponseMessage)diff --git a/backend/generated-go/v1/saved_query_service_equal.pb.go b/backend/generated-go/v1/saved_query_service_equal.pb.goindex 12de7f9aec..32c3ee1804 100644--- a/backend/generated-go/v1/saved_query_service_equal.pb.go+++ b/backend/generated-go/v1/saved_query_service_equal.pb.go@@ -189,6 +189,77 @@ func (x *BatchUpdateSavedQueriesResponse) Equal(y *BatchUpdateSavedQueriesResponreturn true}+func (x *GetSavedQueryPolicyRequest) Equal(y *GetSavedQueryPolicyRequest) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Resource != y.Resource {+ return false+ }+ return true+}++func (x *SetSavedQueryPolicyRequest) Equal(y *SetSavedQueryPolicyRequest) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Resource != y.Resource {+ return false+ }+ if !x.Policy.Equal(y.Policy) {+ return false+ }+ return true+}++func (x *SavedQueryPolicy) Equal(y *SavedQueryPolicy) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if len(x.Bindings) != len(y.Bindings) {+ return false+ }+ for i := 0; i < len(x.Bindings); i++ {+ if !x.Bindings[i].Equal(y.Bindings[i]) {+ return false+ }+ }+ if x.Etag != y.Etag {+ return false+ }+ return true+}++func (x *SavedQueryBinding) Equal(y *SavedQueryBinding) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Level != y.Level {+ return false+ }+ if len(x.Members) != len(y.Members) {+ return false+ }+ for i := 0; i < len(x.Members); i++ {+ if x.Members[i] != y.Members[i] {+ return false+ }+ }+ return true+}+func (x *DeleteSavedQueryRequest) Equal(y *DeleteSavedQueryRequest) bool {if x == y {return truediff --git a/backend/generated-go/v1/saved_query_service_grpc.pb.go b/backend/generated-go/v1/saved_query_service_grpc.pb.goindex b31ccc2ab8..234afad852 100644--- a/backend/generated-go/v1/saved_query_service_grpc.pb.go+++ b/backend/generated-go/v1/saved_query_service_grpc.pb.go@@ -29,6 +29,8 @@ const (SavedQueryService_UpdateSavedQueryStar_FullMethodName = "/bytebase.v1.SavedQueryService/UpdateSavedQueryStar"SavedQueryService_BatchUpdateSavedQueries_FullMethodName = "/bytebase.v1.SavedQueryService/BatchUpdateSavedQueries"SavedQueryService_DeleteSavedQuery_FullMethodName = "/bytebase.v1.SavedQueryService/DeleteSavedQuery"+ SavedQueryService_GetSavedQueryPolicy_FullMethodName = "/bytebase.v1.SavedQueryService/GetSavedQueryPolicy"+ SavedQueryService_SetSavedQueryPolicy_FullMethodName = "/bytebase.v1.SavedQueryService/SetSavedQueryPolicy")// SavedQueryServiceClient is the client API for SavedQueryService service.@@ -37,58 +39,87 @@ const (//// SavedQueryService manages saved queries for SQL Editor query development.//-// A saved query is private to its creator; `bb.savedQueries.manage` is the-// admin backstop that can reach any saved query in scope. Per-object-// VIEWER/EDITOR grants arrive with the access-model redesign, which brings-// its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages-// them.+// 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.type SavedQueryServiceClient interface {- // Creates a personal saved query used in SQL Editor. The creator becomes- // the fixed owner.+ // Create a saved query. The creator becomes its fixed owner, and the saved+ // query starts private.// Permissions required: bb.savedQueries.create on the parent projectCreateSavedQuery(ctx context.Context, in *CreateSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)- // Get a saved query by name. Returns NotFound for saved queries the- // caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageGetSavedQuery(ctx context.Context, in *GetSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)- // List saved queries: the grant-independent governance surface. Supports- // listing in a project, or across all projects by using `projects/-`, with- // whole statements rather than the previews Search returns — e.g. an- // offboarding review filtering by creator.- // Permissions required: bb.savedQueries.list+ // 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/-"ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error)- // Search for saved queries in a project: the SQL Editor's hot list path,- // returning only rows the caller can read, with content previews.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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.+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueries(ctx context.Context, in *SearchSavedQueriesRequest, opts ...grpc.CallOption) (*SearchSavedQueriesResponse, error)- // Search the folder paths of the caller's saved queries in a project.- // Folders are a derived view over the `folder` field rather than a- // resource collection, so this is a custom method on savedQueries and- // shares SearchSavedQueries' caller-scoped semantics — not the- // cross-creator reach of ListSavedQueries.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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`).+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueryFolders(ctx context.Context, in *SearchSavedQueryFoldersRequest, opts ...grpc.CallOption) (*SearchSavedQueryFoldersResponse, error)- // Update a saved query. `title`, `content`, and `database` require write- // access; `folder` re-files the saved query and is creator/admin only.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageUpdateSavedQuery(ctx context.Context, in *UpdateSavedQueryRequest, opts ...grpc.CallOption) (*SavedQuery, error)- // Star or unstar a saved query for the caller. A star is always the- // caller's own per-user marker — invisible to others and carrying no- // access. The only requirement is that the caller can read the saved- // query being starred (which also keeps private saved query names- // unprobeable).- // Permissions required: read access to the saved query+ // Star or unstar a saved query for the caller. A star is a per-user marker:+ // invisible to everyone else and granting nothing. Read access is the gate+ // only so unreadable saved queries stay unprobeable.+ // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageUpdateSavedQueryStar(ctx context.Context, in *UpdateSavedQueryStarRequest, opts ...grpc.CallOption) (*SavedQuery, error)- // Batch re-file saved queries into a folder. The update mask supports- // `folder` only; only rows the caller may re-file are updated (their own,- // or any in scope for admins).- // Permissions required: creator, or bb.savedQueries.manage in scope+ // Re-file saved queries into a folder in bulk; the update mask supports+ // `folder` only. An EDITOR binding does not carry re-filing, so matched+ // saved queries the caller cannot re-file are skipped rather than rejected,+ // and the response counts what actually changed.+ // Permissions required: creator, or bb.savedQueries.manageBatchUpdateSavedQueries(ctx context.Context, in *BatchUpdateSavedQueriesRequest, opts ...grpc.CallOption) (*BatchUpdateSavedQueriesResponse, error)- // Delete a saved query. Only the creator (or an admin) can delete.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageDeleteSavedQuery(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+ 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+ SetSavedQueryPolicy(ctx context.Context, in *SetSavedQueryPolicyRequest, opts ...grpc.CallOption) (*SavedQueryPolicy, error)}type savedQueryServiceClient struct {@@ -189,64 +220,113 @@ func (c *savedQueryServiceClient) DeleteSavedQuery(ctx context.Context, in *Delereturn out, nil}+func (c *savedQueryServiceClient) GetSavedQueryPolicy(ctx context.Context, in *GetSavedQueryPolicyRequest, opts ...grpc.CallOption) (*SavedQueryPolicy, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(SavedQueryPolicy)+ err := c.cc.Invoke(ctx, SavedQueryService_GetSavedQueryPolicy_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *savedQueryServiceClient) SetSavedQueryPolicy(ctx context.Context, in *SetSavedQueryPolicyRequest, opts ...grpc.CallOption) (*SavedQueryPolicy, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(SavedQueryPolicy)+ err := c.cc.Invoke(ctx, SavedQueryService_SetSavedQueryPolicy_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// SavedQueryServiceServer is the server API for SavedQueryService service.// All implementations must embed UnimplementedSavedQueryServiceServer// for forward compatibility.//// SavedQueryService manages saved queries for SQL Editor query development.//-// A saved query is private to its creator; `bb.savedQueries.manage` is the-// admin backstop that can reach any saved query in scope. Per-object-// VIEWER/EDITOR grants arrive with the access-model redesign, which brings-// its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages-// them.+// 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.type SavedQueryServiceServer interface {- // Creates a personal saved query used in SQL Editor. The creator becomes- // the fixed owner.+ // Create a saved query. The creator becomes its fixed owner, and the saved+ // query starts private.// Permissions required: bb.savedQueries.create on the parent projectCreateSavedQuery(context.Context, *CreateSavedQueryRequest) (*SavedQuery, error)- // Get a saved query by name. Returns NotFound for saved queries the- // caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageGetSavedQuery(context.Context, *GetSavedQueryRequest) (*SavedQuery, error)- // List saved queries: the grant-independent governance surface. Supports- // listing in a project, or across all projects by using `projects/-`, with- // whole statements rather than the previews Search returns — e.g. an- // offboarding review filtering by creator.- // Permissions required: bb.savedQueries.list+ // 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/-"ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error)- // Search for saved queries in a project: the SQL Editor's hot list path,- // returning only rows the caller can read, with content previews.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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.+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueries(context.Context, *SearchSavedQueriesRequest) (*SearchSavedQueriesResponse, error)- // Search the folder paths of the caller's saved queries in a project.- // Folders are a derived view over the `folder` field rather than a- // resource collection, so this is a custom method on savedQueries and- // shares SearchSavedQueries' caller-scoped semantics — not the- // cross-creator reach of ListSavedQueries.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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`).+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueryFolders(context.Context, *SearchSavedQueryFoldersRequest) (*SearchSavedQueryFoldersResponse, error)- // Update a saved query. `title`, `content`, and `database` require write- // access; `folder` re-files the saved query and is creator/admin only.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageUpdateSavedQuery(context.Context, *UpdateSavedQueryRequest) (*SavedQuery, error)- // Star or unstar a saved query for the caller. A star is always the- // caller's own per-user marker — invisible to others and carrying no- // access. The only requirement is that the caller can read the saved- // query being starred (which also keeps private saved query names- // unprobeable).- // Permissions required: read access to the saved query+ // Star or unstar a saved query for the caller. A star is a per-user marker:+ // invisible to everyone else and granting nothing. Read access is the gate+ // only so unreadable saved queries stay unprobeable.+ // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageUpdateSavedQueryStar(context.Context, *UpdateSavedQueryStarRequest) (*SavedQuery, error)- // Batch re-file saved queries into a folder. The update mask supports- // `folder` only; only rows the caller may re-file are updated (their own,- // or any in scope for admins).- // Permissions required: creator, or bb.savedQueries.manage in scope+ // Re-file saved queries into a folder in bulk; the update mask supports+ // `folder` only. An EDITOR binding does not carry re-filing, so matched+ // saved queries the caller cannot re-file are skipped rather than rejected,+ // and the response counts what actually changed.+ // Permissions required: creator, or bb.savedQueries.manageBatchUpdateSavedQueries(context.Context, *BatchUpdateSavedQueriesRequest) (*BatchUpdateSavedQueriesResponse, error)- // Delete a saved query. Only the creator (or an admin) can delete.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageDeleteSavedQuery(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+ 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+ SetSavedQueryPolicy(context.Context, *SetSavedQueryPolicyRequest) (*SavedQueryPolicy, error)mustEmbedUnimplementedSavedQueryServiceServer()}@@ -284,6 +364,12 @@ func (UnimplementedSavedQueryServiceServer) BatchUpdateSavedQueries(context.Contfunc (UnimplementedSavedQueryServiceServer) DeleteSavedQuery(context.Context, *DeleteSavedQueryRequest) (*emptypb.Empty, error) {return nil, status.Error(codes.Unimplemented, "method DeleteSavedQuery not implemented")}+func (UnimplementedSavedQueryServiceServer) GetSavedQueryPolicy(context.Context, *GetSavedQueryPolicyRequest) (*SavedQueryPolicy, error) {+ return nil, status.Error(codes.Unimplemented, "method GetSavedQueryPolicy not implemented")+}+func (UnimplementedSavedQueryServiceServer) SetSavedQueryPolicy(context.Context, *SetSavedQueryPolicyRequest) (*SavedQueryPolicy, error) {+ return nil, status.Error(codes.Unimplemented, "method SetSavedQueryPolicy not implemented")+}func (UnimplementedSavedQueryServiceServer) mustEmbedUnimplementedSavedQueryServiceServer() {}func (UnimplementedSavedQueryServiceServer) testEmbeddedByValue() {}@@ -467,6 +553,42 @@ func _SavedQueryService_DeleteSavedQuery_Handler(srv interface{}, ctx context.Coreturn interceptor(ctx, in, info, handler)}+func _SavedQueryService_GetSavedQueryPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetSavedQueryPolicyRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SavedQueryServiceServer).GetSavedQueryPolicy(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SavedQueryService_GetSavedQueryPolicy_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SavedQueryServiceServer).GetSavedQueryPolicy(ctx, req.(*GetSavedQueryPolicyRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _SavedQueryService_SetSavedQueryPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(SetSavedQueryPolicyRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SavedQueryServiceServer).SetSavedQueryPolicy(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SavedQueryService_SetSavedQueryPolicy_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SavedQueryServiceServer).SetSavedQueryPolicy(ctx, req.(*SetSavedQueryPolicyRequest))+ }+ return interceptor(ctx, in, info, handler)+}+// SavedQueryService_ServiceDesc is the grpc.ServiceDesc for SavedQueryService service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -510,6 +632,14 @@ var SavedQueryService_ServiceDesc = grpc.ServiceDesc{MethodName: "DeleteSavedQuery",Handler: _SavedQueryService_DeleteSavedQuery_Handler,},+ {+ MethodName: "GetSavedQueryPolicy",+ Handler: _SavedQueryService_GetSavedQueryPolicy_Handler,+ },+ {+ MethodName: "SetSavedQueryPolicy",+ Handler: _SavedQueryService_SetSavedQueryPolicy_Handler,+ },},Streams: []grpc.StreamDesc{},Metadata: "v1/saved_query_service.proto",diff --git a/backend/generated-go/v1/v1connect/saved_query_service.connect.go b/backend/generated-go/v1/v1connect/saved_query_service.connect.goindex cfdf60bb46..cbd3e5dc81 100644--- a/backend/generated-go/v1/v1connect/saved_query_service.connect.go+++ b/backend/generated-go/v1/v1connect/saved_query_service.connect.go@@ -61,56 +61,88 @@ const (// SavedQueryServiceDeleteSavedQueryProcedure is the fully-qualified name of the SavedQueryService's// DeleteSavedQuery RPC.SavedQueryServiceDeleteSavedQueryProcedure = "/bytebase.v1.SavedQueryService/DeleteSavedQuery"+ // SavedQueryServiceGetSavedQueryPolicyProcedure is the fully-qualified name of the+ // SavedQueryService's GetSavedQueryPolicy RPC.+ SavedQueryServiceGetSavedQueryPolicyProcedure = "/bytebase.v1.SavedQueryService/GetSavedQueryPolicy"+ // SavedQueryServiceSetSavedQueryPolicyProcedure is the fully-qualified name of the+ // SavedQueryService's SetSavedQueryPolicy RPC.+ SavedQueryServiceSetSavedQueryPolicyProcedure = "/bytebase.v1.SavedQueryService/SetSavedQueryPolicy")// SavedQueryServiceClient is a client for the bytebase.v1.SavedQueryService service.type SavedQueryServiceClient interface {- // Creates a personal saved query used in SQL Editor. The creator becomes- // the fixed owner.+ // Create a saved query. The creator becomes its fixed owner, and the saved+ // query starts private.// Permissions required: bb.savedQueries.create on the parent projectCreateSavedQuery(context.Context, *connect.Request[v1.CreateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // Get a saved query by name. Returns NotFound for saved queries the- // caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageGetSavedQuery(context.Context, *connect.Request[v1.GetSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // List saved queries: the grant-independent governance surface. Supports- // listing in a project, or across all projects by using `projects/-`, with- // whole statements rather than the previews Search returns — e.g. an- // offboarding review filtering by creator.- // Permissions required: bb.savedQueries.list+ // 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/-"ListSavedQueries(context.Context, *connect.Request[v1.ListSavedQueriesRequest]) (*connect.Response[v1.ListSavedQueriesResponse], error)- // Search for saved queries in a project: the SQL Editor's hot list path,- // returning only rows the caller can read, with content previews.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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.+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueries(context.Context, *connect.Request[v1.SearchSavedQueriesRequest]) (*connect.Response[v1.SearchSavedQueriesResponse], error)- // Search the folder paths of the caller's saved queries in a project.- // Folders are a derived view over the `folder` field rather than a- // resource collection, so this is a custom method on savedQueries and- // shares SearchSavedQueries' caller-scoped semantics — not the- // cross-creator reach of ListSavedQueries.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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`).+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueryFolders(context.Context, *connect.Request[v1.SearchSavedQueryFoldersRequest]) (*connect.Response[v1.SearchSavedQueryFoldersResponse], error)- // Update a saved query. `title`, `content`, and `database` require write- // access; `folder` re-files the saved query and is creator/admin only.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageUpdateSavedQuery(context.Context, *connect.Request[v1.UpdateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // Star or unstar a saved query for the caller. A star is always the- // caller's own per-user marker — invisible to others and carrying no- // access. The only requirement is that the caller can read the saved- // query being starred (which also keeps private saved query names- // unprobeable).- // Permissions required: read access to the saved query+ // Star or unstar a saved query for the caller. A star is a per-user marker:+ // invisible to everyone else and granting nothing. Read access is the gate+ // only so unreadable saved queries stay unprobeable.+ // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageUpdateSavedQueryStar(context.Context, *connect.Request[v1.UpdateSavedQueryStarRequest]) (*connect.Response[v1.SavedQuery], error)- // Batch re-file saved queries into a folder. The update mask supports- // `folder` only; only rows the caller may re-file are updated (their own,- // or any in scope for admins).- // Permissions required: creator, or bb.savedQueries.manage in scope+ // Re-file saved queries into a folder in bulk; the update mask supports+ // `folder` only. An EDITOR binding does not carry re-filing, so matched+ // saved queries the caller cannot re-file are skipped rather than rejected,+ // and the response counts what actually changed.+ // Permissions required: creator, or bb.savedQueries.manageBatchUpdateSavedQueries(context.Context, *connect.Request[v1.BatchUpdateSavedQueriesRequest]) (*connect.Response[v1.BatchUpdateSavedQueriesResponse], error)- // Delete a saved query. Only the creator (or an admin) can delete.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageDeleteSavedQuery(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+ 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+ SetSavedQueryPolicy(context.Context, *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)}// NewSavedQueryServiceClient constructs a client for the bytebase.v1.SavedQueryService service. By@@ -178,6 +210,18 @@ func NewSavedQueryServiceClient(httpClient connect.HTTPClient, baseURL string, oconnect.WithSchema(savedQueryServiceMethods.ByName("DeleteSavedQuery")),connect.WithClientOptions(opts...),),+ getSavedQueryPolicy: connect.NewClient[v1.GetSavedQueryPolicyRequest, v1.SavedQueryPolicy](+ httpClient,+ baseURL+SavedQueryServiceGetSavedQueryPolicyProcedure,+ connect.WithSchema(savedQueryServiceMethods.ByName("GetSavedQueryPolicy")),+ connect.WithClientOptions(opts...),+ ),+ setSavedQueryPolicy: connect.NewClient[v1.SetSavedQueryPolicyRequest, v1.SavedQueryPolicy](+ httpClient,+ baseURL+SavedQueryServiceSetSavedQueryPolicyProcedure,+ connect.WithSchema(savedQueryServiceMethods.ByName("SetSavedQueryPolicy")),+ connect.WithClientOptions(opts...),+ ),}}@@ -192,6 +236,8 @@ type savedQueryServiceClient struct {updateSavedQueryStar *connect.Client[v1.UpdateSavedQueryStarRequest, v1.SavedQuery]batchUpdateSavedQueries *connect.Client[v1.BatchUpdateSavedQueriesRequest, v1.BatchUpdateSavedQueriesResponse]deleteSavedQuery *connect.Client[v1.DeleteSavedQueryRequest, emptypb.Empty]+ getSavedQueryPolicy *connect.Client[v1.GetSavedQueryPolicyRequest, v1.SavedQueryPolicy]+ setSavedQueryPolicy *connect.Client[v1.SetSavedQueryPolicyRequest, v1.SavedQueryPolicy]}// CreateSavedQuery calls bytebase.v1.SavedQueryService.CreateSavedQuery.@@ -239,54 +285,90 @@ func (c *savedQueryServiceClient) DeleteSavedQuery(ctx context.Context, req *conreturn c.deleteSavedQuery.CallUnary(ctx, req)}+// GetSavedQueryPolicy calls bytebase.v1.SavedQueryService.GetSavedQueryPolicy.+func (c *savedQueryServiceClient) GetSavedQueryPolicy(ctx context.Context, req *connect.Request[v1.GetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error) {+ return c.getSavedQueryPolicy.CallUnary(ctx, req)+}++// SetSavedQueryPolicy calls bytebase.v1.SavedQueryService.SetSavedQueryPolicy.+func (c *savedQueryServiceClient) SetSavedQueryPolicy(ctx context.Context, req *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error) {+ return c.setSavedQueryPolicy.CallUnary(ctx, req)+}+// SavedQueryServiceHandler is an implementation of the bytebase.v1.SavedQueryService service.type SavedQueryServiceHandler interface {- // Creates a personal saved query used in SQL Editor. The creator becomes- // the fixed owner.+ // Create a saved query. The creator becomes its fixed owner, and the saved+ // query starts private.// Permissions required: bb.savedQueries.create on the parent projectCreateSavedQuery(context.Context, *connect.Request[v1.CreateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // Get a saved query by name. Returns NotFound for saved queries the- // caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageGetSavedQuery(context.Context, *connect.Request[v1.GetSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // List saved queries: the grant-independent governance surface. Supports- // listing in a project, or across all projects by using `projects/-`, with- // whole statements rather than the previews Search returns — e.g. an- // offboarding review filtering by creator.- // Permissions required: bb.savedQueries.list+ // 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/-"ListSavedQueries(context.Context, *connect.Request[v1.ListSavedQueriesRequest]) (*connect.Response[v1.ListSavedQueriesResponse], error)- // Search for saved queries in a project: the SQL Editor's hot list path,- // returning only rows the caller can read, with content previews.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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.+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueries(context.Context, *connect.Request[v1.SearchSavedQueriesRequest]) (*connect.Response[v1.SearchSavedQueriesResponse], error)- // Search the folder paths of the caller's saved queries in a project.- // Folders are a derived view over the `folder` field rather than a- // resource collection, so this is a custom method on savedQueries and- // shares SearchSavedQueries' caller-scoped semantics — not the- // cross-creator reach of ListSavedQueries.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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`).+ // Permissions required: bb.savedQueries.search on the projectSearchSavedQueryFolders(context.Context, *connect.Request[v1.SearchSavedQueryFoldersRequest]) (*connect.Response[v1.SearchSavedQueryFoldersResponse], error)- // Update a saved query. `title`, `content`, and `database` require write- // access; `folder` re-files the saved query and is creator/admin only.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageUpdateSavedQuery(context.Context, *connect.Request[v1.UpdateSavedQueryRequest]) (*connect.Response[v1.SavedQuery], error)- // Star or unstar a saved query for the caller. A star is always the- // caller's own per-user marker — invisible to others and carrying no- // access. The only requirement is that the caller can read the saved- // query being starred (which also keeps private saved query names- // unprobeable).- // Permissions required: read access to the saved query+ // Star or unstar a saved query for the caller. A star is a per-user marker:+ // invisible to everyone else and granting nothing. Read access is the gate+ // only so unreadable saved queries stay unprobeable.+ // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageUpdateSavedQueryStar(context.Context, *connect.Request[v1.UpdateSavedQueryStarRequest]) (*connect.Response[v1.SavedQuery], error)- // Batch re-file saved queries into a folder. The update mask supports- // `folder` only; only rows the caller may re-file are updated (their own,- // or any in scope for admins).- // Permissions required: creator, or bb.savedQueries.manage in scope+ // Re-file saved queries into a folder in bulk; the update mask supports+ // `folder` only. An EDITOR binding does not carry re-filing, so matched+ // saved queries the caller cannot re-file are skipped rather than rejected,+ // and the response counts what actually changed.+ // Permissions required: creator, or bb.savedQueries.manageBatchUpdateSavedQueries(context.Context, *connect.Request[v1.BatchUpdateSavedQueriesRequest]) (*connect.Response[v1.BatchUpdateSavedQueriesResponse], error)- // Delete a saved query. Only the creator (or an admin) can delete.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.manageDeleteSavedQuery(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+ 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+ SetSavedQueryPolicy(context.Context, *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error)}// NewSavedQueryServiceHandler builds an HTTP handler from the service implementation. It returns@@ -350,6 +432,18 @@ func NewSavedQueryServiceHandler(svc SavedQueryServiceHandler, opts ...connect.Hconnect.WithSchema(savedQueryServiceMethods.ByName("DeleteSavedQuery")),connect.WithHandlerOptions(opts...),)+ savedQueryServiceGetSavedQueryPolicyHandler := connect.NewUnaryHandler(+ SavedQueryServiceGetSavedQueryPolicyProcedure,+ svc.GetSavedQueryPolicy,+ connect.WithSchema(savedQueryServiceMethods.ByName("GetSavedQueryPolicy")),+ connect.WithHandlerOptions(opts...),+ )+ savedQueryServiceSetSavedQueryPolicyHandler := connect.NewUnaryHandler(+ SavedQueryServiceSetSavedQueryPolicyProcedure,+ svc.SetSavedQueryPolicy,+ connect.WithSchema(savedQueryServiceMethods.ByName("SetSavedQueryPolicy")),+ connect.WithHandlerOptions(opts...),+ )return "/bytebase.v1.SavedQueryService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {case SavedQueryServiceCreateSavedQueryProcedure:@@ -370,6 +464,10 @@ func NewSavedQueryServiceHandler(svc SavedQueryServiceHandler, opts ...connect.HsavedQueryServiceBatchUpdateSavedQueriesHandler.ServeHTTP(w, r)case SavedQueryServiceDeleteSavedQueryProcedure:savedQueryServiceDeleteSavedQueryHandler.ServeHTTP(w, r)+ case SavedQueryServiceGetSavedQueryPolicyProcedure:+ savedQueryServiceGetSavedQueryPolicyHandler.ServeHTTP(w, r)+ case SavedQueryServiceSetSavedQueryPolicyProcedure:+ savedQueryServiceSetSavedQueryPolicyHandler.ServeHTTP(w, r)default:http.NotFound(w, r)}@@ -414,3 +512,11 @@ func (UnimplementedSavedQueryServiceHandler) BatchUpdateSavedQueries(context.Confunc (UnimplementedSavedQueryServiceHandler) DeleteSavedQuery(context.Context, *connect.Request[v1.DeleteSavedQueryRequest]) (*connect.Response[emptypb.Empty], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SavedQueryService.DeleteSavedQuery is not implemented"))}++func (UnimplementedSavedQueryServiceHandler) GetSavedQueryPolicy(context.Context, *connect.Request[v1.GetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SavedQueryService.GetSavedQueryPolicy is not implemented"))+}++func (UnimplementedSavedQueryServiceHandler) SetSavedQueryPolicy(context.Context, *connect.Request[v1.SetSavedQueryPolicyRequest]) (*connect.Response[v1.SavedQueryPolicy], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.SavedQueryService.SetSavedQueryPolicy is not implemented"))+}diff --git a/backend/migrator/migration/3.22/0008##saved_query_bindings.sql b/backend/migrator/migration/3.22/0008##saved_query_bindings.sqlnew file mode 100644index 0000000000..a501ee2555--- /dev/null+++ b/backend/migrator/migration/3.22/0008##saved_query_bindings.sql@@ -0,0 +1,15 @@+-- Per-object sharing: a saved query carries its own grants instead of a+-- project-wide visibility flag. Existing rows start with no bindings, which+-- makes them private to their creator -- the owner-private migration the+-- design calls for, matching BigQuery's own classic-to-modern path.+--+-- The column holds a protojson array of SavedQueryBinding at the jsonb root+-- (not a wrapper object), so the access queries' `@>` containment probes hit+-- the GIN index below without an expression index.+ALTER TABLE saved_query ADD COLUMN bindings jsonb NOT NULL DEFAULT '[]';++-- "Shared with me" is one GIN probe per principal in the caller's set+-- (themselves plus each of their groups), BitmapOr'd together. jsonb_path_ops+-- is smaller and faster than the default opclass for pure containment, which+-- is all these queries do.+CREATE INDEX idx_saved_query_bindings ON saved_query USING gin (bindings jsonb_path_ops);diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex 32d1cc8032..36918f239f 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -373,6 +373,11 @@ CREATE TABLE saved_query (-- Stored as SavedQueryPayload (proto/store/store/saved_query.proto); the-- connected database is a soft reference kept as its canonical name.payload jsonb NOT NULL DEFAULT '{}',+ -- Per-object grants: a protojson array of SavedQueryBinding at the jsonb+ -- root, e.g. [{"level":"EDITOR","members":["groups/[email protected]"]}]. The+ -- array must sit at the root so the access queries' `@>` probes use the+ -- GIN index below. Empty means private to the creator.+ bindings jsonb NOT NULL DEFAULT '[]',PRIMARY KEY (resource_id));@@ -383,6 +388,11 @@ CREATE TABLE saved_query (CREATE INDEX idx_saved_query_project_creator_folder ON saved_query(project, creator, folder);CREATE INDEX idx_saved_query_creator_project ON saved_query(creator, project);+-- "Shared with me" probes bindings once per principal in the caller's set and+-- BitmapOrs the results. jsonb_path_ops is smaller and faster than the default+-- opclass for the containment these queries do.+CREATE INDEX idx_saved_query_bindings ON saved_query USING gin (bindings jsonb_path_ops);+-- saved_query_star stores per-user stars: row existence is the star. The FK-- cascade is a race backstop only — code paths delete star rows explicitly-- before their parent.diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex f04d438890..fa6940d55a 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.7"), *files[len(files)-1].version)- require.Equal(t, "migration/3.22/0007##saved_query_permissions_folder_star.sql", files[len(files)-1].path)+ 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)}func TestVersionUnique(t *testing.T) {diff --git a/backend/store/group.go b/backend/store/group.goindex b7215395c2..e4a39e0ed3 100644--- a/backend/store/group.go+++ b/backend/store/group.go@@ -3,6 +3,7 @@ package storeimport ("context""database/sql"+ "fmt""strings""github.com/google/cel-go/cel"@@ -245,6 +246,16 @@ func (s *Store) CreateGroup(ctx context.Context, create *GroupMessage) (*GroupMe}// UpdateGroup updates a group.+// groupPrincipalToken is how a group is named inside a saved-query binding:+// its email, or its ID when it has none — matching what GetUserGroupsSnapshot+// emits for the caller's principal set.+func groupPrincipalToken(id, email string) string {+ if email != "" {+ return email+ }+ return id+}+func (s *Store) UpdateGroup(ctx context.Context, patch *UpdateGroupMessage) (*GroupMessage, error) {set := qb.Q()if v := patch.Email; v != nil {@@ -281,11 +292,28 @@ func (s *Store) UpdateGroup(ctx context.Context, patch *UpdateGroupMessage) (*Grreturn nil, errors.Wrapf(err, "failed to build sql")}+ tx, err := s.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return nil, errors.Wrap(err, "failed to begin transaction")+ }+ defer tx.Rollback()++ // Saved-query grants name a group by email, so a rename has to rewrite them+ // in the same transaction or every saved query shared with this group+ // becomes unreachable to its members. Read the old token under the row lock+ // the UPDATE below takes anyway.+ var oldEmail sql.NullString+ if err := tx.QueryRowContext(ctx,+ `SELECT email FROM user_group WHERE id = $1 AND workspace = $2 FOR UPDATE`,+ patch.ID, patch.Workspace).Scan(&oldEmail); err != nil {+ return nil, err+ }+var group GroupMessagevar payload []bytevar email sql.NullString- if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan( // NOSONAR: query is parameterized via qb.Query+ if err := tx.QueryRowContext(ctx, query, args...).Scan( // NOSONAR: query is parameterized via qb.Query&group.ID,&email,&group.Title,@@ -295,6 +323,32 @@ func (s *Store) UpdateGroup(ctx context.Context, patch *UpdateGroupMessage) (*Grreturn nil, err}+ oldToken := groupPrincipalToken(patch.ID, oldEmail.String)+ newToken := groupPrincipalToken(patch.ID, email.String)+ if oldToken != newToken {+ // Both needles are whole JSON strings built here rather than assembled+ // in SQL, so they reach the query as plain bound values: no LIKE, and+ // therefore no chance of an email's own % or _ acting as a wildcard.+ // The quotes keep the match exact -- "group:eng@x" cannot match inside+ // "group:xeng@x". Scoped to this workspace's projects, since group+ // tokens are workspace-local and an identical email elsewhere belongs+ // to a different group.+ oldMember := fmt.Sprintf("%q", common.FormatGroupEmail(oldToken))+ newMember := fmt.Sprintf("%q", common.FormatGroupEmail(newToken))+ if _, err := tx.ExecContext(ctx, `+ UPDATE saved_query+ SET bindings = replace(bindings::text, $1, $2)::jsonb+ WHERE project IN (SELECT resource_id FROM project WHERE workspace = $3)+ AND strpos(bindings::text, $1) > 0+ `, oldMember, newMember, patch.Workspace); err != nil {+ return nil, errors.Wrapf(err, "failed to rewrite saved query grants for group %s", patch.ID)+ }+ }++ if err := tx.Commit(); err != nil {+ return nil, errors.Wrap(err, "failed to commit transaction")+ }+groupPayload := storepb.GroupPayload{}if err := common.ProtojsonUnmarshaler.Unmarshal(payload, &groupPayload); err != nil {return nil, errdiff --git a/backend/store/principal.go b/backend/store/principal.goindex 43f71b1876..89faa412ea 100644--- a/backend/store/principal.go+++ b/backend/store/principal.go@@ -3,6 +3,7 @@ package storeimport ("context""database/sql"+ "fmt""strings""time"@@ -687,6 +688,22 @@ func (s *Store) UpdateUserEmail(ctx context.Context, user *UserMessage, newEmailif err := updateReference("UPDATE saved_query SET creator = $1 WHERE creator = $2"); err != nil {return nil, err}+ // Saved-query grants name their principals by email as well, so a rename+ // has to rewrite the members inside the bindings jsonb in the same+ // transaction — otherwise every grant made to this address silently+ // orphans. Both needles are whole JSON strings built here rather than+ // assembled in SQL, so an email's own % or _ cannot act as a wildcard, and+ // the quotes keep the match exact: "user:[email protected]" cannot match inside+ // "user:[email protected]".+ oldMember := fmt.Sprintf("%q", common.FormatUserEmail(user.Email))+ newMember := fmt.Sprintf("%q", common.FormatUserEmail(newEmail))+ if _, err := tx.ExecContext(ctx, `+ UPDATE saved_query+ SET bindings = replace(bindings::text, $1, $2)::jsonb+ WHERE strpos(bindings::text, $1) > 0+ `, oldMember, newMember); err != nil {+ return nil, errors.Wrapf(err, "failed to rewrite saved query grants for %s", user.Email)+ }if err := updateReference("UPDATE issue_comment SET creator = $1 WHERE creator = $2"); err != nil {return nil, err}diff --git a/backend/store/saved_query.go b/backend/store/saved_query.goindex 93adf35beb..c760c39629 100644--- a/backend/store/saved_query.go+++ b/backend/store/saved_query.go@@ -2,7 +2,10 @@ package storeimport ("context"+ "crypto/sha256""database/sql"+ "encoding/hex"+ "encoding/json""fmt""strings""time"@@ -35,6 +38,10 @@ type SavedQueryMessage struct {// The folder path this saved query lives in ("a/b/c", "" = unfiled).Folder string+ // Bindings are the per-object grants. Empty means private to the creator+ // (the admin backstop aside).+ Bindings []*storepb.SavedQueryBinding+// Output only fieldsSize int64CreatedAt time.Time@@ -51,6 +58,18 @@ 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.+ //+ // Must describe the same caller as PrincipalEmail: the clause reads "own"+ // from PrincipalEmail and "granted" from here. Setting one without the+ // other narrows the result rather than widening it, but the two disagreeing+ // would be a bug.+ AccessMembers []string+ResourceID *string// LoadFull is used if we want to load the full sheet.@@ -110,12 +129,27 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessagsaved_query.payload,saved_query.folder,saved_query.name,+ saved_query.bindings,%s,OCTET_LENGTH(saved_query.statement),EXISTS (SELECT 1 FROM saved_query_star WHERE saved_query_star.saved_query = saved_query.resource_id AND saved_query_star.principal = ?)FROM saved_queryWHERE TRUE`, statementField), find.PrincipalEmail)+ // The read predicate, pushed into SQL rather than applied to the page+ // afterwards: filtering after LIMIT would silently return short pages.+ if find.AccessMembers != nil {+ access := qb.Q().Space("saved_query.creator = ?", find.PrincipalEmail)+ for _, member := range find.AccessMembers {+ probe, err := bindingProbe(member)+ if err != nil {+ return nil, err+ }+ access.Or("saved_query.bindings @> ?", probe)+ }+ q.And("(?)", access)+ }+if find.Workspace != "" {q.And("EXISTS (SELECT 1 FROM project WHERE project.resource_id = saved_query.project AND project.workspace = ? AND project.deleted = FALSE)", find.Workspace)}@@ -155,7 +189,7 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessagvar sheets []*SavedQueryMessagefor rows.Next() {var sheet SavedQueryMessage- var payloadBytes []byte+ var payloadBytes, bindingsBytes []byteif err := rows.Scan(&sheet.ResourceID,&sheet.Creator,@@ -165,6 +199,7 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessag&payloadBytes,&sheet.Folder,&sheet.Title,+ &bindingsBytes,&sheet.Statement,&sheet.Size,&sheet.Starred,@@ -178,6 +213,12 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessag}sheet.Database = payload.Database+ bindings, err := unmarshalSavedQueryBindings(bindingsBytes)+ if err != nil {+ return nil, err+ }+ sheet.Bindings = bindings+sheets = append(sheets, &sheet)}if err := rows.Err(); err != nil {@@ -187,6 +228,128 @@ func (s *Store) ListSavedQueries(ctx context.Context, find *FindSavedQueryMessagreturn sheets, nil}+// 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".+func bindingProbe(member string) (string, error) {+ probe, err := json.Marshal([]map[string]any{{"members": []string{member}}})+ if err != nil {+ return "", errors.Wrapf(err, "failed to build binding probe for %q", member)+ }+ return string(probe), nil+}++// marshalSavedQueryBindings writes the bindings as a protojson array at the+// jsonb root. protojson has no top-level array form, so each element is+// marshalled on its own and the array assembled here; the shape is pinned+// because the GIN containment probes above depend on it.+func marshalSavedQueryBindings(bindings []*storepb.SavedQueryBinding) (string, error) {+ elements := make([]json.RawMessage, 0, len(bindings))+ for _, binding := range bindings {+ element, err := protojson.Marshal(binding)+ if err != nil {+ return "", errors.Wrapf(err, "failed to marshal saved query binding")+ }+ elements = append(elements, element)+ }+ out, err := json.Marshal(elements)+ if err != nil {+ return "", errors.Wrapf(err, "failed to marshal saved query bindings")+ }+ return string(out), nil+}++func unmarshalSavedQueryBindings(b []byte) ([]*storepb.SavedQueryBinding, error) {+ if len(b) == 0 {+ return nil, nil+ }+ var elements []json.RawMessage+ if err := json.Unmarshal(b, &elements); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal saved query bindings")+ }+ bindings := make([]*storepb.SavedQueryBinding, 0, len(elements))+ for _, element := range elements {+ var binding storepb.SavedQueryBinding+ if err := common.ProtojsonUnmarshaler.Unmarshal(element, &binding); err != nil {+ return nil, errors.Wrapf(err, "failed to unmarshal saved query binding")+ }+ bindings = append(bindings, &binding)+ }+ return bindings, nil+}++// SavedQueryPolicyEtag derives the etag from the stored bindings themselves,+// so no column has to be kept in step with them. Two policies with the same+// grants produce the same etag, which is what compare-and-swap needs: a write+// is rejected only when the grants actually moved.+func SavedQueryPolicyEtag(bindings []*storepb.SavedQueryBinding) (string, error) {+ marshalled, err := marshalSavedQueryBindings(bindings)+ if err != nil {+ return "", err+ }+ sum := sha256.Sum256([]byte(marshalled))+ return hex.EncodeToString(sum[:]), nil+}++// SetSavedQueryBindings replaces a saved query's grants under compare-and-swap.+// The row is locked and its current etag compared before the write, so a+// full-replacement write can never silently undo a concurrent revocation.+// Returns ErrSavedQueryEtagMismatch when the caller's etag is stale, and+// reports false when the saved query is gone from the named project -- deleted,+// or re-parented to the default project by a purge.+func (s *Store) SetSavedQueryBindings(ctx context.Context, projectID, resourceID string, bindings []*storepb.SavedQueryBinding, expectedEtag string) (bool, error) {+ marshalled, err := marshalSavedQueryBindings(bindings)+ if err != nil {+ return false, err+ }++ tx, err := s.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return false, errors.Wrap(err, "failed to begin transaction")+ }+ defer tx.Rollback()++ // Scoped to the project the caller named, not the saved query's global id.+ // A project purge re-parents its members' saved queries to the default+ // project, so a write resolved against the old project must land on+ // nothing rather than on a row that has since moved out from under it.+ var currentBytes []byte+ if err := tx.QueryRowContext(ctx,+ `SELECT bindings FROM saved_query WHERE resource_id = $1 AND project = $2 FOR UPDATE`,+ resourceID, projectID).Scan(¤tBytes); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return false, nil+ }+ return false, errors.Wrapf(err, "failed to lock saved query %s", resourceID)+ }+ current, err := unmarshalSavedQueryBindings(currentBytes)+ if err != nil {+ return false, err+ }+ currentEtag, err := SavedQueryPolicyEtag(current)+ if err != nil {+ return false, err+ }+ if expectedEtag != currentEtag {+ return false, ErrSavedQueryEtagMismatch+ }++ if _, err := tx.ExecContext(ctx,+ `UPDATE saved_query SET bindings = $1 WHERE resource_id = $2 AND project = $3`,+ marshalled, resourceID, projectID); err != nil {+ return false, errors.Wrapf(err, "failed to update bindings for saved query %s", resourceID)+ }+ if err := tx.Commit(); err != nil {+ return false, errors.Wrap(err, "failed to commit transaction")+ }+ return true, nil+}++// ErrSavedQueryEtagMismatch reports that the policy moved under a+// compare-and-swap write; the caller refetches and reapplies.+var ErrSavedQueryEtagMismatch = errors.New("saved query policy etag mismatch")+// CreateSavedQuery creates a new saved query. The insert transaction locks// the owning project row and requires it to be active, so a create racing a// project purge fails cleanly instead of as an FK violation — the parent@@ -406,6 +569,9 @@ func (s *Store) BatchUpdateSavedQueryFolder(ctx context.Context, resourceIDs []sif err := rows.Err(); err != nil {return 0, err}+ // Free the cursor before the UPDATE below: statements on the same+ // transaction cannot interleave with an open one.+ rows.Close()if len(locked) > 0 {if _, err := tx.ExecContext(ctx, `@@ -427,15 +593,30 @@ func (s *Store) BatchUpdateSavedQueryFolder(ctx context.Context, resourceIDs []s// 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.-func (s *Store) ListSavedQueryFolderPaths(ctx context.Context, projectID string, creator *string, filterQ *qb.Query) ([]string, error) {+// 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) {q := qb.Q().Space(`SELECT DISTINCT folderFROM saved_queryWHERE TRUE`)q.And("saved_query.project = ?", projectID)q.And("saved_query.folder <> ''")- if creator != nil {- q.And("saved_query.creator = ?", *creator)+ if accessMembers != nil {+ access := qb.Q().Space("saved_query.creator = ?", principalEmail)+ for _, member := range accessMembers {+ probe, err := bindingProbe(member)+ if err != nil {+ return nil, err+ }+ access.Or("saved_query.bindings @> ?", probe)+ }+ q.And("(?)", access)}if filterQ != nil {q.And("?", filterQ)@@ -479,7 +660,7 @@ func NormalizeSavedQueryFolder(folder string) (string, error) {return normalized, nil}-func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, filter string, allowTitleContains bool) (*qb.Query, error) {+func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, accessMembers []string, filter string, allowTitleContains bool) (*qb.Query, error) {if filter == "" {return nil, nil}@@ -530,7 +711,11 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, fil}return qb.Q().Space("saved_query.resource_id = ?", savedQueryID), nilcase "creator":- userID, err := getUserID(value.(string))+ creator, ok := value.(string)+ if !ok {+ return nil, errors.Errorf("invalid creator value %v, expect a string", value)+ }+ userID, err := getUserID(creator)if err != nil {return nil, err}@@ -542,7 +727,27 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, fil}return qb.Q().Space("NOT EXISTS (SELECT 1 FROM saved_query_star WHERE saved_query_star.saved_query = saved_query.resource_id AND saved_query_star.principal = ?)", caller), nil}- return qb.Q().Space("TRUE"), nil+ 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.+ shared, ok := value.(bool)+ if !ok {+ return nil, errors.Errorf("invalid shared value %v, expect true or false", value)+ }+ granted := qb.Q().Space("FALSE")+ for _, principal := range accessMembers {+ probe, err := bindingProbe(principal)+ if err != nil {+ return nil, err+ }+ granted.Or("saved_query.bindings @> ?", probe)+ }+ if shared {+ return qb.Q().Space("(saved_query.creator <> ? AND (?))", caller, granted), nil+ }+ return qb.Q().Space("(NOT (saved_query.creator <> ? AND (?)))", caller, granted), nilcase "folder":folder, ok := value.(string)if !ok {@@ -617,7 +822,11 @@ func GetSearchSavedQueryFilter(ctx context.Context, s *Store, caller string, filif variable != "creator" {return nil, errors.Errorf(`only "creator" support "!=" operator`)}- userID, err := getUserID(value.(string))+ creator, ok := value.(string)+ if !ok {+ return nil, errors.Errorf("invalid creator value %v, expect a string", value)+ }+ userID, err := getUserID(creator)if err != nil {return nil, err}diff --git a/backend/store/saved_query_bindings_test.go b/backend/store/saved_query_bindings_test.gonew file mode 100644index 0000000000..af3e098c7e--- /dev/null+++ b/backend/store/saved_query_bindings_test.go@@ -0,0 +1,136 @@+package store_test++import (+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store"+)++// The bindings column holds a protojson array at the jsonb root, not a wrapper+// object. That shape is load-bearing: the access queries probe it with `@>`+// against the GIN index, and a wrapper would need an expression index instead.+// Nothing else asserts the shape directly, so a change to it would surface as+// sharing silently matching no rows.+func TestSavedQueryBindingsStoredShape(t *testing.T) {+ const seedSQL = `+ INSERT INTO saved_query (resource_id, creator, project, name, statement)+ VALUES ('saved-query-a', '[email protected]', 'project-a', 'Saved Query A', 'SELECT 1;');+ `+ fixture := newProjectDeletionLockOrderFixture(t, seedSQL)++ bindings := []*storepb.SavedQueryBinding{{+ Level: storepb.SavedQueryBinding_EDITOR,+ Members: []string{"groups/[email protected]", "users/[email protected]"},+ }}+ etag, err := store.SavedQueryPolicyEtag(nil)+ require.NoError(t, err)++ applied, err := fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", bindings, etag)+ require.NoError(t, err)+ require.True(t, applied)++ // A jsonb array at the root, so `jsonb_typeof` sees an array.+ var typ string+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,+ "SELECT jsonb_typeof(bindings) FROM saved_query WHERE resource_id = 'saved-query-a'").Scan(&typ))+ require.Equal(t, "array", typ)++ // The containment probe the access clause builds must match a member listed+ // alongside others, for both principal types.+ for _, probe := range []string{+ `[{"members":["users/[email protected]"]}]`,+ `[{"members":["groups/[email protected]"]}]`,+ } {+ var matched bool+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,+ "SELECT bindings @> $1::jsonb FROM saved_query WHERE resource_id = 'saved-query-a'", probe).Scan(&matched))+ require.True(t, matched, "probe %s must match the stored bindings", probe)+ }++ // A principal named by no binding must not match.+ var strangerMatched bool+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,+ "SELECT bindings @> $1::jsonb FROM saved_query WHERE resource_id = 'saved-query-a'",+ `[{"members":["users/[email protected]"]}]`).Scan(&strangerMatched))+ require.False(t, strangerMatched)++ // Compare-and-swap: the etag moved with the write, so replaying the old one+ // is rejected rather than clobbering the grants just stored.+ _, err = fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", nil, etag)+ require.ErrorIs(t, err, store.ErrSavedQueryEtagMismatch)++ newEtag, err := store.SavedQueryPolicyEtag(bindings)+ require.NoError(t, err)+ applied, err = fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", nil, newEtag)+ require.NoError(t, err)+ require.True(t, applied)++ // Revoking everything leaves an empty array, which reads back as no grants+ // and as the same etag an untouched saved query has.+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,+ "SELECT jsonb_typeof(bindings) FROM saved_query WHERE resource_id = 'saved-query-a'").Scan(&typ))+ require.Equal(t, "array", typ)++ // A saved query that no longer exists reports "not applied" rather than an+ // error, so the caller decides what a vanished row means.+ applied, err = fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "missing", nil, etag)+ require.NoError(t, err)+ require.False(t, applied)++ // The write is scoped to the project the caller named. A purge re-parents+ // its members' saved queries to the default project, so a request resolved+ // against the old project must land on nothing rather than on a row that+ // moved out from under it.+ _, err = fixture.db.ExecContext(fixture.ctx,+ "UPDATE saved_query SET project = 'default' WHERE resource_id = 'saved-query-a'")+ require.NoError(t, err)+ applied, err = fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", bindings, newEtag)+ require.NoError(t, err)+ require.False(t, applied, "a re-parented saved query is gone from the project the caller named")+}++// A group is named in a binding by its email, so renaming one has to carry its+// grants along or every saved query shared with it becomes unreachable to its+// members.+func TestSavedQueryBindingsFollowGroupRename(t *testing.T) {+ const seedSQL = `+ INSERT INTO user_group (id, email, workspace, name, description, payload)+ VALUES ('group-1', '[email protected]', 'default', 'Eng', '', '{}');+ INSERT INTO saved_query (resource_id, creator, project, name, statement)+ VALUES ('saved-query-a', '[email protected]', 'project-a', 'Saved Query A', 'SELECT 1;');+ `+ fixture := newProjectDeletionLockOrderFixture(t, seedSQL)++ emptyEtag, err := store.SavedQueryPolicyEtag(nil)+ require.NoError(t, err)+ applied, err := fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a",+ []*storepb.SavedQueryBinding{{+ Level: storepb.SavedQueryBinding_EDITOR,+ Members: []string{"groups/[email protected]", "users/[email protected]"},+ }}, emptyEtag)+ require.NoError(t, err)+ require.True(t, applied)++ newEmail := "[email protected]"+ _, err = fixture.store.UpdateGroup(fixture.ctx, &store.UpdateGroupMessage{+ ID: "group-1",+ Workspace: "default",+ Email: &newEmail,+ })+ require.NoError(t, err)++ // The renamed group's grant follows it; the untouched user member does not move.+ var matchedNew, matchedOld, matchedUser bool+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx, `+ SELECT bindings @> '[{"members":["groups/[email protected]"]}]'::jsonb,+ bindings @> '[{"members":["groups/[email protected]"]}]'::jsonb,+ bindings @> '[{"members":["users/[email protected]"]}]'::jsonb+ FROM saved_query WHERE resource_id = 'saved-query-a'+ `).Scan(&matchedNew, &matchedOld, &matchedUser))+ require.True(t, matchedNew, "the grant must follow the rename")+ require.False(t, matchedOld, "the stale token must be gone")+ require.True(t, matchedUser, "unrelated members must be untouched")+}diff --git a/backend/store/saved_query_lock_order_test.go b/backend/store/saved_query_lock_order_test.goindex d8ef7da0dd..3adb20367e 100644--- a/backend/store/saved_query_lock_order_test.go+++ b/backend/store/saved_query_lock_order_test.go@@ -7,6 +7,7 @@ import ("github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/store")@@ -390,3 +391,91 @@ func TestCreateSavedQueryRejectsInactiveProject(t *testing.T) {require.NoError(t, err)require.NotEmpty(t, created.ResourceID)}++// SetSavedQueryBindings updates one existing row and touches no child table, so+// it cannot form a wait-for cycle with the purge by itself. What it can do is+// race project deletion, and both orders must reach a terminal outcome: either+// the policy lands and the purge then removes the row, or the purge wins and the+// write reports the saved query as gone rather than failing on the FK.+func TestSavedQuerySetBindingsAndDeleteProjectLockOrder(t *testing.T) {+ const seedSQL = `+ INSERT INTO service_account (name, email, workspace, service_key_hash, project)+ VALUES ('service account', '[email protected]', 'default', 'unused', 'project-a');+ INSERT INTO saved_query (resource_id, creator, project, name, statement)+ VALUES ('saved-query-a', '[email protected]', 'project-a', 'Saved Query A', '');+ INSERT INTO saved_query_star (saved_query, principal) VALUES+ ('saved-query-a', '[email protected]');+ `++ bindings := []*storepb.SavedQueryBinding{{+ Level: storepb.SavedQueryBinding_VIEWER,+ Members: []string{"user:[email protected]"},+ }}++ requireGone := func(t *testing.T, fixture *projectDeletionLockOrderFixture) {+ t.Helper()+ var count int+ require.NoError(t, fixture.db.QueryRowContext(fixture.ctx,+ "SELECT COUNT(*) FROM saved_query WHERE resource_id = 'saved-query-a'").Scan(&count))+ require.Zero(t, count, "the purge owns the terminal state in both orders")+ require.Zero(t, savedQueryStarCount(t, fixture))+ }++ emptyEtag, err := store.SavedQueryPolicyEtag(nil)+ require.NoError(t, err)++ t.Run("purge first", func(t *testing.T) {+ fixture := newProjectDeletionLockOrderFixture(t, seedSQL)+ const barrierID = 9951+ barrier := newMaintenanceLockBarrier(fixture.ctx, t, fixture.db, barrierID)+ // The barrier has to fire where the purge actually holds the+ // saved_query row: pausing it after the star delete leaves that row+ // unlocked, so the policy write would sail past and prove nothing.+ installMaintenanceLockBarrier(t, fixture.db, barrierID,+ "AFTER DELETE ON saved_query FOR EACH ROW")++ purgeResult := make(chan error, 1)+ go func() { purgeResult <- fixture.store.DeleteProject(fixture.ctx, "default", "project-a") }()+ waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)+ purgePID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)++ setResult := make(chan error, 1)+ go func() {+ _, err := fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", bindings, emptyEtag)+ setResult <- err+ }()+ waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, purgePID)+ barrier.release(t)++ requireMaintenanceResult(t, purgeResult)+ // The row is gone by the time the lock is granted, which the store+ // reports as "not applied" (a nil error) rather than an FK failure.+ requireMaintenanceResult(t, setResult)+ requireGone(t, fixture)+ })++ t.Run("policy write first", func(t *testing.T) {+ fixture := newProjectDeletionLockOrderFixture(t, seedSQL)+ const barrierID = 9952+ barrier := newMaintenanceLockBarrier(fixture.ctx, t, fixture.db, barrierID)+ installMaintenanceLockBarrier(t, fixture.db, barrierID,+ "AFTER UPDATE OF bindings ON saved_query FOR EACH ROW")++ setResult := make(chan error, 1)+ go func() {+ _, err := fixture.store.SetSavedQueryBindings(fixture.ctx, "project-a", "saved-query-a", bindings, emptyEtag)+ setResult <- err+ }()+ waitForMaintenanceBarrier(fixture.ctx, t, fixture.db, barrierID)+ setPID := maintenanceBarrierWaitingPID(fixture.ctx, t, fixture.db, barrierID)++ purgeResult := make(chan error, 1)+ go func() { purgeResult <- fixture.store.DeleteProject(fixture.ctx, "default", "project-a") }()+ waitForBackendBlockedByPID(fixture.ctx, t, fixture.db, setPID)+ barrier.release(t)++ requireMaintenanceResult(t, setResult)+ requireMaintenanceResult(t, purgeResult)+ requireGone(t, fixture)+ })+}diff --git a/backend/tests/saved_query_test.go b/backend/tests/saved_query_test.goindex eafa70c201..e3b69d458a 100644--- a/backend/tests/saved_query_test.go+++ b/backend/tests/saved_query_test.go@@ -446,8 +446,8 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {ownerToken := ctl.authInterceptor.token- createSavedQuery := func(title, folder string) {- _, err := ctl.savedQueryServiceClient.CreateSavedQuery(ctx, connect.NewRequest(&v1pb.CreateSavedQueryRequest{+ createSavedQuery := func(title, folder string) *v1pb.SavedQuery {+ resp, err := ctl.savedQueryServiceClient.CreateSavedQuery(ctx, connect.NewRequest(&v1pb.CreateSavedQueryRequest{Parent: ctl.project.Name,SavedQuery: &v1pb.SavedQuery{Title: title,@@ -456,6 +456,7 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {},}))a.NoError(err)+ return resp.Msg}createSavedQuery("owner", "owner/child")@@ -495,7 +496,7 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {}))a.NoError(err)ctl.authInterceptor.token = loginResp.Msg.Token- createSavedQuery("other-users", "theirs/deep")+ theirSavedQuery := createSavedQuery("other-users", "theirs/deep")// Each caller sees only their own folder paths, with ancestor prefixes.otherFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{@@ -514,15 +515,16 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {a.NoError(err)a.Empty(notMineForOther.Msg.Folders)- // Unfiltered means "every folder I can read", so the admin backstop sees- // the other creator's folders too. The My/Shared split the SQL Editor- // renders comes from the creator filter, asserted below.+ // 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.ctl.authInterceptor.token = ownerTokenownerFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{Parent: ctl.project.Name,}))a.NoError(err)- a.Equal([]string{"owner", "owner-second", "owner/child", "theirs", "theirs/deep"}, ownerFolders.Msg.Folders)+ a.Equal([]string{"owner", "owner-second", "owner/child"}, ownerFolders.Msg.Folders)ownFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{Parent: ctl.project.Name,@@ -531,12 +533,32 @@ func TestSearchSavedQueryFoldersReturnsCallerFolders(t *testing.T) {a.NoError(err)a.Equal([]string{"owner", "owner-second", "owner/child"}, ownFolders.Msg.Folders)- // The admin backstop is what makes the SQL Editor's shared tree work:- // everyone-else's folders resolve server-side, so a cold cache still- // renders the folders holding saved queries the caller never opened.+ // A grant is what makes the SQL Editor's shared tree work. The folder of a+ // saved query somebody else filed resolves server-side once it is shared,+ // so a cold cache still renders folders holding rows the caller never+ // opened -- without one, a foldered shared row would be unreachable,+ // because the client can only expand into folders this call reports.+ ctl.authInterceptor.token = loginResp.Msg.Token+ theirPolicy, err := ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{+ Resource: theirSavedQuery.Name,+ }))+ a.NoError(err)+ _, err = ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{+ Resource: theirSavedQuery.Name,+ Policy: &v1pb.SavedQueryPolicy{+ Etag: theirPolicy.Msg.Etag,+ Bindings: []*v1pb.SavedQueryBinding{{+ Level: v1pb.SavedQueryBinding_VIEWER,+ Members: []string{fmt.Sprintf("user:%s", ownerEmail)},+ }},+ },+ }))+ a.NoError(err)++ ctl.authInterceptor.token = ownerTokensharedFolders, err := ctl.savedQueryServiceClient.SearchSavedQueryFolders(ctx, connect.NewRequest(&v1pb.SearchSavedQueryFoldersRequest{Parent: ctl.project.Name,- Filter: fmt.Sprintf(`creator != "users/%s"`, ownerEmail),+ Filter: "shared == true",}))a.NoError(err)a.Equal([]string{"theirs", "theirs/deep"}, sharedFolders.Msg.Folders)@@ -743,3 +765,203 @@ func findSavedQueryByName(savedQueries []*v1pb.SavedQuery, name string) *v1pb.Sa}return nil}++// 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.+func TestSavedQuerySharing(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++ granteeEmail := fmt.Sprintf("saved-query-grantee-%[email protected]", generateRandomString("user"))+ granteePassword := "1024bytebase"+ grantee, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Email: granteeEmail,+ Password: granteePassword,+ Title: "Saved Query Grantee",+ },+ }))+ a.NoError(err)+ _, err = ctl.addMemberToWorkspaceIAM(ctx, grantee.Msg.Workspace, fmt.Sprintf("user:%s", granteeEmail), "roles/workspaceMember")+ a.NoError(err)++ // The grantee needs the project's saved-query surface to discover anything;+ // the binding is what carries content access on top of it.+ policyResp, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{+ Resource: ctl.project.Name,+ }))+ a.NoError(err)+ projectPolicy := policyResp.Msg+ projectPolicy.Bindings = append(projectPolicy.Bindings, &v1pb.Binding{+ Role: "roles/sqlEditorUser",+ Members: []string{fmt.Sprintf("user:%s", granteeEmail)},+ })+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{+ Resource: ctl.project.Name,+ Policy: projectPolicy,+ }))+ a.NoError(err)++ createResp, err := ctl.savedQueryServiceClient.CreateSavedQuery(ctx, connect.NewRequest(&v1pb.CreateSavedQueryRequest{+ Parent: ctl.project.Name,+ SavedQuery: &v1pb.SavedQuery{+ Title: "shared-query",+ Content: []byte("SELECT 1;"),+ },+ }))+ a.NoError(err)+ savedQuery := createResp.Msg++ // A new saved query starts private: no bindings.+ getPolicyResp, err := ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ }))+ a.NoError(err)+ a.Empty(getPolicyResp.Msg.Bindings)+ a.NotEmpty(getPolicyResp.Msg.Etag, "etag is what the next write has to present")+ initialEtag := getPolicyResp.Msg.Etag++ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: granteeEmail,+ Password: granteePassword,+ }))+ a.NoError(err)+ granteeToken := loginResp.Msg.Token++ asGrantee := func(f func()) {+ ctl.authInterceptor.token = granteeToken+ defer func() { ctl.authInterceptor.token = ownerToken }()+ f()+ }++ // Private: invisible, and NotFound rather than PermissionDenied so the name+ // cannot be probed.+ asGrantee(func() {+ _, err := ctl.savedQueryServiceClient.GetSavedQuery(ctx, connect.NewRequest(&v1pb.GetSavedQueryRequest{+ Name: savedQuery.Name,+ }))+ a.Error(err)+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))++ searchResp, err := ctl.savedQueryServiceClient.SearchSavedQueries(ctx, connect.NewRequest(&v1pb.SearchSavedQueriesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.NotContains(savedQueryNames(searchResp.Msg.SavedQueries), savedQuery.Name)+ })++ setPolicy := func(level v1pb.SavedQueryBinding_Level, etag string) *v1pb.SavedQueryPolicy {+ resp, err := ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ Policy: &v1pb.SavedQueryPolicy{+ Etag: etag,+ Bindings: []*v1pb.SavedQueryBinding{+ {Level: level, Members: []string{fmt.Sprintf("user:%s", granteeEmail)}},+ },+ },+ }))+ a.NoError(err)+ return resp.Msg+ }++ viewerPolicy := setPolicy(v1pb.SavedQueryBinding_VIEWER, initialEtag)+ a.NotEqual(initialEtag, viewerPolicy.Etag, "the etag moves with the grants")++ // A stale etag must not silently reinstate what somebody just revoked.+ _, err = ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ Policy: &v1pb.SavedQueryPolicy{+ Etag: initialEtag,+ Bindings: nil,+ },+ }))+ a.Error(err)+ a.Equal(connect.CodeAborted, connect.CodeOf(err))++ // VIEWER: reads, and shows up under shared == true, but cannot write.+ asGrantee(func() {+ getResp, err := ctl.savedQueryServiceClient.GetSavedQuery(ctx, connect.NewRequest(&v1pb.GetSavedQueryRequest{+ Name: savedQuery.Name,+ }))+ a.NoError(err)+ a.Equal("shared-query", getResp.Msg.Title)++ sharedResp, err := ctl.savedQueryServiceClient.SearchSavedQueries(ctx, connect.NewRequest(&v1pb.SearchSavedQueriesRequest{+ Parent: ctl.project.Name,+ Filter: "shared == true",+ }))+ a.NoError(err)+ a.Contains(savedQueryNames(sharedResp.Msg.SavedQueries), savedQuery.Name)++ _, err = ctl.savedQueryServiceClient.UpdateSavedQuery(ctx, connect.NewRequest(&v1pb.UpdateSavedQueryRequest{+ SavedQuery: &v1pb.SavedQuery{Name: savedQuery.Name, Title: "renamed by viewer"},+ 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")++ // Grantees read their own level through the policy; they cannot rewrite it.+ policy, err := ctl.savedQueryServiceClient.GetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.GetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ }))+ a.NoError(err)+ a.Len(policy.Msg.Bindings, 1)+ a.Equal(v1pb.SavedQueryBinding_VIEWER, policy.Msg.Bindings[0].Level)++ _, err = ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ Policy: &v1pb.SavedQueryPolicy{Etag: policy.Msg.Etag},+ }))+ a.Error(err)+ a.Equal(connect.CodePermissionDenied, connect.CodeOf(err))+ })++ editorPolicy := setPolicy(v1pb.SavedQueryBinding_EDITOR, viewerPolicy.Etag)++ // EDITOR: writes content, but never deletes and never re-files.+ asGrantee(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))++ _, 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")++ _, 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")+ })++ // Revoking drops the grantee back to invisible.+ _, err = ctl.savedQueryServiceClient.SetSavedQueryPolicy(ctx, connect.NewRequest(&v1pb.SetSavedQueryPolicyRequest{+ Resource: savedQuery.Name,+ Policy: &v1pb.SavedQueryPolicy{Etag: editorPolicy.Etag},+ }))+ a.NoError(err)++ asGrantee(func() {+ _, err := ctl.savedQueryServiceClient.GetSavedQuery(ctx, connect.NewRequest(&v1pb.GetSavedQueryRequest{+ Name: savedQuery.Name,+ }))+ a.Error(err)+ a.Equal(connect.CodeNotFound, connect.CodeOf(err))+ })+}diff --git a/docs/design/saved-queries-model.md b/docs/design/saved-queries-model.mdindex 7aa93e95e0..5102063faa 100644--- a/docs/design/saved-queries-model.md+++ b/docs/design/saved-queries-model.md@@ -45,10 +45,9 @@ 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) is gated by a dedicated- `bb.savedQueries.search` permission carried by the human project roles —- automation roles stay off the surface (`manage` passes too — the admin- backstop);+ *discovery* (Search, always per-project and always caller-scoped) 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. Leavinga project ends discovery and run; explicit grants persist untilrevoked.@@ -212,314 +211,340 @@ Alternatives the rejected options.### Model and access rules-A saved query carries a policy of per-object grants; the `creator` is the-immutable owner; a private saved query has no bindings. **Ownership is a-typed principal** — following BigQuery, whoever holds `create` owns what-they create, so `creator` may be a user (`users/{email}`) or a service-account / workload identity (`serviceAccounts/{email}`, …); `read/write/-share/delete`'s `u == s.creator` compares by principal identity, any type.-Only *sharing* is narrower: binding members stay `user:`/`group:` (below),-so a service account can own and run its own automation queries but is-never a grantee — its access comes from being the creator (or an admin).+Three things grant access to a saved query, and nothing else does:++- **Creator.** Whoever created it owns it, permanently. Ownership never+ 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).```-Grant levels: VIEWER (open, read) < EDITOR (+ write content/title/database)+Grant levels: VIEWER (open, read) < EDITOR (+ write title/content/database)Principals: user:{email} | group:{email}```-**Member format follows `bytebase.v1.IamPolicy` exactly** — the same-`user:`/`group:` binding prefixes (`common.UserBindingPrefix` /-`GroupBindingPrefix`) the project and workspace policies use, restricted to-the `user:` and `group:` types (no `allUsers`, `serviceAccount:`, or-`workloadIdentity:`). This is a deliberate invariant: principal parsing,-group expansion, and the share-with-project snapshot all reuse the existing-IAM machinery unchanged, and a project binding copies into a saved-query-binding verbatim.--The whole model (G1); every RPC gate derives from these. Notation: `u` is-the caller, `P` a project, `s` a saved query, `s.project` its owning-project; "holds" means any of `u`'s role bindings — project-level (direct-or via a group) or workspace-level — grants the permission. Binding-conditions are handled precisely: expiry (`request.time`) is honored, but-a binding whose condition scopes *resources* (databases, environments)-confers **no** `bb.savedQueries.*` permission at all — saved-query-surfaces are project-wide, and a data-slice grant must not silently widen-to them. The generic interceptor cannot enforce this (it evaluates-`request.time` only and passes residual resource conditions), so the rule-lives where saved-query code evaluates permissions: the CUSTOM gates, and-an in-handler source re-check on **both** IAM methods (`create`, `list`)-that rejects resource-conditioned bindings (see Per-RPC access). Same-narrowing stance as the snapshot's condition skip:+The creator may be any principal type — a user, a service account, a workload+identity — since whoever holds `create` owns what they create. Only *sharing*+is narrower: binding members are `user:` and `group:` only, so a service+account can own and run its own automation queries but is never a grantee.++Member format follows `bytebase.v1.IamPolicy` exactly, on both sides of the+boundary it draws. The API takes the binding form (`user:`, `group:`), minus+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 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.```-admin(u, P) = u holds bb.savedQueries.manage on P -- the dataform.admin backstop-grant(s, u) = max level (VIEWER|EDITOR) among s.bindings whose principal is in principals(u)+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+discover(u, P) = u holds bb.savedQueries.search on P -- gates Search, not contentread(s, u) = admin(u, s.project) OR u == s.creator OR grant(s, u) >= VIEWERwrite(s, u) = admin(u, s.project) OR u == s.creator OR grant(s, u) >= EDITOR-share(s, u) = admin(u, s.project) OR u == s.creator -- manage the policy+share(s, u) = admin(u, s.project) OR u == s.creatordelete(s, u) = admin(u, s.project) OR u == s.creator```-The four role permissions the rules reference (G3–G6) — everything between-them (who reads, edits, re-shares a *specific* saved query) is that query's-own bindings:+#### The four permissions| Permission | Meaning ||---|---|| `bb.savedQueries.create` | Create saved queries in the project |-| `bb.savedQueries.search` | Discover: the per-member Search and folder list (results still filtered to `read(s,u)`) |-| `bb.savedQueries.list` | Auditor: enumerate/filter in scope (project or `projects/-`), read-only, ignoring grants |-| `bb.savedQueries.manage` | Admin: read/write/re-share/delete any saved query in scope, incl. private |--There is no `get` permission — bindings decide reads (`bb.worksheets.get`-is dropped, not renamed). `search` is a dedicated permission rather than a-ride on `bb.projects.get` (see Alternatives) so custom roles can control-the saved-query surface independently of project visibility; the decoupled-combos are API-level shapes — the UI needs `bb.projects.get` to render-project context, and every search-carrying role also holds it. `list` and-`manage` can read content in scope — that is their purpose — so neither-belongs in default member roles (decision 7). Role mapping: the human project roles — `projectOwner`,-`projectDeveloper`, `sqlEditorUser`, `sqlEditorReadUser`, `projectViewer` —-carry `create` and `search`; the automation roles (`projectReleaser`,-`gitopsServiceAgent`) carry **neither**, keeping CI principals off the-saved-query surface entirely — which is what makes the share-with-project-snapshot's role filter meaningful for them. `projectOwner` carries-project-scoped `list` + `manage`; `workspaceAdmin`/`workspaceDBA` carry-**all four** workspace-scoped — they are human operator roles, and an-admin who could manage everyone's queries yet not draft their own would-be absurd. `manage` implies the Search gate — Search evaluates-`discover ∨ admin` in the handler — so a manage-only custom role can-still enumerate what it manages; there is no hidden permission-coupling.--The gates are **layered, exactly as new BigQuery enforces them** (G3): the-per-object grant carries content access (`codeViewer/Editor` on the asset);-a dedicated permission gates **discovery** — `SearchSavedQueries`-requires `bb.savedQueries.search` or `manage` (the backstop must be able-to enumerate what it manages), the exact `dataform.repositories.list`-analog, always per-project (no cross-project "shared with me"; no peer-has one); and-**running** always passes the SQL Editor's own database grants, the-`bigquery.jobUser` analog. A grantee who is not a project member opens the-saved query by its link — BigQuery's own sharing flow, "grant the role,-then share the link" — but cannot browse the project or run anything in-it. Databricks and Snowflake enforce their container structurally (an ACL-can only name a workspace/account user); BigQuery and this design let a-grant name any workspace identity, expressing the container through the-discovery and run gates instead.--**Offboarding.** Removing a user from a project ends discovery and run-immediately (workspace-wide roles aside — those reach every project by-design). Explicitly granted content access — and the creator's access to-their own queries — persists until revoked, and the revocation surface is-explicit: an offboarding review is **two `ListSavedQueries` filters** over-the target. `creator == target` lists the rows they own — no binding-exists for these, so no member filter can find them (remediation: an-admin deletes them, or deliberately leaves the departed user their own-drafts). `member == target`, given a `user:` principal, **expands the-target's group memberships server-side** — the same `principals(u)`-expansion the read path uses — listing rows granted directly *and* via-any of the user's groups (a `group:` principal matches that group's-rows); direct grants strip via `SetIamPolicy`, while group-held access is-revoked at the group (leave or edit it), not per-query — a group grant's-audience is deliberately the live group, and workspace deactivation ends-everything. This is precisely BigQuery's-behavior. The audit's Problem-1 complaint was never retention itself but-*implicit* retention — flag-derived access with no grant to see, audit,-or revoke.--**Share-with-project is a snapshot.** There is deliberately no derived-"everyone in the project" principal (see Alternatives); the share dialog's-*Share with project* shortcut writes the project's current IAM principals —-`group:` and `user:` bindings, not an expansion of members — into the-policy at the chosen level. The source is the project's **effective**-role bindings, not just its own policy row: a project role granted from-the *workspace* IAM policy applies to every project, so those bindings are-folded in too (the same "holds on P" the `discover` gate uses) — otherwise-a workspace-level project member would pass discovery yet be silently-omitted from the share. Only bindings **whose role carries-`bb.savedQueries.search` but *not* `bb.savedQueries.manage`** are included.-Two exclusions, one rule — snapshot only principals whose sole path to the-query *is* a per-object grant: a role kept off the saved-query surface (a-CI releaser) has no `search` and must not be swept in; an admin role-(`workspaceAdmin`/`workspaceDBA`, or `projectOwner`) reaches the query-through the `manage` **backstop**, not a grant, so freezing it into a-VIEWER/EDITOR binding is both redundant *and* a residual-access bug —-the grant would outlive the admin role and leave a former operator-deep-link access. That leaves the pure project audience-(`projectDeveloper`, `sqlEditorUser`, `sqlEditorReadUser`, `projectViewer`),-which is exactly who "share with everyone here" means. `allUsers` members — which-self-hosted project IAM permits — are **skipped, never expanded**: the-per-object policy accepts only `user:` and `group:` principals-(`SetIamPolicy` rejects anything else), and freezing a workspace-wide-audience into per-user grants would be exactly the member explosion the-snapshot avoids. The dialog surfaces the skip so the sharer can grant a-group instead. Snapshots keep group dynamism (a group-gaining a member propagates, since the entry stores the group reference) but-not membership dynamism (a principal added to the project later is re-shared-by the owner, as in every group-based peer). Project bindings carrying a CEL-`condition` (expiring or scoped access) are **skipped**: a time-bounded-grant cannot be faithfully frozen into an unconditional one, and for a-governance product under-granting (the owner re-shares) beats silently-converting expiring access into permanent access.--**Ownership does not transfer** (G4): the creator alone (plus admins)-re-shares or deletes. Transfer/co-ownership would add a tier and an-orphan-guard for a case the admin backstop and fork-a-copy already cover.-**The admin backstop** (`bb.savedQueries.manage`) matches `dataform.admin`-and Databricks workspace admins: read/write/re-share/delete anything in-scope, private included — a deliberate privacy reversal (decision 5) that-makes orphan cleanup and incident response possible.+| `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: read/write/re-share/delete anything in scope, private included |++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.++#### Layered gates++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` |+| Discovery | `bb.savedQueries.search` on the project | `dataform.repositories.list` |+| Running | the SQL Editor's own database permissions | `bigquery.jobUser` |++So a grantee outside the project opens the saved query by link — BigQuery's own+"grant the role, then share the link" flow — but cannot browse the project or+run anything in it. Discovery is always per-project; there is no cross-project+"shared with me", and no peer has one.++**Conditioned role bindings.** Expiry (`request.time`) is honored. A binding+whose condition scopes *resources* — databases, environments — confers **no**+`bb.savedQueries.*` permission at all: these surfaces are project-wide, and a+data-slice grant must not silently widen to them. The generic interceptor+cannot enforce this (it evaluates `request.time` only and passes residual+resource conditions), so the rule lives in saved-query code: the CUSTOM gates,+plus an in-handler source re-check on both IAM methods, `create` and `list`.++#### Offboarding++Removing a user from a project ends discovery and running immediately+(workspace-wide roles aside — those reach every project by design). Explicit+grants, and the creator's access to their own queries, persist until revoked.+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.++Users can always see what they hold: `SearchSavedQueries` with `shared == true`+returns everything shared with the caller.++What v1 does not ship is the third-party direction — a bulk "what is still+shared with *this other person*" sweep. Search cannot answer it, since it+scopes to the caller's own readable set. `ListSavedQueries` filters by+`creator`, which finds what the departing user owns (no grant-based filter+could find those anyway; an admin deletes them, or deliberately leaves them+their drafts), but there is no `member` filter and bindings are not on the+`SavedQuery` resource, so enumerating someone's residual grants means walking+`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+`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+explicit objects with a read and a write API, which answers it.++#### Share with project++There is deliberately no derived "everyone in the project" principal (see+Alternatives). The share dialog's *Share with project* shortcut instead+snapshots the project's current principals into the policy at the chosen+level, as `user:` and `group:` bindings — never an expansion of group members.++The source is the project's **effective** role bindings, not just its own+policy row: a project role granted at the workspace level applies to every+project, so those fold in too. Otherwise a workspace-level project member+would pass discovery yet be silently missing from the share.++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 |+| `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 |++What remains is the pure project audience — `projectDeveloper`,+`sqlEditorUser`, `sqlEditorReadUser`, `projectViewer` — which is exactly who+"share with everyone here" means.++A snapshot keeps group dynamism (a group gaining a member propagates, since the+binding stores the group reference) but not membership dynamism: a principal+added to the project later is re-shared by the owner, as in every group-based+peer.+### API and authorization-Sharing is a policy on the resource, managed via a-`GetIamPolicy`/`SetIamPolicy` pair — new BigQuery's shape; Databricks and-Snowflake likewise keep permissions on a dedicated surface. Because Bytebase-has no resource-level role store below the project, the policy carries-capability **levels** grouped by member list, evaluated by the saved-query-handlers, not central `CheckPermission` (decision 6). `SetIamPolicy` is-**compare-and-swap**: `GetIamPolicy` returns an `etag`, `SetIamPolicy`-must present it, and a mismatch aborts for refetch — a full-replacement-write may never silently overwrite a concurrent revocation (the-offboarding race). **`GetIamPolicy` is gated on `share(s,u)`, not-`read(s,u)`** — reading the full member list is a sharer/admin operation,-as in GCP (`getIamPolicy` is its own privileged permission) and Bytebase's-project policy. An ordinary VIEWER/EDITOR never needs the roster: their own-capability arrives as `effective_level` on every row, so a query shared-with a contractor or a narrow partner group does not leak the rest of the-ACL to them.--**Database is project-scoped.** `database` is an ordinary `write(s,u)`-field, but with one invariant `CreateSavedQuery`/`UpdateSavedQuery` enforce-(carried over from today's `getWorksheetDatabase`): a set database must-belong to the saved query's **own project**, and is stored canonically. A+Sharing is a policy on the resource, read and written by the+`GetSavedQueryPolicy`/`SetSavedQueryPolicy` pair — new BigQuery's shape, and+Databricks and Snowflake likewise keep permissions on a dedicated surface. The+pair is named for the resource rather than reusing `GetIamPolicy`/`SetIamPolicy`,+which already exist on `ProjectService` and `WorkspaceService` returning+`bytebase.v1.IamPolicy`: one method name with two return types across the same+API is a trap on the generated SDK and OpenAPI surfaces.++Because Bytebase has no resource-level role store below the project, the policy+carries capability **levels** grouped by member list, evaluated by the+saved-query handlers rather than the central `CheckPermission` (decision 6).++Two properties matter:++- **`SetSavedQueryPolicy` is compare-and-swap.** `GetSavedQueryPolicy` returns+ 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)`.++ An earlier revision filtered the response so a grantee saw only their own+ bindings. Dropped as unnecessary: any authenticated user can already list+ every user in the workspace, so all the filtering concealed was which of+ those colleagues hold a grant on this query, from someone who holds one+ themselves. It also had no peer — GCP's `getIamPolicy` is all-or-nothing —+ and it bought a second response shape plus an invariant about not writing a+ partial view back. Seeing who else can reach a query you can reach is+ arguably the better governance property anyway.++**Database is project-scoped.** `database` is an ordinary `write(s,u)` field+with one invariant, carried over from today's `getWorksheetDatabase`: a set+database must belong to the saved query's own project, stored canonically. Aproject-A editor cannot pin a project-B database onto a project-A query —-otherwise Get/Search responses and the deep link would become a-cross-project metadata surface even though running still needs that-database's own grants. Empty is allowed (no connected database); the-reference stays soft (nullable, no FK) and may dangle after the database is-deleted or transferred, degrading to "no database" in the UI.--**Per-RPC access.** `CreateSavedQuery` and `ListSavedQueries` are IAM — a-single family permission checked at the interceptor. Because the platform's-generic check evaluates conditions with `request.time` only and passes-residual resource conditions, **both re-check the permission source-in-handler and reject resource-conditioned bindings**, enforcing the family-condition rule uniformly: a database- or environment-scoped role confers-neither `list`'s content read nor `create`'s project-wide row. The search-family (`SearchSavedQueries`, `SearchSavedQueryFolders`)-is CUSTOM — its gate is `discover(u, P) ∨ admin(u, P)`, an OR the-single-permission interceptor cannot express — and every object method is-a CUSTOM per-row predicate.--`SearchSavedQueries` and `ListSavedQueries` are **two enumeration surfaces-for two use cases**, not redundant: Search is the **SQL Editor** — a member-browsing what they can use *in one project* (My / Shared / Starred),-grant-respecting, preview-only, on the hot path; List is **governance** — an-auditor or service account enumerating by `creator` (or other metadata)-*across projects* (`projects/-`), grant-independent, full content,-`bb.savedQueries.list`-gated. They overlap only for an admin within a single-project (both can surface every row), by different lenses. One boundary is-deliberately left out: a member has **no cross-project "all my own queries"-view** — discovery is per-project (peer-consistent with BigQuery/Databricks),-and the only `projects/-` path is the privileged audit List. If a-self-scoped cross-project view is later wanted, it is safe to add without-`list` — a `creator == me` query exposes only the caller's own rows, an-additive relaxation, not a new surface.+otherwise Get/Search responses and the deep link become a cross-project+metadata surface, even though running still needs that database's own grants.+Empty is allowed, and the reference stays soft (nullable, no FK), so it may+dangle after the database is deleted or transferred and degrade to "no+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.| RPC | Auth | Gate | Content / audit ||---|---|---|---|-| `CreateSavedQuery` | IAM `create` + handler source re-check | creator becomes owner | writes own; audited |-| `SearchSavedQueries` | CUSTOM | `discover ∨ admin` → rows where `read(s,u)`; admin: all | previews; unaudited |-| `ListSavedQueries` | IAM `list` + handler source re-check | all rows matching `filter`; `projects/-` allowed | full content (FULL); unaudited |+| `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 |+| `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 || `DeleteSavedQuery` | CUSTOM | `delete(s,u)` | — ; audited |-| `GetIamPolicy` | CUSTOM | `share(s,u)` — sharer/admin only (see below) | policy only; unaudited |-| `SetIamPolicy` | CUSTOM | `share(s,u)` + etag CAS | policy only; audited |+| `GetSavedQueryPolicy` | CUSTOM | `read(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 || `BatchUpdateSavedQueries` | CUSTOM | rows the caller may re-file (creator; admin: any); mask limited to `folder` | count only; audited |-| `SearchSavedQueryFolders` | CUSTOM | `discover ∨ admin` → the caller's own folder paths | paths only; unaudited |--Duplicate/fork needs no RPC: read what you can already see, then-`CreateSavedQuery` — the copy is yours and private.--**Audit events.** Today's `WorksheetService` carries **no**-`bytebase.v1.audit` annotations at all (sheet and database services do) —-this design closes that gap, under one invariant: **the audit log records-changes, not lookups.** Every RPC that mutates a saved query or its policy-is annotated — `CreateSavedQuery`, `UpdateSavedQuery`,-`BatchUpdateSavedQueries`, `DeleteSavedQuery`, and `SetIamPolicy` (the-share event) — and no read RPC is. This is the same line the rest of the-v1 API draws, and it keeps the annotation set derivable from the method-rather than from who the caller happened to be.--The reads left unaudited include two privileged ones, deliberately:-`GetSavedQuery`/`SearchSavedQueries` under the admin backstop, and the-grant-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 read trail behind them — and a read-trail on the SQL Editor's own hot path would be mostly the caller reading-their own drafts. This drops the earlier revision's read-side machinery:-Search returns previews for every row the caller can read, admin-override-rows included (no metadata-only carve-out), and `UpdateSavedQuery` is-audited outright rather than only when it exercises the override.--Two costs, stated plainly. First, **autosave writes are audit events**:-the editor saves on a 2-second debounce, so an active editing session-emits an audit row every couple of seconds, and saved-query writes will-dominate the log by volume — the price of a rule that does not special-case-the hot path. Second, **a shared query keeps no per-editor trail** in the-resource itself: the fixed `creator` names the owner, not whoever last-edited, so multi-editor changes are last-write-wins and the updater's-identity lives only in the audit event; add version history if that ever-matters. `UpdateSavedQueryStar` is a write but stays unaudited — a-per-user marker that carries no content and no access. `GetIamPolicy` and-the folder listing return no content and are unaudited.--**Compatibility: hard cutover, no shim** (decision 8). `WorksheetService`-and the `visibility` field are removed in the release that ships-`SavedQueryService`; the in-repo frontend ships against the new API in the-same release. Post-rename, a shim is not a deprecated field but an entire-second service to maintain and secure — for a UI-owned feature. Cost:-external worksheet scripts break loudly at upgrade, documented in the-changelog.+| `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+`CreateSavedQuery`. The copy is yours, and private.++#### Search versus List++Two enumeration surfaces for two use cases, not redundant:++| | `SearchSavedQueries` | `ListSavedQueries` |+|---|---|---|+| For | The SQL Editor | Governance |+| Scope | One project | One project, or `projects/-` |+| Bindings | Respected; admins not widened | 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+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+without `list` — `creator == me` exposes only the caller's own rows.++The SQL Editor's Shared view is `shared == true`, not `creator != me`. The two+diverge for an admin, for whom `creator != me` also matches saved queries nobody+shared with them.++#### Audit events++Today's `WorksheetService` carries no `bytebase.v1.audit` annotations at all,+though sheet and database services do. This design closes that gap under one+invariant: **the audit log records changes, not lookups.** Every RPC that+mutates a saved query or its policy is annotated — `CreateSavedQuery`,+`UpdateSavedQuery`, `BatchUpdateSavedQueries`, `DeleteSavedQuery`,+`SetSavedQueryPolicy` — and no read RPC is. That keeps the annotation set+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.++Two costs, stated plainly:++- **Autosave writes are audit events.** The editor saves on a 2-second debounce,+ so an active session emits a row every couple of seconds and saved-query+ writes will dominate the log by volume. That is the price of a rule that does+ not special-case the hot path.+- **A shared query keeps no per-editor trail** in the resource. The fixed+ `creator` names the owner, not whoever last edited, so multi-editor changes+ are last-write-wins and the updater's identity lives only in the audit event.+ Add version history if that ever matters.++`UpdateSavedQueryStar` is a write but stays unaudited — a per-user marker+carrying no content and no access. `GetSavedQueryPolicy` and the folder listing+return no content and are unaudited.++#### Compatibility++**Hard cutover, no shim** (decision 8). `WorksheetService` and the `visibility`+field are removed in the release that ships `SavedQueryService`, and the in-repo+frontend ships against the new API in the same release. After the rename a shim+would not be a deprecated field but an entire second service to maintain and+secure, for a UI-owned feature. External worksheet scripts break loudly at+upgrade, documented in the changelog.**Existing data migrates owner-private** — a deliberate, one-time breaking-change. Every existing row keeps its `creator`, `title`, `content`, and its-connected-database reference (carried into the payload as the database's-canonical resource name, `SavedQueryPayload.database` — so run context-survives and the name encodes workspace- vs project-instance scope; cleared-only if that database no longer belongs to the query's project, per the-same-project invariant);+change, and BigQuery's own classic→modern path. Every row keeps its `creator`,+`title`, `content`, and connected database (carried into+`SavedQueryPayload.database` as a canonical resource name, so run context+survives; cleared if that database no longer belongs to the query's project).`visibility` is dropped and `bindings` starts empty, so `PRIVATE`,-`PROJECT_READ`, and `PROJECT_WRITE` alike become creator-only. **Owner-organization is preserved**: the creator's own `worksheet_organizer` row-migrates — its folder placement into `saved_query.folder`, its `starred`-flag into a `saved_query_star` row — so owners keep their tree and-favorites; only *sharing* resets. Non-creator organizer rows are dropped-(their owners lose access to the now-private query anyway, so their star-or folder on it is moot). Previously shared worksheets lose their sharing-at upgrade; owners re-share from the new dialog (Share-with-project-reproduces the old project-wide audience in one click). There is deliberately no automatic mapping: the old flag-carries no per-user grant to preserve, and snapshotting project IAM into-every shared row would widen or persist access differently — exactly the-project-derived-principal hack rejected in Alternatives. This is BigQuery's-own classic→modern path (migrate owner-private, owners re-grant), and the-blast radius is small — sharing was a coarse, little-used flag. Called out-in the release notes. Historical audit-log-entries keep old names as records.+`PROJECT_READ`, and `PROJECT_WRITE` alike become creator-only.++Owner organization is preserved: the creator's own `worksheet_organizer` row+migrates, its folder placement into `saved_query.folder` and its `starred` flag+into a `saved_query_star` row, so owners keep their tree and favorites. Only+*sharing* resets. Non-creator organizer rows are dropped, since their owners+lose access to the now-private query anyway.++Owners re-share from the new dialog, where Share with project reproduces the old+project-wide audience in one click. There is deliberately no automatic mapping:+the old flag carries no per-user grant to preserve, and snapshotting project IAM+into every shared row would widen or persist access differently — the+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.+### Storage and query scalabilityThe policy lives in `saved_query.bindings jsonb` — no separate accesstable. The **stored shape is pinned**: the protojson *array* of`Binding` messages, e.g.-`[{"level": "EDITOR", "members": ["group:[email protected]", "user:[email protected]"]}]`+`[{"level": "EDITOR", "members": ["groups/[email protected]", "users/[email protected]"]}]`— the array must sit at the jsonb root for the `@>` probes below (a wrapped`{"bindings": [...]}` would force expression indexes). This deviates fromthe store-a-whole-message payload convention, deliberately; the store layer@@ -543,7 +568,7 @@ platform-wide convention change outside this design's scope.The caller's principal set expands cheaply — groups are flat (members areusers, one hop) and `GetUserGroupsSnapshot` is cached in-`memberGroupsCache`: `principals(u) = {user:u} ∪ {group:g …}`, typically a+`memberGroupsCache`: `principals(u) = {users/u} ∪ {groups/g …}`, typically ahandful. Bindings carry `user:`/`group:` members (the IamPolicy invariantabove), so the only format boundary is group *membership*, storedresource-name-style (`GroupMember.member = users/{email}`):@@ -551,10 +576,13 @@ resource-name-style (`GroupMember.member = users/{email}`):caller's groups, then emits each as `group:{email}` for the probe — exactlythe conversion the existing IAM group-expansion already performs. (`creator`is a typed **principal** resource name — `users/{email}` or-`serviceAccounts/{email}` — not a binding member: the `creator ==` filter-matches that principal form, `member ==` matches the `user:`/`group:`-binding form.)-The list query filters the table directly, one GIN probe per principal:+`serviceAccounts/{email}` — not a binding member, so the `creator ==` filter+matches that principal form while the bindings themselves carry the+`user:`/`group:` form. Only the read path crosses between them; there is no+member-based filter in v1, see Offboarding.)+The index is `gin (bindings jsonb_path_ops)` — smaller and faster than the+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@@ -562,8 +590,8 @@ The list query filters the table directly, one GIN probe per principal:SELECT s.* FROM saved_query sWHERE s.project = $PAND ( s.creator = $me -- own (incl. private)- OR s.bindings @> '[{"members":["user:me"]}]'- OR s.bindings @> '[{"members":["group:g1"]}]'+ OR s.bindings @> '[{"members":["users/me"]}]'+ OR s.bindings @> '[{"members":["groups/g1"]}]'OR ... ) -- one @> per principals(u), each GIN-indexedORDER BY s.name, s.resource_id -- name is the titleLIMIT $n OFFSET $k;@@ -682,13 +710,17 @@ direction (absence of `40P01` alone is insufficient).### Sharing and organization UX-- Views, all within the current project: **My** (`creator == me`, organized- in my folder tree), **Shared** (a binding grants me VIEWER+, flat- searchable list), **Starred** (my favorites, own or shared). Nobody- fetches a query they have no grant on.-- The edit-vs-view affordance reads `effective_level` off each row- (server-computed, on the resource) — no per-row `GetIamPolicy` fan-out;- creator and admin status the UI already knows.+- Views, all within the current project, all served by `SearchSavedQueries`:+ **My** (`creator == me`, organized in my folder tree), **Shared**+ (`shared == true` — a binding grants me VIEWER or EDITOR — as a flat+ searchable list), **Starred** (`starred == true`, own or shared). Nobody+ fetches a saved query they have no access to.+- Edit-vs-view is resolved when a saved query is opened, not per row in the+ 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+ writable anyway, so only **Shared** ever resolves to view-only.- Share dialog (creator or admin): add `user:`/`group:` at VIEWER/EDITOR;the picker suggests project members/groups (a non-member grantee opensvia link but cannot browse the project or run — see Model). **Share with@@ -829,6 +861,6 @@ Sources: [Snowflake worksheets](https://docs.snowflake.com/en/user-guide/ui-snowtier plus orphan-guard for cases the admin backstop and fork alreadycover. Re-adding an OWNER level later is additive.- **A legacy `WorksheetService` shim** (derive `visibility` best-effort,- translate legacy writes to snapshot SetIamPolicy) — after the rename the+ translate legacy writes to a snapshot policy write) — after the rename theshim is an entire second service to maintain, secure, and audit, for afeature whose real consumer ships in lockstep. Hard cutover instead.diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex e217dc1a38..049544de40 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3038,6 +3038,16 @@"rows-affected": "rows affected","rows-upper-limit": "reached the limit of query results","save-sheet": "Save query",+ "saved-query-share": {+ "editor": "Editor",+ "granted-at-other-level": "{{count}} more granted at another level.",+ "not-shared": "Not shared with anyone.",+ "only-users-and-groups": "Only users and groups can be granted access.",+ "policy-changed": "Sharing changed elsewhere. Reloaded the latest.",+ "private-hint": "Only you and workspace admins can open this saved query.",+ "shared-with": "Shared with",+ "viewer": "Viewer"+ },"scroll-to-bottom": "Scroll to the bottom","scroll-to-top": "Scroll to the top","search-history-by-statement": "Search by statement",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 20a7e613cb..7fe955305a 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3038,6 +3038,16 @@"rows-affected": "filas afectadas","rows-upper-limit": "se ha alcanzado el límite de resultados de la consulta","save-sheet": "Guardar consulta",+ "saved-query-share": {+ "editor": "Editor",+ "granted-at-other-level": "{{count}} más con acceso en otro nivel.",+ "not-shared": "No compartido con nadie.",+ "only-users-and-groups": "Solo se puede conceder acceso a usuarios y grupos.",+ "policy-changed": "El uso compartido cambió en otro lugar. Se recargó la versión más reciente.",+ "private-hint": "Solo tú y los administradores del espacio de trabajo pueden abrir esta consulta guardada.",+ "shared-with": "Compartido con",+ "viewer": "Lector"+ },"scroll-to-bottom": "Desplazarse hacia abajo","scroll-to-top": "Desplazarse hacia arriba","search-history-by-statement": "Búsqueda por enunciado",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 2b70950447..2a79fc1fe2 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3038,6 +3038,16 @@"rows-affected": "行に影響","rows-upper-limit": "クエリ結果の数が上限に達しました","save-sheet": "クエリを保存",+ "saved-query-share": {+ "editor": "編集者",+ "granted-at-other-level": "他のレベルで {{count}} 件付与されています。",+ "not-shared": "誰にも共有されていません。",+ "only-users-and-groups": "アクセス権を付与できるのはユーザーとグループのみです。",+ "policy-changed": "共有設定が別の場所で変更されました。最新の状態を再読み込みしました。",+ "private-hint": "この保存済みクエリを開けるのは、あなたとワークスペース管理者のみです。",+ "shared-with": "共有先",+ "viewer": "閲覧者"+ },"scroll-to-bottom": "末尾へスクロール","scroll-to-top": "先頭へスクロール","search-history-by-statement": "ステートメントで検索",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex ff525992bc..a399bedb4e 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3038,6 +3038,16 @@"rows-affected": "dòng bị ảnh hưởng","rows-upper-limit": "đã đạt đến giới hạn kết quả truy vấn","save-sheet": "Lưu truy vấn",+ "saved-query-share": {+ "editor": "Người chỉnh sửa",+ "granted-at-other-level": "Còn {{count}} mục được cấp ở mức khác.",+ "not-shared": "Chưa chia sẻ với ai.",+ "only-users-and-groups": "Chỉ có thể cấp quyền cho người dùng và nhóm.",+ "policy-changed": "Cài đặt chia sẻ đã thay đổi ở nơi khác. Đã tải lại bản mới nhất.",+ "private-hint": "Chỉ bạn và quản trị viên workspace có thể mở truy vấn đã lưu này.",+ "shared-with": "Được chia sẻ với",+ "viewer": "Người xem"+ },"scroll-to-bottom": "Cuộn xuống cuối","scroll-to-top": "Cuộn lên đầu","search-history-by-statement": "Tìm kiếm theo câu lệnh",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 76e8ccb2ad..a6a54bedb1 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3038,6 +3038,16 @@"rows-affected": "行受影响","rows-upper-limit": "到达查询结果条数上限","save-sheet": "保存查询",+ "saved-query-share": {+ "editor": "编辑者",+ "granted-at-other-level": "另有 {{count}} 个成员在其他权限级别。",+ "not-shared": "尚未共享给任何人。",+ "only-users-and-groups": "只能将访问权限授予用户和用户组。",+ "policy-changed": "共享设置已在别处更改,已重新加载最新配置。",+ "private-hint": "仅你和工作区管理员可以打开该已保存的查询。",+ "shared-with": "共享给",+ "viewer": "查看者"+ },"scroll-to-bottom": "滚动到底部","scroll-to-top": "滚动到顶部","search-history-by-statement": "搜索 SQL 语句",diff --git a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsxnew file mode 100644index 0000000000..c09f9d0a8c--- /dev/null+++ b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx@@ -0,0 +1,255 @@+import { create as createProto } from "@bufbuild/protobuf";+import { Code, ConnectError } from "@connectrpc/connect";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { AccountMultiSelect } from "@/components/AccountMultiSelect";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { useAppStore } from "@/stores/app";+import type {+ SavedQuery,+ SavedQueryPolicy,+} from "@/types/proto-es/v1/saved_query_service_pb";+import {+ SavedQueryBinding_Level,+ SavedQueryBindingSchema,+ SavedQueryPolicySchema,+} from "@/types/proto-es/v1/saved_query_service_pb";++type Props = {+ readonly savedQuery: SavedQuery;+ /**+ * Whether the caller may change the grants. A grantee can read the policy —+ * that is how they learn their own level — but only the creator and admins+ * can rewrite it, so the editor renders read-only for everyone else.+ */+ readonly canManage: boolean;+};++const GRANTABLE_LEVELS = [+ SavedQueryBinding_Level.VIEWER,+ SavedQueryBinding_Level.EDITOR,+] as const;++/**+ * Only `user:` and `group:` can be grantees. A service account can create,+ * own, and run its own saved queries, but never receives a grant, so anything+ * else the account picker can produce is rejected rather than silently dropped.+ */+const isGrantableMember = (member: string) =>+ member.startsWith("user:") || member.startsWith("group:");++/**+ * Reads a saved query's sharing policy and, for its creator or an admin,+ * edits it. Writes replace the policy in full under the etag the read+ * returned; a concurrent change aborts the write so a revocation someone else+ * just made is never silently reinstated.+ */+export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {+ const { t } = useTranslation();+ const levelLabel = (level: SavedQueryBinding_Level) =>+ level === SavedQueryBinding_Level.EDITOR+ ? t("sql-editor.saved-query-share.editor")+ : t("sql-editor.saved-query-share.viewer");+ const getSavedQueryPolicy = useAppStore((s) => s.getSavedQueryPolicy);+ const setSavedQueryPolicy = useAppStore((s) => s.setSavedQueryPolicy);+ const notify = useAppStore((s) => s.notify);++ const [policy, setPolicy] = useState<SavedQueryPolicy | undefined>();+ const [level, setLevel] = useState<SavedQueryBinding_Level>(+ SavedQueryBinding_Level.VIEWER+ );+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ setPolicy(await getSavedQueryPolicy(savedQuery.name));+ } catch {+ setPolicy(undefined);+ } finally {+ setLoading(false);+ }+ }, [getSavedQueryPolicy, savedQuery.name]);++ useEffect(() => {+ void load();+ }, [load]);++ // The picker edits one level at a time, so members are flattened into the+ // selected level's list and rewritten as a single binding on save.+ const membersAtLevel = useMemo(+ () =>+ policy?.bindings.find((binding) => binding.level === level)?.members ??+ [],+ [policy, level]+ );++ const membersAtOtherLevel = useMemo(+ () =>+ policy?.bindings+ .filter((binding) => binding.level !== level)+ .flatMap((binding) => binding.members) ?? [],+ [policy, level]+ );++ const handleChange = async (members: string[]) => {+ if (!policy) return;+ const rejected = members.filter((member) => !isGrantableMember(member));+ if (rejected.length > 0) {+ notify({+ module: "bytebase",+ style: "WARN",+ title: t("sql-editor.saved-query-share.only-users-and-groups"),+ });+ }+ const granted = members.filter(isGrantableMember);+ // A member holds one level at a time: promoting or demoting somebody drops+ // them from the level they used to hold rather than leaving both.+ const promoted = new Set(granted);++ const bindings = [];+ for (const candidate of GRANTABLE_LEVELS) {+ const at =+ candidate === level+ ? granted+ : (policy.bindings+ .find((binding) => binding.level === candidate)+ ?.members.filter((member) => !promoted.has(member)) ?? []);+ if (at.length > 0) {+ bindings.push(+ createProto(SavedQueryBindingSchema, {+ level: candidate,+ members: at,+ })+ );+ }+ }++ setSaving(true);+ try {+ const next = await setSavedQueryPolicy(+ savedQuery.name,+ createProto(SavedQueryPolicySchema, {+ bindings,+ etag: policy.etag,+ })+ );+ setPolicy(next);+ } catch (error) {+ if (error instanceof ConnectError && error.code === Code.Aborted) {+ // Somebody else changed the grants between the read and this write.+ // Reload rather than retrying, so their change is not overwritten.+ notify({+ module: "bytebase",+ style: "WARN",+ title: t("sql-editor.saved-query-share.policy-changed"),+ });+ await load();+ return;+ }+ notify({+ module: "bytebase",+ style: "CRITICAL",+ title:+ error instanceof ConnectError ? error.message : t("common.error"),+ });+ } finally {+ setSaving(false);+ }+ };++ if (loading) {+ return (+ <p className="text-sm text-control-light">{t("common.loading")}...</p>+ );+ }+ if (!policy) {+ return null;+ }++ return (+ <section className="flex flex-col gap-y-2">+ <div className="flex items-center justify-between gap-x-2">+ <h3 className="text-sm font-medium">+ {t("sql-editor.saved-query-share.shared-with")}+ </h3>+ {canManage && (+ <Select+ value={String(level)}+ onValueChange={(next) =>+ setLevel(Number(next) as SavedQueryBinding_Level)+ }+ >+ <SelectTrigger size="sm" className="w-28">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {GRANTABLE_LEVELS.map((candidate) => (+ <SelectItem key={candidate} value={String(candidate)}>+ {levelLabel(candidate)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>++ {canManage ? (+ <>+ <AccountMultiSelect+ value={membersAtLevel}+ onChange={(members) => void handleChange(members)}+ disabled={saving}+ />+ {membersAtOtherLevel.length > 0 && (+ <p className="text-xs text-control-light">+ {t("sql-editor.saved-query-share.granted-at-other-level", {+ count: membersAtOtherLevel.length,+ })}+ </p>+ )}+ </>+ ) : policy.bindings.length === 0 ? (+ <p className="text-sm text-control-light">+ {t("sql-editor.saved-query-share.not-shared")}+ </p>+ ) : (+ // Labelled by level, not flattened: this read-only view is the only+ // place a grantee can see whether they hold VIEWER or EDITOR, which is+ // the whole reason the policy is readable by anyone who can read the+ // saved query.+ <dl className="flex flex-col gap-y-1 text-sm">+ {GRANTABLE_LEVELS.filter((candidate) =>+ policy.bindings.some(+ (binding) =>+ binding.level === candidate && binding.members.length > 0+ )+ ).map((candidate) => (+ <div key={candidate} className="flex gap-x-2">+ <dt className="shrink-0 font-medium">{levelLabel(candidate)}</dt>+ <dd className="text-control-light">+ {policy.bindings+ .filter((binding) => binding.level === candidate)+ .flatMap((binding) => binding.members)+ .join(", ")}+ </dd>+ </div>+ ))}+ </dl>+ )}++ {canManage && policy.bindings.length === 0 && (+ <p className="text-xs text-control-light">+ {t("sql-editor.saved-query-share.private-hint")}+ </p>+ )}+ </section>+ );+}diff --git a/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx b/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsxindex 68240ae4b2..8971a00831 100644--- a/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx+++ b/frontend/src/modules/sql-editor/components/SharePopoverBody.test.tsx@@ -20,6 +20,9 @@ const mocks = vi.hoisted(() => ({routerResolve: vi.fn(() => ({href: "/sql-editor/projects/proj1/savedQueries/1",})),+ hasProjectPermissionV2: vi.fn(() => false),+ getProjectByName: vi.fn((name: string) => ({ name })),+ SavedQueryGrantEditor: vi.fn(() => null),}));vi.mock("react-i18next", () => ({@@ -33,6 +36,8 @@ vi.mock("@/stores/app", () => {const state = () => ({serverInfo: mocks.serverInfo,notify: mocks.pushNotification,+ currentUser: { email: "[email protected]" },+ getProjectByName: mocks.getProjectByName,});return {useAppStore: Object.assign(@@ -47,6 +52,16 @@ vi.mock("@/utils", () => ({extractSavedQueryID: mocks.extractSavedQueryID,}));+vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,+}));++// The grant editor reads the policy over the wire and has its own tests; these+// cover the link section, so stub it out rather than mocking a policy fetch.+vi.mock("./SavedQueryGrantEditor", () => ({+ SavedQueryGrantEditor: mocks.SavedQueryGrantEditor,+}));+vi.mock("@/app/router", async (importOriginal) => ({...(await importOriginal<typeof import("@/app/router")>()),router: {@@ -115,16 +130,36 @@ describe("SharePopoverBody", () => {unmount();});- test("renders the deep link without an access selector", () => {+ test("renders the deep link alongside the grant editor", () => {const { container, render, unmount } = renderIntoContainer(<SharePopoverBody savedQuery={mockSavedQuery as never} />);render();const input = container.querySelector("input") as HTMLInputElement;expect(input.value).toContain("/savedQueries/1");- // Saved queries are private until per-object grants ship, so the- // popover carries no visibility selector.- expect(container.querySelector("[data-access-trigger]")).toBeNull();+ // The link carries location; the grant editor carries access. Both belong+ // in the popover, and the creator gets an editable one.+ expect(mocks.SavedQueryGrantEditor).toHaveBeenCalledWith(+ expect.objectContaining({ canManage: true }),+ undefined+ );+ unmount();+ });++ test("a non-creator without manage gets a read-only grant editor", () => {+ mocks.hasProjectPermissionV2.mockReturnValue(false);+ const { render, unmount } = renderIntoContainer(+ <SharePopoverBody+ savedQuery={+ { ...mockSavedQuery, creator: "users/[email protected]" } as never+ }+ />+ );+ render();+ expect(mocks.SavedQueryGrantEditor).toHaveBeenCalledWith(+ expect.objectContaining({ canManage: false }),+ undefined+ );unmount();});diff --git a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsxindex 44bcea1c56..e96ba77ea7 100644--- a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx+++ b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx@@ -8,6 +8,9 @@ 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 { SavedQueryGrantEditor } from "./SavedQueryGrantEditor";type Props = {readonly savedQuery?: SavedQuery;@@ -15,14 +18,26 @@ type Props = {/*** Replaces frontend/src/views/sql-editor/EditorCommon/SharePopover.vue.- * Renders the share popover body: the saved query's deep link with a copy- * button. The link carries location, not access — a saved query is private- * to its creator (admins aside) until the access-model redesign ships- * per-object grants, so there is no access selector here.+ * Renders the share popover body: the saved query's grants, plus its deep+ * link. The link carries location, not access — opening it still runs the+ * same read check — so the two are shown together but do different work.*/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.+ // 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]);const sharedTabLink = useMemo(() => {if (!savedQuery) return "";@@ -57,6 +72,10 @@ export function SharePopoverBody({ savedQuery }: Props) {</div></section>+ {savedQuery && (+ <SavedQueryGrantEditor savedQuery={savedQuery} canManage={canManage} />+ )}+{/* Link input + copy button — single bordered container with roundedinner corners. No group-level focus ring; only the input shows afocus highlight. */}diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx b/frontend/src/modules/sql-editor/model/Sheet/context.test.tsxindex ce1f13fe2d..d2cd58b28f 100644--- a/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx+++ b/frontend/src/modules/sql-editor/model/Sheet/context.test.tsx@@ -367,9 +367,12 @@ describe("sheet context", () => {await viewContext!.fetchSheetList();});+ // Shared is "reached through a binding", not "somebody else created it":+ // the latter also matches saved queries an admin can read but nobody+ // shared with them.expect(mocks.getAppState().searchSavedQueryFolders).toHaveBeenCalledWith("projects/proj1",- 'creator != "users/[email protected]"'+ "shared == true");expect(container.textContent).toContain("theirs");});diff --git a/frontend/src/modules/sql-editor/model/Sheet/context.ts b/frontend/src/modules/sql-editor/model/Sheet/context.tsindex 6c5fe2feb9..ee7f55fc18 100644--- a/frontend/src/modules/sql-editor/model/Sheet/context.ts+++ b/frontend/src/modules/sql-editor/model/Sheet/context.ts@@ -1028,13 +1028,13 @@ const sheetFilterForView = (includeDisplayFilters = true): string => {const email = useAppStore.getState().currentUser?.email ?? "";- // The server already restricts Search results to rows the caller can- // read (their own, plus everything for workspace admins), so "shared"- // is simply the readable rows someone else created.+ // "Shared" means reached through a binding, which is narrower than "someone+ // else created it": an admin can read saved queries nobody shared with them,+ // and those must not appear here.const baseFilters =view === "my"? [`creator == "users/${escapeCELStringLiteral(email)}"`]- : [`creator != "users/${escapeCELStringLiteral(email)}"`];+ : [`shared == true`];return [...baseFilters,...extraFilters,diff --git a/frontend/src/stores/app/savedQuery.ts b/frontend/src/stores/app/savedQuery.tsindex 617491b58e..5727667e2b 100644--- a/frontend/src/stores/app/savedQuery.ts+++ b/frontend/src/stores/app/savedQuery.ts@@ -9,15 +9,19 @@ import {BatchUpdateSavedQueriesRequestSchema,CreateSavedQueryRequestSchema,DeleteSavedQueryRequestSchema,+ GetSavedQueryPolicyRequestSchema,GetSavedQueryRequestSchema,+ SavedQueryBinding_Level,SavedQuerySchema,SearchSavedQueriesRequestSchema,SearchSavedQueryFoldersRequestSchema,+ SetSavedQueryPolicyRequestSchema,UpdateSavedQueryRequestSchema,UpdateSavedQueryStarRequestSchema,} from "@/types/proto-es/v1/saved_query_service_pb";import { isValidDatabaseName } from "@/types/v1/database";import { extractSavedQueryID } from "@/utils/v1/savedQuery";+import { setSavedQueryAccess } from "./savedQueryAccess";import type { AppSliceCreator, SavedQuerySlice, SavedQueryView } from "./types";const cacheKey = (uid: string, view: SavedQueryView) => `${uid}:${view}`;@@ -72,9 +76,29 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = (}};+ // The caller's principals, in the binding format the policy stores. Mirrors+ // the server's principals(u): themselves plus each group they belong to,+ // matched by reference so group membership stays live.+ const callerPrincipals = (): string[] => {+ const user = get().currentUser;+ if (!user?.email) return [];+ return [+ `user:${user.email}`,+ ...user.groups.map((group) => `group:${group.replace(/^groups\//, "")}`),+ ];+ };++ // Wire the cycle-free access layer the shared `@/utils` predicates read.+ setSavedQueryAccess({+ getSavedQueryLevel: (name) =>+ get().savedQueryLevelByName[name] ??+ SavedQueryBinding_Level.LEVEL_UNSPECIFIED,+ });+return {savedQueriesByKey: {},savedQueryRequests: {},+ savedQueryLevelByName: {},getSavedQueryByName: (name, view) => {const uid = extractSavedQueryID(name);@@ -109,6 +133,14 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = ();await hydrateRelatedResources([response]);setCacheEntry(response, "FULL");+ // Somebody else's saved query: resolve the caller's grant level+ // before returning, because the readable/writable predicates are+ // synchronous and run as soon as this resolves. Own saved queries+ // need no policy read -- the creator short-circuit covers them.+ const me = get().currentUser?.email;+ if (me && response.creator !== `users/${me}`) {+ await get().fetchSavedQueryLevel(response);+ }return response;} catch {return undefined;@@ -246,5 +278,52 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = (// load it eagerly.savedQueryList: () =>uniqBy(Object.values(get().savedQueriesByKey), (w) => w.name),++ getSavedQueryPolicy: async (name) =>+ await savedQueryServiceClientConnect.getSavedQueryPolicy(+ createProto(GetSavedQueryPolicyRequestSchema, { resource: name })+ ),++ setSavedQueryPolicy: async (name, policy) => {+ const updated = await savedQueryServiceClientConnect.setSavedQueryPolicy(+ createProto(SetSavedQueryPolicyRequestSchema, {+ resource: name,+ policy,+ })+ );+ // The caller's own level can change with the policy they just wrote --+ // an admin can demote themselves -- so drop the cached value rather than+ // leaving a stale one behind the read-only affordances.+ set((s) => {+ const { [name]: _dropped, ...savedQueryLevelByName } =+ s.savedQueryLevelByName;+ return { savedQueryLevelByName };+ });+ return updated;+ },++ fetchSavedQueryLevel: async (savedQuery) => {+ const principals = new Set(callerPrincipals());+ let level = SavedQueryBinding_Level.LEVEL_UNSPECIFIED;+ try {+ const policy = await get().getSavedQueryPolicy(savedQuery.name);+ for (const binding of policy.bindings) {+ if (binding.level <= level) continue;+ if (binding.members.some((member) => principals.has(member))) {+ level = binding.level;+ }+ }+ } catch {+ // Unreadable or unreachable: leave the level unspecified, which the+ // predicates treat as "no grant" and fall back to creator/admin.+ }+ set((s) => ({+ savedQueryLevelByName: {+ ...s.savedQueryLevelByName,+ [savedQuery.name]: level,+ },+ }));+ return level;+ },};};diff --git a/frontend/src/stores/app/savedQueryAccess.ts b/frontend/src/stores/app/savedQueryAccess.tsnew file mode 100644index 0000000000..1dbe218047--- /dev/null+++ b/frontend/src/stores/app/savedQueryAccess.ts@@ -0,0 +1,26 @@+import { SavedQueryBinding_Level } from "@/types/proto-es/v1/saved_query_service_pb";++type SavedQueryAccess = {+ getSavedQueryLevel: (name: string) => SavedQueryBinding_Level;+};++// Same indirection as `projectAccess`: the readable/writable predicates live in+// `@/utils`, which sits inside the app store's own load graph, so they cannot+// statically import the store index without forming an initialization cycle.+// The slice registers the real implementation via `setSavedQueryAccess` at+// store-creation time.+//+// Before registration, and for any saved query whose policy has not been read,+// this reports no grant — the predicates then fall back to creator/admin, which+// is the safe direction: affordances stay hidden rather than appearing for+// someone the server will refuse.+let savedQueryAccess: SavedQueryAccess = {+ getSavedQueryLevel: () => SavedQueryBinding_Level.LEVEL_UNSPECIFIED,+};++export const setSavedQueryAccess = (access: SavedQueryAccess) => {+ savedQueryAccess = access;+};++export const getSavedQueryLevel = (name: string) =>+ savedQueryAccess.getSavedQueryLevel(name);diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex f30cdc484f..5d7fa95778 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -63,7 +63,11 @@ import type { Release } from "@/types/proto-es/v1/release_service_pb";import type { Revision } from "@/types/proto-es/v1/revision_service_pb";import type { Role } from "@/types/proto-es/v1/role_service_pb";import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";-import type { SavedQuery } from "@/types/proto-es/v1/saved_query_service_pb";+import type {+ SavedQuery,+ SavedQueryBinding_Level,+ SavedQueryPolicy,+} from "@/types/proto-es/v1/saved_query_service_pb";import type { ServiceAccount } from "@/types/proto-es/v1/service_account_service_pb";import type {DataClassificationSetting_DataClassificationConfig,@@ -659,6 +663,36 @@ export type SavedQuerySlice = {*/patchSavedQueryFolderInCache: (names: string[], folder: string) => void;savedQueryList: () => SavedQuery[];+ /**+ * The calling user's grant level per saved query, keyed by resource name.+ * Nothing caller-relative rides on the SavedQuery resource, so this is+ * resolved from the policy when a saved query somebody else created is+ * fetched, and read back synchronously by the readable/writable predicates.+ */+ savedQueryLevelByName: Record<string, SavedQueryBinding_Level>;+ /**+ * Resolve and cache the caller's level on a saved query by reading its+ * policy and matching the bindings against the caller's own principals+ * (themselves plus their groups), the same set the server uses.+ */+ fetchSavedQueryLevel: (+ savedQuery: SavedQuery+ ) => Promise<SavedQueryBinding_Level>;+ /**+ * Read a saved query's grants. Anyone who can read the saved query can read+ * its policy, so this is also how a grantee learns whether they may edit —+ * nothing caller-relative rides on the resource itself.+ */+ getSavedQueryPolicy: (name: string) => Promise<SavedQueryPolicy>;+ /**+ * Replace a saved query's grants. `policy.etag` must carry the etag from the+ * last read; the server aborts on a mismatch rather than clobbering a+ * concurrent revocation.+ */+ setSavedQueryPolicy: (+ name: string,+ policy: SavedQueryPolicy+ ) => Promise<SavedQueryPolicy>;};export type InstanceRoleSlice = {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.tsindex 7ba9f63ae0..47b572815a 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@@ -2,7 +2,7 @@// @generated from file v1/saved_query_service.proto (package bytebase.v1, syntax proto3)/* eslint-disable */-import type { GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";+import type { GenEnum, GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";import type { Message } from "@bufbuild/protobuf";import type { EmptySchema, FieldMask, Timestamp } from "@bufbuild/protobuf/wkt";@@ -16,7 +16,7 @@ export declare const file_v1_saved_query_service: GenFile;*/export declare type CreateSavedQueryRequest = Message<"bytebase.v1.CreateSavedQueryRequest"> & {/**- * The parent resource where this saved query will be created.+ * The project to create the saved query in.* Format: projects/{project}** @generated from field: string parent = 1;@@ -42,7 +42,6 @@ export declare const CreateSavedQueryRequestSchema: GenMessage<CreateSavedQueryR*/export declare type GetSavedQueryRequest = Message<"bytebase.v1.GetSavedQueryRequest"> & {/**- * The name of the saved query to retrieve.* Format: projects/{project}/savedQueries/{savedQuery}** @generated from field: string name = 1;@@ -61,45 +60,39 @@ export declare const GetSavedQueryRequestSchema: GenMessage<GetSavedQueryRequest*/export declare type ListSavedQueriesRequest = Message<"bytebase.v1.ListSavedQueriesRequest"> & {/**- * The parent resource of the saved queries.+ * The project to list saved queries in, or "projects/-" for every project.* Format: projects/{project}- * Use "projects/-" to list saved queries across all projects.** @generated from field: string parent = 1;*/parent: string;/**- * To filter the list result.- * The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ * Filter the result, in CEL. See https://github.com/google/cel-spec*- * Supported filter:- * - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ * Supported fields:+ * - creator: the creator in "users/{email}" format. Supports "==" and "!=".** For example:- * creator == "users/{email}"- * creator != "users/{email}"+ * creator == "users/[email protected]"** @generated from field: string filter = 2;*/filter: string;/**- * The maximum number of saved queries to return. The service may return fewer than- * this value.- * If unspecified, at most 10 saved queries will be returned.- * The maximum value is 1000; values above 1000 will be coerced to 1000.+ * The maximum number of saved queries to return. The service may return+ * fewer. Defaults to 10; values above 1000 are coerced to 1000.** @generated from field: int32 page_size = 3;*/pageSize: number;/**- * A page token, received from a previous `ListSavedQueries` call.- * Provide this to retrieve the subsequent page.- *- * When paginating, all other parameters provided to `ListSavedQueries` must match- * the call that provided the page token.+ * 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.** @generated from field: string page_token = 4;*/@@ -117,16 +110,13 @@ export declare const ListSavedQueriesRequestSchema: GenMessage<ListSavedQueriesR*/export declare type ListSavedQueriesResponse = Message<"bytebase.v1.ListSavedQueriesResponse"> & {/**- * The saved queries from the specified parent.- ** @generated from field: repeated bytebase.v1.SavedQuery saved_queries = 1;*/savedQueries: SavedQuery[];/**- * A token to retrieve next page of saved queries.- * Pass this value in the page_token field in the subsequent call to- * `ListSavedQueries` method to retrieve the next page of saved queries.+ * Pass to the next ListSavedQueries call to fetch the following page. Empty+ * on the last page.** @generated from field: string next_page_token = 2;*/@@ -144,7 +134,6 @@ export declare const ListSavedQueriesResponseSchema: GenMessage<ListSavedQueries*/export declare type SearchSavedQueryFoldersRequest = Message<"bytebase.v1.SearchSavedQueryFoldersRequest"> & {/**- * The parent resource whose saved query folders are searched.* Format: projects/{project}** @generated from field: string parent = 1;@@ -152,15 +141,9 @@ export declare type SearchSavedQueryFoldersRequest = Message<"bytebase.v1.Searchparent: string;/**- * To filter the folders by the saved queries they hold. Takes the same- * fields and syntax as `SearchSavedQueries.filter`, except `title`. A- * folder is returned when at least one saved query the caller can read- * matches, so the caller-scoping is the same as SearchSavedQueries: your- * own saved queries, plus everyone's for the admin backstop.- *- * For example, to split a folder tree into your own and everyone else's:- * creator == "users/{email}"- * creator != "users/{email}"+ * Filter folders by the saved queries they hold. Takes the same fields and+ * syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ * when at least one saved query the caller can read matches.** @generated from field: string filter = 2;*/@@ -178,9 +161,8 @@ export declare const SearchSavedQueryFoldersRequestSchema: GenMessage<SearchSave*/export declare type SearchSavedQueryFoldersResponse = Message<"bytebase.v1.SearchSavedQueryFoldersResponse"> & {/**- * The caller's folder paths, including every ancestor prefix, sorted.- * A folder is a path on saved queries ("a/b/c"), so empty folders cannot- * exist.+ * Folder paths, every ancestor prefix included, sorted. A folder is a path+ * on saved queries ("a/b/c"), so empty folders cannot exist.** @generated from field: repeated string folders = 1;*/@@ -198,9 +180,7 @@ export declare const SearchSavedQueryFoldersResponseSchema: GenMessage<SearchSav*/export declare type UpdateSavedQueryRequest = Message<"bytebase.v1.UpdateSavedQueryRequest"> & {/**- * The saved query to update.- *- * The saved query's `name` field is used to identify the saved query to update.+ * `saved_query.name` identifies the saved query to update.* Format: projects/{project}/savedQueries/{savedQuery}** @generated from field: bytebase.v1.SavedQuery saved_query = 1;@@ -208,14 +188,8 @@ export declare type UpdateSavedQueryRequest = Message<"bytebase.v1.UpdateSavedQusavedQuery?: SavedQuery | undefined;/**- * The list of fields to be updated.- * Fields are specified relative to the saved query.- * (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)- * Only support update the following fields for now:- * - `title`- * - `content`- * - `database`- * - `folder`+ * Fields to update, relative to the saved query (`title`, not+ * `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.** @generated from field: google.protobuf.FieldMask update_mask = 2;*/@@ -233,7 +207,6 @@ export declare const UpdateSavedQueryRequestSchema: GenMessage<UpdateSavedQueryR*/export declare type UpdateSavedQueryStarRequest = Message<"bytebase.v1.UpdateSavedQueryStarRequest"> & {/**- * The name of the saved query to star or unstar.* Format: projects/{project}/savedQueries/{savedQuery}** @generated from field: string name = 1;@@ -259,7 +232,6 @@ export declare const UpdateSavedQueryStarRequestSchema: GenMessage<UpdateSavedQu*/export declare type BatchUpdateSavedQueriesRequest = Message<"bytebase.v1.BatchUpdateSavedQueriesRequest"> & {/**- * The parent resource whose saved queries are updated.* Format: projects/{project}** @generated from field: string parent = 1;@@ -267,30 +239,28 @@ export declare type BatchUpdateSavedQueriesRequest = Message<"bytebase.v1.BatchUparent: string;/**- * To filter the batch update target.- * The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ * Select the saved queries to update, in CEL. See+ * https://github.com/google/cel-spec*- * Supported filter:- * - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- * - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- * - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- * - folder: the saved query folder path, support exact "==" operator.+ * Supported fields:+ * - name: the saved query name. Supports "==" and "in [...]".+ * - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ * - starred: whether the caller starred it. Supports "==".+ * - folder: the exact folder path. Supports "==".** @generated from field: string filter = 2;*/filter: string;/**- * The fields to apply to every matched saved query.+ * The values to apply to every matched saved query.** @generated from field: bytebase.v1.SavedQuery saved_query = 3;*/savedQuery?: SavedQuery | undefined;/**- * The list of fields to be updated.- * Only support update the following fields for now:- * - `folder`+ * Fields to update. Supported: `folder`.** @generated from field: google.protobuf.FieldMask update_mask = 4;*/@@ -308,7 +278,8 @@ export declare const BatchUpdateSavedQueriesRequestSchema: GenMessage<BatchUpdat*/export declare type BatchUpdateSavedQueriesResponse = Message<"bytebase.v1.BatchUpdateSavedQueriesResponse"> & {/**- * The number of saved queries updated.+ * How many saved queries were updated, which may be fewer than the filter+ * matched.** @generated from field: int32 updated_count = 1;*/@@ -321,12 +292,156 @@ export declare type BatchUpdateSavedQueriesResponse = Message<"bytebase.v1.Batch*/export declare const BatchUpdateSavedQueriesResponseSchema: GenMessage<BatchUpdateSavedQueriesResponse>;+/**+ * @generated from message bytebase.v1.GetSavedQueryPolicyRequest+ */+export declare type GetSavedQueryPolicyRequest = Message<"bytebase.v1.GetSavedQueryPolicyRequest"> & {+ /**+ * Format: projects/{project}/savedQueries/{savedQuery}+ *+ * @generated from field: string resource = 1;+ */+ resource: string;+};++/**+ * Describes the message bytebase.v1.GetSavedQueryPolicyRequest.+ * Use `create(GetSavedQueryPolicyRequestSchema)` to create a new message.+ */+export declare const GetSavedQueryPolicyRequestSchema: GenMessage<GetSavedQueryPolicyRequest>;++/**+ * @generated from message bytebase.v1.SetSavedQueryPolicyRequest+ */+export declare type SetSavedQueryPolicyRequest = Message<"bytebase.v1.SetSavedQueryPolicyRequest"> & {+ /**+ * Format: projects/{project}/savedQueries/{savedQuery}+ *+ * @generated from field: string resource = 1;+ */+ 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.+ *+ * @generated from field: bytebase.v1.SavedQueryPolicy policy = 2;+ */+ policy?: SavedQueryPolicy | undefined;+};++/**+ * Describes the message bytebase.v1.SetSavedQueryPolicyRequest.+ * Use `create(SetSavedQueryPolicyRequestSchema)` to create a new message.+ */+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.+ *+ * @generated from message bytebase.v1.SavedQueryPolicy+ */+export declare type SavedQueryPolicy = Message<"bytebase.v1.SavedQueryPolicy"> & {+ /**+ * At most one binding per level. A member listed under two levels is+ * rejected rather than resolved to the higher one.+ *+ * @generated from field: repeated bytebase.v1.SavedQueryBinding bindings = 1;+ */+ bindings: SavedQueryBinding[];++ /**+ * The etag of the policy as read. SetSavedQueryPolicy requires it and fails+ * with ABORTED when it no longer matches.+ *+ * @generated from field: string etag = 2;+ */+ etag: string;+};++/**+ * Describes the message bytebase.v1.SavedQueryPolicy.+ * Use `create(SavedQueryPolicySchema)` to create a new message.+ */+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.+ *+ * @generated from message bytebase.v1.SavedQueryBinding+ */+export declare type SavedQueryBinding = Message<"bytebase.v1.SavedQueryBinding"> & {+ /**+ * @generated from field: bytebase.v1.SavedQueryBinding.Level level = 1;+ */+ 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.+ *+ * 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.+ *+ * @generated from field: repeated string members = 2;+ */+ members: string[];+};++/**+ * Describes the message bytebase.v1.SavedQueryBinding.+ * Use `create(SavedQueryBindingSchema)` to create a new message.+ */+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.+ *+ * @generated from enum bytebase.v1.SavedQueryBinding.Level+ */+export enum SavedQueryBinding_Level {+ /**+ * @generated from enum value: LEVEL_UNSPECIFIED = 0;+ */+ LEVEL_UNSPECIFIED = 0,++ /**+ * Open and read the saved query.+ *+ * @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.+ *+ * @generated from enum value: EDITOR = 2;+ */+ EDITOR = 2,+}++/**+ * Describes the enum bytebase.v1.SavedQueryBinding.Level.+ */+export declare const SavedQueryBinding_LevelSchema: GenEnum<SavedQueryBinding_Level>;+/*** @generated from message bytebase.v1.DeleteSavedQueryRequest*/export declare type DeleteSavedQueryRequest = Message<"bytebase.v1.DeleteSavedQueryRequest"> & {/**- * The name of the saved query to delete.* Format: projects/{project}/savedQueries/{savedQuery}** @generated from field: string name = 1;@@ -345,7 +460,6 @@ export declare const DeleteSavedQueryRequestSchema: GenMessage<DeleteSavedQueryR*/export declare type SearchSavedQueriesRequest = Message<"bytebase.v1.SearchSavedQueriesRequest"> & {/**- * The parent resource of the saved queries.* Format: projects/{project}** @generated from field: string parent = 1;@@ -353,22 +467,28 @@ export declare type SearchSavedQueriesRequest = Message<"bytebase.v1.SearchSavedparent: string;/**- * To filter the search result.- * The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ * Filter the result, in CEL. See https://github.com/google/cel-spec*- * Supported filter:- * - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- * - title: the saved query title, support "contains" operator.- * - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- * - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- * - folder: the saved query folder path, support "==" operator.+ * Supported fields:+ * - 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 "==".+ * - 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.** For example:- * creator == "users/{email}"- * title.contains("saved query title")- * creator != "users/{email}"+ * creator == "users/[email protected]"+ * shared == true* starred == true- * starred == false+ * title.contains("weekly report")* folder == "foo/bar"** @generated from field: string filter = 2;@@ -376,18 +496,19 @@ export declare type SearchSavedQueriesRequest = Message<"bytebase.v1.SearchSavedfilter: string;/**- * The maximum number of saved queries to return. The service may return fewer than- * this value.- * If unspecified, at most 10 saved queries will be returned.- * The maximum value is 1000; values above 1000 will be coerced to 1000.+ * The maximum number of saved queries to return. The service may return+ * fewer. Defaults to 10; values above 1000 are coerced to 1000.** @generated from field: int32 page_size = 3;*/pageSize: number;/**- * A page token, received from a previous `SearchSavedQueries` call.- * Provide this to retrieve the subsequent page.+ * 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.** @generated from field: string page_token = 4;*/@@ -405,16 +526,13 @@ export declare const SearchSavedQueriesRequestSchema: GenMessage<SearchSavedQuer*/export declare type SearchSavedQueriesResponse = Message<"bytebase.v1.SearchSavedQueriesResponse"> & {/**- * The saved queries that matched the search criteria.- ** @generated from field: repeated bytebase.v1.SavedQuery saved_queries = 1;*/savedQueries: SavedQuery[];/**- * A token to retrieve next page of saved queries.- * Pass this value in the page_token field in the subsequent call to- * `SearchSavedQueries` method to retrieve the next page of saved queries.+ * Pass to the next SearchSavedQueries call to fetch the following page.+ * Empty on the last page.** @generated from field: string next_page_token = 2;*/@@ -432,8 +550,7 @@ export declare const SearchSavedQueriesResponseSchema: GenMessage<SearchSavedQue*/export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {/**- * The name of the saved query resource, generated by the server.- * Canonical parent is project.+ * Server-generated.* Format: projects/{project}/savedQueries/{savedQuery}** @generated from field: string name = 1;@@ -441,7 +558,6 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {name: string;/**- * The project resource name.* Format: projects/{project}** @generated from field: string project = 2;@@ -449,9 +565,10 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {project: string;/**- * The database resource name.+ * The connected database, which must belong to the saved query's own+ * project. Empty when none is connected, or when the database no longer+ * exists.* Format: instances/{instance}/databases/{database}- * If the database parent doesn't exist, the database field is empty.** @generated from field: string database = 3;*/@@ -465,8 +582,7 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {title: string;/**- * The creator of the SavedQuery — the fixed owner; ownership does not- * transfer.+ * The fixed owner. Ownership does not transfer.* Format: users/{email}** @generated from field: string creator = 5;@@ -474,46 +590,40 @@ export declare type SavedQuery = Message<"bytebase.v1.SavedQuery"> & {creator: string;/**- * The create time of the saved query.- ** @generated from field: google.protobuf.Timestamp create_time = 6;*/createTime?: Timestamp | undefined;/**- * The last update time of the saved query.- ** @generated from field: google.protobuf.Timestamp update_time = 7;*/updateTime?: Timestamp | undefined;/**- * The content of the saved query.- * By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can- * use GetSavedQuery() request to retrieve the full content.+ * The SQL text. SearchSavedQueries truncates it; when it is shorter than+ * `content_size`, GetSavedQuery returns the whole thing.** @generated from field: bytes content = 8;*/content: Uint8Array;/**- * content_size is the full size of the content, may not match the size of the `content` field.+ * The full size of the content, which may exceed the `content` returned.** @generated from field: int64 content_size = 9;*/contentSize: bigint;/**- * starred indicates whether the saved query is starred by the current authenticated user.+ * Whether the calling user starred it.** @generated from field: bool starred = 11;*/starred: boolean;/**- * The folder path this saved query lives in, set by its creator (or an- * admin). Empty means unfiled. A saved query lives in exactly one folder;- * a folder is a path on saved queries, e.g. "a/b/c".+ * The folder holding this saved query, set by its creator or an admin. A+ * path like "a/b/c"; empty means unfiled.** @generated from field: string folder = 13;*/@@ -529,18 +639,21 @@ export declare const SavedQuerySchema: GenMessage<SavedQuery>;/*** SavedQueryService manages saved queries for SQL Editor query development.*- * A saved query is private to its creator; `bb.savedQueries.manage` is the- * admin backstop that can reach any saved query in scope. Per-object- * VIEWER/EDITOR grants arrive with the access-model redesign, which brings- * its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages- * them.+ * 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.** @generated from service bytebase.v1.SavedQueryService*/export declare const SavedQueryService: GenService<{/**- * Creates a personal saved query used in SQL Editor. The creator becomes- * the fixed owner.+ * 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** @generated from rpc bytebase.v1.SavedQueryService.CreateSavedQuery@@ -551,9 +664,9 @@ export declare const SavedQueryService: GenService<{output: typeof SavedQuerySchema;},/**- * Get a saved query by name. Returns NotFound for saved queries the- * caller cannot read.- * Permissions required: creator, or bb.savedQueries.manage in scope+ * 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** @generated from rpc bytebase.v1.SavedQueryService.GetSavedQuery*/@@ -563,11 +676,12 @@ export declare const SavedQueryService: GenService<{output: typeof SavedQuerySchema;},/**- * List saved queries: the grant-independent governance surface. Supports- * listing in a project, or across all projects by using `projects/-`, with- * whole statements rather than the previews Search returns — e.g. an- * offboarding review filtering by creator.- * Permissions required: bb.savedQueries.list+ * 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/-"** @generated from rpc bytebase.v1.SavedQueryService.ListSavedQueries*/@@ -577,9 +691,15 @@ export declare const SavedQueryService: GenService<{output: typeof ListSavedQueriesResponseSchema;},/**- * Search for saved queries in a project: the SQL Editor's hot list path,- * returning only rows the caller can read, with content previews.- * Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ * 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.+ * Permissions required: bb.savedQueries.search on the project** @generated from rpc bytebase.v1.SavedQueryService.SearchSavedQueries*/@@ -589,12 +709,17 @@ export declare const SavedQueryService: GenService<{output: typeof SearchSavedQueriesResponseSchema;},/**- * Search the folder paths of the caller's saved queries in a project.- * Folders are a derived view over the `folder` field rather than a- * resource collection, so this is a custom method on savedQueries and- * shares SearchSavedQueries' caller-scoped semantics — not the- * cross-creator reach of ListSavedQueries.- * Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ * 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`).+ * Permissions required: bb.savedQueries.search on the project** @generated from rpc bytebase.v1.SavedQueryService.SearchSavedQueryFolders*/@@ -604,10 +729,12 @@ export declare const SavedQueryService: GenService<{output: typeof SearchSavedQueryFoldersResponseSchema;},/**- * Update a saved query. `title`, `content`, and `database` require write- * access; `folder` re-files the saved query and is creator/admin only.- * Returns NotFound for saved queries the caller cannot read.- * Permissions required: creator, or bb.savedQueries.manage in scope+ * 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** @generated from rpc bytebase.v1.SavedQueryService.UpdateSavedQuery*/@@ -617,12 +744,10 @@ export declare const SavedQueryService: GenService<{output: typeof SavedQuerySchema;},/**- * Star or unstar a saved query for the caller. A star is always the- * caller's own per-user marker — invisible to others and carrying no- * access. The only requirement is that the caller can read the saved- * query being starred (which also keeps private saved query names- * unprobeable).- * Permissions required: read access to the saved query+ * Star or unstar a saved query for the caller. A star is a per-user marker:+ * invisible to everyone else and granting nothing. Read access is the gate+ * only so unreadable saved queries stay unprobeable.+ * Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage** @generated from rpc bytebase.v1.SavedQueryService.UpdateSavedQueryStar*/@@ -632,10 +757,11 @@ export declare const SavedQueryService: GenService<{output: typeof SavedQuerySchema;},/**- * Batch re-file saved queries into a folder. The update mask supports- * `folder` only; only rows the caller may re-file are updated (their own,- * or any in scope for admins).- * Permissions required: creator, or bb.savedQueries.manage in scope+ * Re-file saved queries into a folder in bulk; the update mask supports+ * `folder` only. An EDITOR binding does not carry re-filing, so matched+ * saved queries the caller cannot re-file are skipped rather than rejected,+ * and the response counts what actually changed.+ * Permissions required: creator, or bb.savedQueries.manage** @generated from rpc bytebase.v1.SavedQueryService.BatchUpdateSavedQueries*/@@ -645,9 +771,10 @@ export declare const SavedQueryService: GenService<{output: typeof BatchUpdateSavedQueriesResponseSchema;},/**- * Delete a saved query. Only the creator (or an admin) can delete.- * Returns NotFound for saved queries the caller cannot read.- * Permissions required: creator, or bb.savedQueries.manage in scope+ * 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** @generated from rpc bytebase.v1.SavedQueryService.DeleteSavedQuery*/@@ -656,5 +783,33 @@ export declare const SavedQueryService: GenService<{input: typeof DeleteSavedQueryRequestSchema;output: typeof EmptySchema;},+ /**+ * 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+ *+ * @generated from rpc bytebase.v1.SavedQueryService.GetSavedQueryPolicy+ */+ getSavedQueryPolicy: {+ methodKind: "unary";+ input: typeof GetSavedQueryPolicyRequestSchema;+ output: typeof SavedQueryPolicySchema;+ },+ /**+ * 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+ *+ * @generated from rpc bytebase.v1.SavedQueryService.SetSavedQueryPolicy+ */+ setSavedQueryPolicy: {+ methodKind: "unary";+ input: typeof SetSavedQueryPolicyRequestSchema;+ output: typeof SavedQueryPolicySchema;+ },}>;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.jsindex f85c3711c8..f78675fed0 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@@ -2,7 +2,7 @@// @generated from file v1/saved_query_service.proto (package bytebase.v1, syntax proto3)/* eslint-disable */-import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2";+import { enumDesc, fileDesc, messageDesc, serviceDesc, tsEnum } from "@bufbuild/protobuf/codegenv2";import { file_buf_validate_validate } from "../buf/validate/validate_pb";import { file_google_api_annotations } from "../google/api/annotations_pb";import { file_google_api_client } from "../google/api/client_pb";@@ -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+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiYwoYTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlEi4KDXNhdmVkX3F1ZXJpZXMYASADKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSJeCh5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCSIyCh9TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlEg8KB2ZvbGRlcnMYASADKAkifQoXVXBkYXRlU2F2ZWRRdWVyeVJlcXVlc3QSMQoLc2F2ZWRfcXVlcnkYASABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQISLwoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrIkEKG1VwZGF0ZVNhdmVkUXVlcnlTdGFyUmVxdWVzdBIRCgRuYW1lGAEgASgJQgPgQQISDwoHc3RhcnJlZBgCIAEoCCLHAQoeQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkSMQoLc2F2ZWRfcXVlcnkYAyABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQISNAoLdXBkYXRlX21hc2sYBCABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQIiOAofQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXNSZXNwb25zZRIVCg11cGRhdGVkX2NvdW50GAEgASgFIkgKF0RlbGV0ZVNhdmVkUXVlcnlSZXF1ZXN0Ei0KBG5hbWUYASABKAlCH+BBAvpBGQoXYnl0ZWJhc2UuY29tL1NhdmVkUXVlcnkigAEKGVNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCRIRCglwYWdlX3NpemUYAyABKAUSEgoKcGFnZV90b2tlbhgEIAEoCSJlChpTZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZRIuCg1zYXZlZF9xdWVyaWVzGAEgAygLMhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkitwMKClNhdmVkUXVlcnkSFAoEbmFtZRgBIAEoCUIG4EEC4EEFEhQKB3Byb2plY3QYAiABKAlCA+BBAxIQCghkYXRhYmFzZRgDIAEoCRIaCgV0aXRsZRgEIAEoCUIL4EECukgFcgMYyAESFAoHY3JlYXRvchgFIAEoCUID4EEDEjQKC2NyZWF0ZV90aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAcgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhQKB2NvbnRlbnQYCCABKAxCA+BBAhIZCgxjb250ZW50X3NpemUYCSABKANCA+BBAxIUCgdzdGFycmVkGAsgASgIQgPgQQMSGAoGZm9sZGVyGA0gASgJQgi6SAVyAxiAAjpL6kFIChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRItcHJvamVjdHMve3Byb2plY3R9L3NhdmVkUXVlcmllcy97c2F2ZWRfcXVlcnl9SgQIChALSgQIDBANUgp2aXNpYmlsaXR5Ugdmb2xkZXJzMtoMChFTYXZlZFF1ZXJ5U2VydmljZRLDAQoQQ3JlYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLkNyZWF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJw2kEScGFyZW50LHNhdmVkX3F1ZXJ5iuowFmJiLnNhdmVkUXVlcmllcy5jcmVhdGWQ6jABmOowAYLT5JMCMzoLc2F2ZWRfcXVlcnkiJC92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllcxKEAQoNR2V0U2F2ZWRRdWVyeRIhLmJ5dGViYXNlLnYxLkdldFNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSI32kEEbmFtZZDqMAKC0+STAiYSJC92MS97bmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKyAQoQTGlzdFNhdmVkUXVlcmllcxIkLmJ5dGViYXNlLnYxLkxpc3RTYXZlZFF1ZXJpZXNSZXF1ZXN0GiUuYnl0ZWJhc2UudjEuTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlIlHaQQZwYXJlbnSK6jAUYmIuc2F2ZWRRdWVyaWVzLmxpc3SQ6jABgtPkkwImEiQvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXMSqgEKElNlYXJjaFNhdmVkUXVlcmllcxImLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QaJy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZSJD2kEGcGFyZW50kOowAoLT5JMCMDoBKiIrL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzOnNlYXJjaBLAAQoXU2VhcmNoU2F2ZWRRdWVyeUZvbGRlcnMSKy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QaLC5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlIkraQQZwYXJlbnSQ6jACgtPkkwI3OgEqIjIvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXM6c2VhcmNoRm9sZGVycxK6AQoQVXBkYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLlVwZGF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJn2kEXc2F2ZWRfcXVlcnksdXBkYXRlX21hc2uQ6jACmOowAYLT5JMCPzoLc2F2ZWRfcXVlcnkyMC92MS97c2F2ZWRfcXVlcnkubmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKoAQoUVXBkYXRlU2F2ZWRRdWVyeVN0YXISKC5ieXRlYmFzZS52MS5VcGRhdGVTYXZlZFF1ZXJ5U3RhclJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5Ik3aQQxuYW1lLHN0YXJyZWSQ6jACgtPkkwI0OgEqIi8vdjEve25hbWU9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn06dXBkYXRlU3RhchLaAQoXQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXMSKy5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZVNhdmVkUXVlcmllc1JlcXVlc3QaLC5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZVNhdmVkUXVlcmllc1Jlc3BvbnNlImTaQR5wYXJlbnQsc2F2ZWRfcXVlcnksdXBkYXRlX21hc2uQ6jACmOowAYLT5JMCNToBKiIwL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzOmJhdGNoVXBkYXRlEo0BChBEZWxldGVTYXZlZFF1ZXJ5EiQuYnl0ZWJhc2UudjEuRGVsZXRlU2F2ZWRRdWVyeVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiO9pBBG5hbWWQ6jACmOowAYLT5JMCJiokL3YxL3tuYW1lPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9QqwBCg9jb20uYnl0ZWJhc2UudjFCFlNhdmVkUXVlcnlTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [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("Chx2MS9zYXZlZF9xdWVyeV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJ6ChdDcmVhdGVTYXZlZFF1ZXJ5UmVxdWVzdBIsCgZwYXJlbnQYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1Byb2plY3QSMQoLc2F2ZWRfcXVlcnkYAiABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQIiKQoUR2V0U2F2ZWRRdWVyeVJlcXVlc3QSEQoEbmFtZRgBIAEoCUID4EECIn4KF0xpc3RTYXZlZFF1ZXJpZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiYwoYTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlEi4KDXNhdmVkX3F1ZXJpZXMYASADKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSJeCh5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCSIyCh9TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlEg8KB2ZvbGRlcnMYASADKAkifQoXVXBkYXRlU2F2ZWRRdWVyeVJlcXVlc3QSMQoLc2F2ZWRfcXVlcnkYASABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQISLwoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrIkEKG1VwZGF0ZVNhdmVkUXVlcnlTdGFyUmVxdWVzdBIRCgRuYW1lGAEgASgJQgPgQQISDwoHc3RhcnJlZBgCIAEoCCLHAQoeQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZmaWx0ZXIYAiABKAkSMQoLc2F2ZWRfcXVlcnkYAyABKAsyFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5QgPgQQISNAoLdXBkYXRlX21hc2sYBCABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQIiOAofQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXNSZXNwb25zZRIVCg11cGRhdGVkX2NvdW50GAEgASgFIk8KGkdldFNhdmVkUXVlcnlQb2xpY3lSZXF1ZXN0EjEKCHJlc291cmNlGAEgASgJQh/gQQL6QRkKF2J5dGViYXNlLmNvbS9TYXZlZFF1ZXJ5IoMBChpTZXRTYXZlZFF1ZXJ5UG9saWN5UmVxdWVzdBIxCghyZXNvdXJjZRgBIAEoCUIf4EEC+kEZChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRIyCgZwb2xpY3kYAiABKAsyHS5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5UG9saWN5QgPgQQIiUgoQU2F2ZWRRdWVyeVBvbGljeRIwCghiaW5kaW5ncxgBIAMoCzIeLmJ5dGViYXNlLnYxLlNhdmVkUXVlcnlCaW5kaW5nEgwKBGV0YWcYAiABKAkiowEKEVNhdmVkUXVlcnlCaW5kaW5nEjgKBWxldmVsGAEgASgOMiQuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeUJpbmRpbmcuTGV2ZWxCA+BBAhIcCgdtZW1iZXJzGAIgAygJQgvgQQK6SAWSAQIIASI2CgVMZXZlbBIVChFMRVZFTF9VTlNQRUNJRklFRBAAEgoKBlZJRVdFUhABEgoKBkVESVRPUhACIkgKF0RlbGV0ZVNhdmVkUXVlcnlSZXF1ZXN0Ei0KBG5hbWUYASABKAlCH+BBAvpBGQoXYnl0ZWJhc2UuY29tL1NhdmVkUXVlcnkigAEKGVNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0Eg4KBmZpbHRlchgCIAEoCRIRCglwYWdlX3NpemUYAyABKAUSEgoKcGFnZV90b2tlbhgEIAEoCSJlChpTZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZRIuCg1zYXZlZF9xdWVyaWVzGAEgAygLMhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkiogMKClNhdmVkUXVlcnkSFAoEbmFtZRgBIAEoCUIG4EEC4EEFEhQKB3Byb2plY3QYAiABKAlCA+BBAxIQCghkYXRhYmFzZRgDIAEoCRIaCgV0aXRsZRgEIAEoCUIL4EECukgFcgMYyAESFAoHY3JlYXRvchgFIAEoCUID4EEDEjQKC2NyZWF0ZV90aW1lGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAcgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhQKB2NvbnRlbnQYCCABKAxCA+BBAhIZCgxjb250ZW50X3NpemUYCSABKANCA+BBAxIUCgdzdGFycmVkGAsgASgIQgPgQQMSGAoGZm9sZGVyGA0gASgJQgi6SAVyAxiAAjpL6kFIChdieXRlYmFzZS5jb20vU2F2ZWRRdWVyeRItcHJvamVjdHMve3Byb2plY3R9L3NhdmVkUXVlcmllcy97c2F2ZWRfcXVlcnl9SgQIChALSgQIDBANMr4PChFTYXZlZFF1ZXJ5U2VydmljZRLDAQoQQ3JlYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLkNyZWF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJw2kEScGFyZW50LHNhdmVkX3F1ZXJ5iuowFmJiLnNhdmVkUXVlcmllcy5jcmVhdGWQ6jABmOowAYLT5JMCMzoLc2F2ZWRfcXVlcnkiJC92MS97cGFyZW50PXByb2plY3RzLyp9L3NhdmVkUXVlcmllcxKEAQoNR2V0U2F2ZWRRdWVyeRIhLmJ5dGViYXNlLnYxLkdldFNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSI32kEEbmFtZZDqMAKC0+STAiYSJC92MS97bmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKyAQoQTGlzdFNhdmVkUXVlcmllcxIkLmJ5dGViYXNlLnYxLkxpc3RTYXZlZFF1ZXJpZXNSZXF1ZXN0GiUuYnl0ZWJhc2UudjEuTGlzdFNhdmVkUXVlcmllc1Jlc3BvbnNlIlHaQQZwYXJlbnSK6jAUYmIuc2F2ZWRRdWVyaWVzLmxpc3SQ6jABgtPkkwImEiQvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXMSqgEKElNlYXJjaFNhdmVkUXVlcmllcxImLmJ5dGViYXNlLnYxLlNlYXJjaFNhdmVkUXVlcmllc1JlcXVlc3QaJy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJpZXNSZXNwb25zZSJD2kEGcGFyZW50kOowAoLT5JMCMDoBKiIrL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzOnNlYXJjaBLAAQoXU2VhcmNoU2F2ZWRRdWVyeUZvbGRlcnMSKy5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1JlcXVlc3QaLC5ieXRlYmFzZS52MS5TZWFyY2hTYXZlZFF1ZXJ5Rm9sZGVyc1Jlc3BvbnNlIkraQQZwYXJlbnSQ6jACgtPkkwI3OgEqIjIvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9zYXZlZFF1ZXJpZXM6c2VhcmNoRm9sZGVycxK6AQoQVXBkYXRlU2F2ZWRRdWVyeRIkLmJ5dGViYXNlLnYxLlVwZGF0ZVNhdmVkUXVlcnlSZXF1ZXN0GhcuYnl0ZWJhc2UudjEuU2F2ZWRRdWVyeSJn2kEXc2F2ZWRfcXVlcnksdXBkYXRlX21hc2uQ6jACmOowAYLT5JMCPzoLc2F2ZWRfcXVlcnkyMC92MS97c2F2ZWRfcXVlcnkubmFtZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfRKoAQoUVXBkYXRlU2F2ZWRRdWVyeVN0YXISKC5ieXRlYmFzZS52MS5VcGRhdGVTYXZlZFF1ZXJ5U3RhclJlcXVlc3QaFy5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5Ik3aQQxuYW1lLHN0YXJyZWSQ6jACgtPkkwI0OgEqIi8vdjEve25hbWU9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn06dXBkYXRlU3RhchLaAQoXQmF0Y2hVcGRhdGVTYXZlZFF1ZXJpZXMSKy5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZVNhdmVkUXVlcmllc1JlcXVlc3QaLC5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZVNhdmVkUXVlcmllc1Jlc3BvbnNlImTaQR5wYXJlbnQsc2F2ZWRfcXVlcnksdXBkYXRlX21hc2uQ6jACmOowAYLT5JMCNToBKiIwL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vc2F2ZWRRdWVyaWVzOmJhdGNoVXBkYXRlEo0BChBEZWxldGVTYXZlZFF1ZXJ5EiQuYnl0ZWJhc2UudjEuRGVsZXRlU2F2ZWRRdWVyeVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiO9pBBG5hbWWQ6jACmOowAYLT5JMCJiokL3YxL3tuYW1lPXByb2plY3RzLyovc2F2ZWRRdWVyaWVzLyp9EqgBChNHZXRTYXZlZFF1ZXJ5UG9saWN5EicuYnl0ZWJhc2UudjEuR2V0U2F2ZWRRdWVyeVBvbGljeVJlcXVlc3QaHS5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5UG9saWN5IknaQQhyZXNvdXJjZZDqMAKC0+STAjQSMi92MS97cmVzb3VyY2U9cHJvamVjdHMvKi9zYXZlZFF1ZXJpZXMvKn06Z2V0UG9saWN5ErYBChNTZXRTYXZlZFF1ZXJ5UG9saWN5EicuYnl0ZWJhc2UudjEuU2V0U2F2ZWRRdWVyeVBvbGljeVJlcXVlc3QaHS5ieXRlYmFzZS52MS5TYXZlZFF1ZXJ5UG9saWN5IlfaQQ9yZXNvdXJjZSxwb2xpY3mQ6jACmOowAYLT5JMCNzoBKiIyL3YxL3tyZXNvdXJjZT1wcm9qZWN0cy8qL3NhdmVkUXVlcmllcy8qfTpzZXRQb2xpY3lCrAEKD2NvbS5ieXRlYmFzZS52MUIWU2F2ZWRRdWVyeVNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [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.@@ -87,42 +87,88 @@ export const BatchUpdateSavedQueriesRequestSchema = /*@__PURE__*/export const BatchUpdateSavedQueriesResponseSchema = /*@__PURE__*/messageDesc(file_v1_saved_query_service, 9);+/**+ * Describes the message bytebase.v1.GetSavedQueryPolicyRequest.+ * Use `create(GetSavedQueryPolicyRequestSchema)` to create a new message.+ */+export const GetSavedQueryPolicyRequestSchema = /*@__PURE__*/+ messageDesc(file_v1_saved_query_service, 10);++/**+ * Describes the message bytebase.v1.SetSavedQueryPolicyRequest.+ * Use `create(SetSavedQueryPolicyRequestSchema)` to create a new message.+ */+export const SetSavedQueryPolicyRequestSchema = /*@__PURE__*/+ messageDesc(file_v1_saved_query_service, 11);++/**+ * Describes the message bytebase.v1.SavedQueryPolicy.+ * Use `create(SavedQueryPolicySchema)` to create a new message.+ */+export const SavedQueryPolicySchema = /*@__PURE__*/+ messageDesc(file_v1_saved_query_service, 12);++/**+ * Describes the message bytebase.v1.SavedQueryBinding.+ * Use `create(SavedQueryBindingSchema)` to create a new message.+ */+export const SavedQueryBindingSchema = /*@__PURE__*/+ messageDesc(file_v1_saved_query_service, 13);++/**+ * Describes the enum bytebase.v1.SavedQueryBinding.Level.+ */+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.+ *+ * @generated from enum bytebase.v1.SavedQueryBinding.Level+ */+export const SavedQueryBinding_Level = /*@__PURE__*/+ tsEnum(SavedQueryBinding_LevelSchema);+/*** Describes the message bytebase.v1.DeleteSavedQueryRequest.* Use `create(DeleteSavedQueryRequestSchema)` to create a new message.*/export const DeleteSavedQueryRequestSchema = /*@__PURE__*/- messageDesc(file_v1_saved_query_service, 10);+ messageDesc(file_v1_saved_query_service, 14);/*** Describes the message bytebase.v1.SearchSavedQueriesRequest.* Use `create(SearchSavedQueriesRequestSchema)` to create a new message.*/export const SearchSavedQueriesRequestSchema = /*@__PURE__*/- messageDesc(file_v1_saved_query_service, 11);+ messageDesc(file_v1_saved_query_service, 15);/*** Describes the message bytebase.v1.SearchSavedQueriesResponse.* Use `create(SearchSavedQueriesResponseSchema)` to create a new message.*/export const SearchSavedQueriesResponseSchema = /*@__PURE__*/- messageDesc(file_v1_saved_query_service, 12);+ messageDesc(file_v1_saved_query_service, 16);/*** Describes the message bytebase.v1.SavedQuery.* Use `create(SavedQuerySchema)` to create a new message.*/export const SavedQuerySchema = /*@__PURE__*/- messageDesc(file_v1_saved_query_service, 13);+ messageDesc(file_v1_saved_query_service, 17);/*** SavedQueryService manages saved queries for SQL Editor query development.*- * A saved query is private to its creator; `bb.savedQueries.manage` is the- * admin backstop that can reach any saved query in scope. Per-object- * VIEWER/EDITOR grants arrive with the access-model redesign, which brings- * its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages- * them.+ * 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.** @generated from service bytebase.v1.SavedQueryService*/diff --git a/frontend/src/utils/v1/savedQuery.ts b/frontend/src/utils/v1/savedQuery.tsindex 9980d9baa3..0dc1c61cbd 100644--- a/frontend/src/utils/v1/savedQuery.ts+++ b/frontend/src/utils/v1/savedQuery.ts@@ -1,8 +1,12 @@import { getCurrentUserV1 } from "@/stores";import { getProjectByName } from "@/stores/app/projectAccess";+import { getSavedQueryLevel } from "@/stores/app/savedQueryAccess";import { extractUserEmail } from "@/stores/modules/v1/common";import { UNKNOWN_ID } from "@/types";-import type { SavedQuery } from "@/types/proto-es/v1/saved_query_service_pb";+import {+ type SavedQuery,+ SavedQueryBinding_Level,+} from "@/types/proto-es/v1/saved_query_service_pb";import { hasProjectPermissionV2 } from "@/utils";export const extractSavedQueryID = (name: string) => {@@ -11,18 +15,14 @@ export const extractSavedQueryID = (name: string) => {return matches?.[1] ?? `${UNKNOWN_ID}`;};-// Browsing saved queries takes bb.savedQueries.search on the project, or the-// admin backstop -- the same OR the server's discovery gate applies to Search-// and SearchSavedQueryFolders. A SQL role can grant query access without-// either, in which case the tree stays empty rather than firing requests that-// can only come back denied.-export const canSearchSavedQueriesInProject = (project: string) => {- const resolved = getProjectByName(project);- return (- hasProjectPermissionV2(resolved, "bb.savedQueries.search") ||- hasProjectPermissionV2(resolved, "bb.savedQueries.manage")- );-};+// 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+// without search, in which case the tree stays empty rather than firing+// requests that can only come back denied.+export const canSearchSavedQueriesInProject = (project: string) =>+ hasProjectPermissionV2(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@@ -31,14 +31,20 @@ export const canSearchSavedQueriesInProject = (project: string) => {export const canCreateSavedQueryInProject = (project: string) =>hasProjectPermissionV2(getProjectByName(project), "bb.savedQueries.create");-// Saved queries are private: only the creator, or someone holding-// "bb.savedQueries.manage" (the admin backstop), can read or write one.-// Per-object sharing arrives with the access-model redesign.+// 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.-const canAccessSavedQuery = (sheet: SavedQuery) => {+//+// 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;@@ -49,11 +55,20 @@ const canAccessSavedQuery = (sheet: SavedQuery) => {);};+const grantedLevel = (sheet: SavedQuery) => getSavedQueryLevel(sheet.name);+export const isSavedQueryReadableV1 = (sheet: SavedQuery) =>- canAccessSavedQuery(sheet);+ isCreatorOrAdmin(sheet) ||+ grantedLevel(sheet) >= SavedQueryBinding_Level.VIEWER;export const isSavedQueryWritableV1 = (sheet: SavedQuery) =>- canAccessSavedQuery(sheet);+ isCreatorOrAdmin(sheet) ||+ grantedLevel(sheet) >= SavedQueryBinding_Level.EDITOR;++// 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);// `extractSavedQueryConnection` moved to `@/lib/sqlEditorConnection`// so the database lookup can go through the React app store withoutdiff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex ae7e3cc1fb..45a1ab9875 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -13690,11 +13690,12 @@ paths:- SavedQueryServicesummary: ListSavedQueriesdescription: |-- List saved queries: the grant-independent governance surface. Supports- listing in a project, or across all projects by using `projects/-`, with- whole statements rather than the previews Search returns — e.g. an- offboarding review filtering by creator.- Permissions required: bb.savedQueries.list+ 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/-"operationId: SavedQueryService_ListSavedQueriesparameters:- name: project@@ -13706,25 +13707,21 @@ paths:- name: filterin: querydescription: |-- To filter the list result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Filter the result, in CEL. See https://github.com/google/cel-spec- Supported filter:- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ Supported fields:+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".For example:- creator == "users/{email}"- creator != "users/{email}"+ creator == "users/[email protected]"schema:type: stringtitle: filter- name: pageSizein: querydescription: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.schema:type: integertitle: page_size@@ -13732,11 +13729,10 @@ paths:- name: pageTokenin: querydescription: |-- A page token, received from a previous `ListSavedQueries` call.- Provide this to retrieve the subsequent page.-- When paginating, all other parameters provided to `ListSavedQueries` must match- the call that provided the page token.+ 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.schema:type: stringtitle: page_token@@ -13752,8 +13748,8 @@ paths:- SavedQueryServicesummary: CreateSavedQuerydescription: |-- Creates a personal saved query used in SQL Editor. The creator becomes- the fixed owner.+ Create a saved query. The creator becomes its fixed owner, and the saved+ query starts private.Permissions required: bb.savedQueries.create on the parent projectoperationId: SavedQueryService_CreateSavedQueryparameters:@@ -13784,9 +13780,9 @@ paths:- SavedQueryServicesummary: GetSavedQuerydescription: |-- Get a saved query by name. Returns NotFound for saved queries the- caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: SavedQueryService_GetSavedQueryparameters:- name: project@@ -13813,9 +13809,10 @@ paths:- SavedQueryServicesummary: DeleteSavedQuerydescription: |-- Delete a saved query. Only the creator (or an admin) can delete.- Returns NotFound for saved queries the caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: SavedQueryService_DeleteSavedQueryparameters:- name: project@@ -13842,10 +13839,12 @@ paths:- SavedQueryServicesummary: UpdateSavedQuerydescription: |-- Update a saved query. `title`, `content`, and `database` require write- access; `folder` re-files the saved query and is creator/admin only.- Returns NotFound for saved queries the caller cannot read.- Permissions required: creator, or bb.savedQueries.manage in scope+ 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.manageoperationId: SavedQueryService_UpdateSavedQueryparameters:- name: project@@ -14066,18 +14065,14 @@ paths:type: stringrequestBody:description: |-- The saved query to update.-- The saved query's `name` field is used to identify the saved query to update.+ `saved_query.name` identifies the saved query to update.Format: projects/{project}/savedQueries/{savedQuery}content:application/json:schema:title: saved_querydescription: |-- The saved query to update.-- The saved query's `name` field is used to identify the saved query to update.+ `saved_query.name` identifies the saved query to update.Format: projects/{project}/savedQueries/{savedQuery}$ref: '#/components/schemas/bytebase.v1.SavedQuery'responses:@@ -14087,18 +14082,95 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.SavedQuery'+ /v1/projects/{project}/savedQueries/{savedQuery}:getPolicy:+ get:+ tags:+ - SavedQueryService+ summary: 'Get a saved query''s sharing policy: who it is shared with, at what level.'+ 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+ operationId: SavedQueryService_GetSavedQueryPolicy+ parameters:+ - name: project+ in: path+ description: The project id.+ required: true+ schema:+ type: string+ - name: savedQuery+ in: path+ description: The savedQuery id.+ required: true+ schema:+ type: string+ responses:+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'+ /v1/projects/{project}/savedQueries/{savedQuery}:setPolicy:+ post:+ tags:+ - SavedQueryService+ 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+ operationId: SavedQueryService_SetSavedQueryPolicy+ parameters:+ - name: project+ in: path+ description: The project id.+ required: true+ schema:+ type: string+ - name: savedQuery+ in: path+ description: The savedQuery id.+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ 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.+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'+ title: SetSavedQueryPolicyRequest+ required:+ - policy+ additionalProperties: false+ required: true+ responses:+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'/v1/projects/{project}/savedQueries/{savedQuery}:updateStar:post:tags:- SavedQueryServicesummary: UpdateSavedQueryStardescription: |-- Star or unstar a saved query for the caller. A star is always the- caller's own per-user marker — invisible to others and carrying no- access. The only requirement is that the caller can read the saved- query being starred (which also keeps private saved query names- unprobeable).- Permissions required: read access to the saved query+ Star or unstar a saved query for the caller. A star is a per-user marker:+ invisible to everyone else and granting nothing. Read access is the gate+ only so unreadable saved queries stay unprobeable.+ Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manageoperationId: SavedQueryService_UpdateSavedQueryStarparameters:- name: project@@ -14139,10 +14211,11 @@ paths:- SavedQueryServicesummary: BatchUpdateSavedQueriesdescription: |-- Batch re-file saved queries into a folder. The update mask supports- `folder` only; only rows the caller may re-file are updated (their own,- or any in scope for admins).- Permissions required: creator, or bb.savedQueries.manage in scope+ Re-file saved queries into a folder in bulk; the update mask supports+ `folder` only. An EDITOR binding does not carry re-filing, so matched+ saved queries the caller cannot re-file are skipped rather than rejected,+ and the response counts what actually changed.+ Permissions required: creator, or bb.savedQueries.manageoperationId: SavedQueryService_BatchUpdateSavedQueriesparameters:- name: project@@ -14161,24 +14234,21 @@ paths:type: stringtitle: filterdescription: |-- To filter the batch update target.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec-- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support exact "==" operator.+ Select the saved queries to update, in CEL. See+ https://github.com/google/cel-spec++ Supported fields:+ - name: the saved query name. Supports "==" and "in [...]".+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ - starred: whether the caller starred it. Supports "==".+ - folder: the exact folder path. Supports "==".savedQuery:title: saved_query- description: The fields to apply to every matched saved query.+ description: The values to apply to every matched saved query.$ref: '#/components/schemas/bytebase.v1.SavedQuery'updateMask:title: update_mask- description: |-- The list of fields to be updated.- Only support update the following fields for now:- - `folder`+ description: 'Fields to update. Supported: `folder`.'$ref: '#/components/schemas/google.protobuf.FieldMask'title: BatchUpdateSavedQueriesRequestrequired:@@ -14197,11 +14267,16 @@ paths:post:tags:- SavedQueryService- summary: SearchSavedQueries- description: |-- Search for saved queries in a project: the SQL Editor's hot list path,- returning only rows the caller can read, with content previews.- Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ 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.+ Permissions required: bb.savedQueries.search on the projectoperationId: SavedQueryService_SearchSavedQueriesparameters:- name: project@@ -14220,38 +14295,45 @@ paths:type: stringtitle: filterdescription: |-- To filter the search result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec-- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - title: the saved query title, support "contains" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support "==" operator.+ Filter the result, in CEL. See https://github.com/google/cel-spec++ Supported fields:+ - 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 "==".+ - 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.For example:- creator == "users/{email}"- title.contains("saved query title")- creator != "users/{email}"+ creator == "users/[email protected]"+ shared == truestarred == true- starred == false+ title.contains("weekly report")folder == "foo/bar"pageSize:type: integertitle: page_sizeformat: int32description: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.pageToken:type: stringtitle: page_tokendescription: |-- A page token, received from a previous `SearchSavedQueries` call.- Provide this to retrieve the subsequent page.+ 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.title: SearchSavedQueriesRequestadditionalProperties: falserequired: true@@ -14266,14 +14348,18 @@ paths:post:tags:- SavedQueryService- summary: SearchSavedQueryFolders- description: |-- Search the folder paths of the caller's saved queries in a project.- Folders are a derived view over the `folder` field rather than a- resource collection, so this is a custom method on savedQueries and- shares SearchSavedQueries' caller-scoped semantics — not the- cross-creator reach of ListSavedQueries.- Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ 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`).+ Permissions required: bb.savedQueries.search on the projectoperationId: SavedQueryService_SearchSavedQueryFoldersparameters:- name: project@@ -14292,15 +14378,9 @@ paths:type: stringtitle: filterdescription: |-- To filter the folders by the saved queries they hold. Takes the same- fields and syntax as `SearchSavedQueries.filter`, except `title`. A- folder is returned when at least one saved query the caller can read- matches, so the caller-scoping is the same as SearchSavedQueries: your- own saved queries, plus everyone's for the admin backstop.-- For example, to split a folder tree into your own and everyone else's:- creator == "users/{email}"- creator != "users/{email}"+ Filter folders by the saved queries they hold. Takes the same fields and+ syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ when at least one saved query the caller can read matches.title: SearchSavedQueryFoldersRequestadditionalProperties: falserequired: true@@ -20054,31 +20134,26 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource whose saved queries are updated.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the batch update target.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Select the saved queries to update, in CEL. See+ https://github.com/google/cel-spec- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support exact "==" operator.+ Supported fields:+ - name: the saved query name. Supports "==" and "in [...]".+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ - starred: whether the caller starred it. Supports "==".+ - folder: the exact folder path. Supports "==".savedQuery:title: saved_query- description: The fields to apply to every matched saved query.+ description: The values to apply to every matched saved query.$ref: '#/components/schemas/bytebase.v1.SavedQuery'updateMask:title: update_mask- description: |-- The list of fields to be updated.- Only support update the following fields for now:- - `folder`+ description: 'Fields to update. Supported: `folder`.'$ref: '#/components/schemas/google.protobuf.FieldMask'title: BatchUpdateSavedQueriesRequestrequired:@@ -20093,7 +20168,9 @@ components:type: integertitle: updated_countformat: int32- description: The number of saved queries updated.+ description: |-+ How many saved queries were updated, which may be fewer than the filter+ matched.title: BatchUpdateSavedQueriesResponseadditionalProperties: falsebytebase.v1.BillingInterval:@@ -20974,7 +21051,7 @@ components:type: stringtitle: parentdescription: |-- The parent resource where this saved query will be created.+ The project to create the saved query in.Format: projects/{project}savedQuery:title: saved_query@@ -22075,9 +22152,7 @@ components:name:type: stringtitle: name- description: |-- The name of the saved query to delete.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'title: DeleteSavedQueryRequestrequired:- name@@ -23252,15 +23327,24 @@ components:required:- nameadditionalProperties: false+ bytebase.v1.GetSavedQueryPolicyRequest:+ type: object+ properties:+ resource:+ type: string+ title: resource+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'+ title: GetSavedQueryPolicyRequest+ required:+ - resource+ additionalProperties: falsebytebase.v1.GetSavedQueryRequest:type: objectproperties:name:type: stringtitle: name- description: |-- The name of the saved query to retrieve.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'title: GetSavedQueryRequestrequired:- name@@ -25490,40 +25574,34 @@ components:type: stringtitle: parentdescription: |-- The parent resource of the saved queries.+ The project to list saved queries in, or "projects/-" for every project.Format: projects/{project}- Use "projects/-" to list saved queries across all projects.filter:type: stringtitle: filterdescription: |-- To filter the list result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Filter the result, in CEL. See https://github.com/google/cel-spec- Supported filter:- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ Supported fields:+ - creator: the creator in "users/{email}" format. Supports "==" and "!=".For example:- creator == "users/{email}"- creator != "users/{email}"+ creator == "users/[email protected]"pageSize:type: integertitle: page_sizeformat: int32description: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.pageToken:type: stringtitle: page_tokendescription: |-- A page token, received from a previous `ListSavedQueries` call.- Provide this to retrieve the subsequent page.-- When paginating, all other parameters provided to `ListSavedQueries` must match- the call that provided the page token.+ 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.title: ListSavedQueriesRequestrequired:- parent@@ -25536,14 +25614,12 @@ components:items:$ref: '#/components/schemas/bytebase.v1.SavedQuery'title: saved_queries- description: The saved queries from the specified parent.nextPageToken:type: stringtitle: next_page_tokendescription: |-- A token to retrieve next page of saved queries.- Pass this value in the page_token field in the subsequent call to- `ListSavedQueries` method to retrieve the next page of saved queries.+ Pass to the next ListSavedQueries call to fetch the following page. Empty+ on the last page.title: ListSavedQueriesResponseadditionalProperties: falsebytebase.v1.ListServiceAccountsRequest:@@ -28774,23 +28850,21 @@ components:type: stringtitle: namedescription: |-- (IMMUTABLE) The name of the saved query resource, generated by the server.- Canonical parent is project.+ (IMMUTABLE) Server-generated.Format: projects/{project}/savedQueries/{savedQuery}project:type: stringtitle: project- description: |-- The project resource name.- Format: projects/{project}+ description: 'Format: projects/{project}'readOnly: truedatabase:type: stringtitle: databasedescription: |-- The database resource name.+ The connected database, which must belong to the saved query's own+ project. Empty when none is connected, or when the database no longer+ exists.Format: instances/{instance}/databases/{database}- If the database parent doesn't exist, the database field is empty.title:type: stringtitle: title@@ -28800,18 +28874,15 @@ components:type: stringtitle: creatordescription: |-- The creator of the SavedQuery — the fixed owner; ownership does not- transfer.+ The fixed owner. Ownership does not transfer.Format: users/{email}readOnly: truecreateTime:title: create_time- description: The create time of the saved query.readOnly: true$ref: '#/components/schemas/google.protobuf.Timestamp'updateTime:title: update_time- description: The last update time of the saved query.readOnly: true$ref: '#/components/schemas/google.protobuf.Timestamp'content:@@ -28819,36 +28890,100 @@ components:title: contentformat: bytedescription: |-- The content of the saved query.- By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can- use GetSavedQuery() request to retrieve the full content.+ The SQL text. SearchSavedQueries truncates it; when it is shorter than+ `content_size`, GetSavedQuery returns the whole thing.contentSize:type:- integer- stringtitle: content_sizeformat: int64- description: content_size is the full size of the content, may not match the size of the `content` field.+ description: The full size of the content, which may exceed the `content` returned.readOnly: truestarred:type: booleantitle: starred- description: starred indicates whether the saved query is starred by the current authenticated user.+ description: Whether the calling user starred it.readOnly: truefolder:type: stringtitle: foldermaxLength: 256description: |-- The folder path this saved query lives in, set by its creator (or an- admin). Empty means unfiled. A saved query lives in exactly one folder;- a folder is a path on saved queries, e.g. "a/b/c".+ The folder holding this saved query, set by its creator or an admin. A+ path like "a/b/c"; empty means unfiled.title: SavedQueryrequired:- name- title- contentadditionalProperties: false+ bytebase.v1.SavedQueryBinding:+ type: object+ properties:+ level:+ title: level+ $ref: '#/components/schemas/bytebase.v1.SavedQueryBinding.Level'+ members:+ type: array+ items:+ type: string+ 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.++ 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.+ 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.+ bytebase.v1.SavedQueryBinding.Level:+ type: string+ title: Level+ enum:+ - LEVEL_UNSPECIFIED+ - VIEWER+ - EDITOR+ description: |-+ Nested because bytebase.v1 already defines a package-scoped EDITOR+ (DatabaseChangeMode), and enum values live in the enclosing scope.+ bytebase.v1.SavedQueryPolicy:+ type: object+ properties:+ bindings:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.SavedQueryBinding'+ title: bindings+ description: |-+ At most one binding per level. A member listed under two levels is+ rejected rather than resolved to the higher one.+ etag:+ type: string+ title: etag+ description: |-+ The etag of the policy as read. SetSavedQueryPolicy requires it and fails+ with ABORTED when it no longer matches.+ 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.bytebase.v1.SchemaCatalog:type: objectproperties:@@ -29327,45 +29462,50 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource of the saved queries.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the search result.- The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ Filter the result, in CEL. See https://github.com/google/cel-spec- Supported filter:- - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- - title: the saved query title, support "contains" operator.- - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- - folder: the saved query folder path, support "==" operator.+ Supported fields:+ - 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 "==".+ - 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.For example:- creator == "users/{email}"- title.contains("saved query title")- creator != "users/{email}"+ creator == "users/[email protected]"+ shared == truestarred == true- starred == false+ title.contains("weekly report")folder == "foo/bar"pageSize:type: integertitle: page_sizeformat: int32description: |-- The maximum number of saved queries to return. The service may return fewer than- this value.- If unspecified, at most 10 saved queries will be returned.- The maximum value is 1000; values above 1000 will be coerced to 1000.+ The maximum number of saved queries to return. The service may return+ fewer. Defaults to 10; values above 1000 are coerced to 1000.pageToken:type: stringtitle: page_tokendescription: |-- A page token, received from a previous `SearchSavedQueries` call.- Provide this to retrieve the subsequent page.+ 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.title: SearchSavedQueriesRequestrequired:- parent@@ -29378,14 +29518,12 @@ components:items:$ref: '#/components/schemas/bytebase.v1.SavedQuery'title: saved_queries- description: The saved queries that matched the search criteria.nextPageToken:type: stringtitle: next_page_tokendescription: |-- A token to retrieve next page of saved queries.- Pass this value in the page_token field in the subsequent call to- `SearchSavedQueries` method to retrieve the next page of saved queries.+ Pass to the next SearchSavedQueries call to fetch the following page.+ Empty on the last page.title: SearchSavedQueriesResponseadditionalProperties: falsebytebase.v1.SearchSavedQueryFoldersRequest:@@ -29394,22 +29532,14 @@ components:parent:type: stringtitle: parent- description: |-- The parent resource whose saved query folders are searched.- Format: projects/{project}+ description: 'Format: projects/{project}'filter:type: stringtitle: filterdescription: |-- To filter the folders by the saved queries they hold. Takes the same- fields and syntax as `SearchSavedQueries.filter`, except `title`. A- folder is returned when at least one saved query the caller can read- matches, so the caller-scoping is the same as SearchSavedQueries: your- own saved queries, plus everyone's for the admin backstop.-- For example, to split a folder tree into your own and everyone else's:- creator == "users/{email}"- creator != "users/{email}"+ Filter folders by the saved queries they hold. Takes the same fields and+ syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ when at least one saved query the caller can read matches.title: SearchSavedQueryFoldersRequestrequired:- parent@@ -29423,9 +29553,8 @@ components:type: stringtitle: foldersdescription: |-- The caller's folder paths, including every ancestor prefix, sorted.- A folder is a path on saved queries ("a/b/c"), so empty folders cannot- exist.+ Folder paths, every ancestor prefix included, sorted. A folder is a path+ on saved queries ("a/b/c"), so empty folders cannot exist.title: SearchSavedQueryFoldersResponseadditionalProperties: falsebytebase.v1.SemanticTypeSetting:@@ -29601,6 +29730,24 @@ components:- policyadditionalProperties: falsedescription: Request message for setting an IAM policy.+ bytebase.v1.SetSavedQueryPolicyRequest:+ type: object+ properties:+ resource:+ type: string+ title: resource+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'+ 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.+ $ref: '#/components/schemas/bytebase.v1.SavedQueryPolicy'+ title: SetSavedQueryPolicyRequest+ required:+ - resource+ - policy+ additionalProperties: falsebytebase.v1.Setting:type: objectproperties:@@ -31835,22 +31982,14 @@ components:savedQuery:title: saved_querydescription: |-- The saved query to update.-- The saved query's `name` field is used to identify the saved query to update.+ `saved_query.name` identifies the saved query to update.Format: projects/{project}/savedQueries/{savedQuery}$ref: '#/components/schemas/bytebase.v1.SavedQuery'updateMask:title: update_maskdescription: |-- The list of fields to be updated.- Fields are specified relative to the saved query.- (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)- Only support update the following fields for now:- - `title`- - `content`- - `database`- - `folder`+ Fields to update, relative to the saved query (`title`, not+ `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.$ref: '#/components/schemas/google.protobuf.FieldMask'title: UpdateSavedQueryRequestrequired:@@ -31862,9 +32001,7 @@ components:name:type: stringtitle: name- description: |-- The name of the saved query to star or unstar.- Format: projects/{project}/savedQueries/{savedQuery}+ description: 'Format: projects/{project}/savedQueries/{savedQuery}'starred:type: booleantitle: starred@@ -33935,11 +34072,14 @@ tags:description: |-SavedQueryService manages saved queries for SQL Editor query development.- A saved query is private to its creator; `bb.savedQueries.manage` is the- admin backstop that can reach any saved query in scope. Per-object- VIEWER/EDITOR grants arrive with the access-model redesign, which brings- its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages- them.+ 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.- name: ServiceAccountServicedescription: ServiceAccountService manages service accounts for API integrations.- name: SheetServicediff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex e8fedcb282..8700a1e1db 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -244,8 +244,11 @@- [RolePermissions](#bytebase-store-RolePermissions)- [store/saved_query.proto](#store_saved_query-proto)+ - [SavedQueryBinding](#bytebase-store-SavedQueryBinding)- [SavedQueryPayload](#bytebase-store-SavedQueryPayload)+ - [SavedQueryBinding.Level](#bytebase-store-SavedQueryBinding-Level)+- [store/server_config.proto](#store_server_config-proto)- [ServerConfigPayload](#bytebase-store-ServerConfigPayload)@@ -4142,6 +4145,25 @@ The severity level for SQL review rules.+<a name="bytebase-store-SavedQueryBinding"></a>++### SavedQueryBinding+One grant on a saved query. Stored in saved_query.bindings, which holds a+protojson array of these messages at the jsonb root rather than a wrapper+object, so the `@>` containment probes the access queries run hit the GIN+index directly.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| level | [SavedQueryBinding.Level](#bytebase-store-SavedQueryBinding-Level) | | |+| members | [string](#string) | repeated | Principals in the same resource-name form the IAM policy payloads use: "users/{email}" and "groups/{email}". The v1 API takes the binding form ("user:", "group:") and converts once on write, as the project policy does. Groups are named by reference and never expanded. |++++++<a name="bytebase-store-SavedQueryPayload"></a>### SavedQueryPayload@@ -4158,6 +4180,19 @@ The severity level for SQL review rules.++<a name="bytebase-store-SavedQueryBinding-Level"></a>++### SavedQueryBinding.Level+++| Name | Number | Description |+| ---- | ------ | ----------- |+| LEVEL_UNSPECIFIED | 0 | |+| VIEWER | 1 | |+| EDITOR | 2 | |++diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex 83bc2014d6..73a762a579 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -1154,11 +1154,19 @@<a href="#store%2fsaved_query.proto">store/saved_query.proto</a><ul>+ <li>+ <a href="#bytebase.store.SavedQueryBinding"><span class="badge">M</span>SavedQueryBinding</a>+ </li>+<li><a href="#bytebase.store.SavedQueryPayload"><span class="badge">M</span>SavedQueryPayload</a></li>+ <li>+ <a href="#bytebase.store.SavedQueryBinding.Level"><span class="badge">E</span>SavedQueryBinding.Level</a>+ </li>+</ul>@@ -11704,6 +11712,40 @@ unreadable and the revision carries no sheet name. </p></td><p></p>+ <h3 id="bytebase.store.SavedQueryBinding">SavedQueryBinding</h3>+ <p>One grant on a saved query. Stored in saved_query.bindings, which holds a</p><p>protojson array of these messages at the jsonb root rather than a wrapper</p><p>object, so the `@>` containment probes the access queries run hit the GIN</p><p>index directly.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>level</td>+ <td><a href="#bytebase.store.SavedQueryBinding.Level">SavedQueryBinding.Level</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>members</td>+ <td><a href="#string">string</a></td>+ <td>repeated</td>+ <td><p>Principals in the same resource-name form the IAM policy payloads use:+"users/{email}" and "groups/{email}". The v1 API takes the binding form+("user:", "group:") and converts once on write, as the project policy+does. Groups are named by reference and never expanded. </p></td>+ </tr>++ </tbody>+ </table>+++++<h3 id="bytebase.store.SavedQueryPayload">SavedQueryPayload</h3><p></p>@@ -11735,6 +11777,35 @@ is deleted or transferred, degrading to "no database" in the UI. </p></t+ <h3 id="bytebase.store.SavedQueryBinding.Level">SavedQueryBinding.Level</h3>+ <p></p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>LEVEL_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>VIEWER</td>+ <td>1</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>EDITOR</td>+ <td>2</td>+ <td><p></p></td>+ </tr>++ </tbody>+ </table>+diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 3fcb8e4229..351615add5 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -683,17 +683,23 @@- [BatchUpdateSavedQueriesResponse](#bytebase-v1-BatchUpdateSavedQueriesResponse)- [CreateSavedQueryRequest](#bytebase-v1-CreateSavedQueryRequest)- [DeleteSavedQueryRequest](#bytebase-v1-DeleteSavedQueryRequest)+ - [GetSavedQueryPolicyRequest](#bytebase-v1-GetSavedQueryPolicyRequest)- [GetSavedQueryRequest](#bytebase-v1-GetSavedQueryRequest)- [ListSavedQueriesRequest](#bytebase-v1-ListSavedQueriesRequest)- [ListSavedQueriesResponse](#bytebase-v1-ListSavedQueriesResponse)- [SavedQuery](#bytebase-v1-SavedQuery)+ - [SavedQueryBinding](#bytebase-v1-SavedQueryBinding)+ - [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy)- [SearchSavedQueriesRequest](#bytebase-v1-SearchSavedQueriesRequest)- [SearchSavedQueriesResponse](#bytebase-v1-SearchSavedQueriesResponse)- [SearchSavedQueryFoldersRequest](#bytebase-v1-SearchSavedQueryFoldersRequest)- [SearchSavedQueryFoldersResponse](#bytebase-v1-SearchSavedQueryFoldersResponse)+ - [SetSavedQueryPolicyRequest](#bytebase-v1-SetSavedQueryPolicyRequest)- [UpdateSavedQueryRequest](#bytebase-v1-UpdateSavedQueryRequest)- [UpdateSavedQueryStarRequest](#bytebase-v1-UpdateSavedQueryStarRequest)+ - [SavedQueryBinding.Level](#bytebase-v1-SavedQueryBinding-Level)+- [SavedQueryService](#bytebase-v1-SavedQueryService)- [v1/service_account_service.proto](#v1_service_account_service-proto)@@ -11052,12 +11058,12 @@ RoleService manages workspace roles and permissions.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| parent | [string](#string) | | The parent resource whose saved queries are updated. Format: projects/{project} |-| filter | [string](#string) | | To filter the batch update target. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+| parent | [string](#string) | | Format: projects/{project} |+| filter | [string](#string) | | Select the saved queries to update, in CEL. See https://github.com/google/cel-spec-Supported filter: - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator. - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator. - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator. - folder: the saved query folder path, support exact "==" operator. |-| saved_query | [SavedQuery](#bytebase-v1-SavedQuery) | | The fields to apply to every matched saved query. |-| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | The list of fields to be updated. Only support update the following fields for now: - `folder` |+Supported fields: - name: the saved query name. Supports "==" and "in [...]". - creator: the creator in "users/{email}" format. Supports "==" and "!=". - starred: whether the caller starred it. Supports "==". - folder: the exact folder path. Supports "==". |+| saved_query | [SavedQuery](#bytebase-v1-SavedQuery) | | The values to apply to every matched saved query. |+| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | Fields to update. Supported: `folder`. |@@ -11072,7 +11078,7 @@ Supported filter: - name: the saved query name in "projects/{project}/savedQ| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| updated_count | [int32](#int32) | | The number of saved queries updated. |+| updated_count | [int32](#int32) | | How many saved queries were updated, which may be fewer than the filter matched. |@@ -11087,7 +11093,7 @@ Supported filter: - name: the saved query name in "projects/{project}/savedQ| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| parent | [string](#string) | | The parent resource where this saved query will be created. Format: projects/{project} |+| parent | [string](#string) | | The project to create the saved query in. Format: projects/{project} || saved_query | [SavedQuery](#bytebase-v1-SavedQuery) | | The saved query to create. |@@ -11103,7 +11109,22 @@ Supported filter: - name: the saved query name in "projects/{project}/savedQ| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| name | [string](#string) | | The name of the saved query to delete. Format: projects/{project}/savedQueries/{savedQuery} |+| name | [string](#string) | | Format: projects/{project}/savedQueries/{savedQuery} |+++++++<a name="bytebase-v1-GetSavedQueryPolicyRequest"></a>++### GetSavedQueryPolicyRequest++++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| resource | [string](#string) | | Format: projects/{project}/savedQueries/{savedQuery} |@@ -11118,7 +11139,7 @@ Supported filter: - name: the saved query name in "projects/{project}/savedQ| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| name | [string](#string) | | The name of the saved query to retrieve. Format: projects/{project}/savedQueries/{savedQuery} |+| name | [string](#string) | | Format: projects/{project}/savedQueries/{savedQuery} |@@ -11133,16 +11154,14 @@ Supported filter: - name: the saved query name in "projects/{project}/savedQ| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| parent | [string](#string) | | The parent resource of the saved queries. Format: projects/{project} Use "projects/-" to list saved queries across all projects. |-| filter | [string](#string) | | To filter the list result. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec--Supported filter: - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+| parent | [string](#string) | | The project to list saved queries in, or "projects/-" for every project. Format: projects/{project} |+| filter | [string](#string) | | Filter the result, in CEL. See https://github.com/google/cel-spec-For example: creator == "users/{email}" creator != "users/{email}" |-| page_size | [int32](#int32) | | The maximum number of saved queries to return. The service may return fewer than this value. If unspecified, at most 10 saved queries will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. |-| page_token | [string](#string) | | A page token, received from a previous `ListSavedQueries` call. Provide this to retrieve the subsequent page.+Supported fields: - creator: the creator in "users/{email}" format. Supports "==" and "!=".-When paginating, all other parameters provided to `ListSavedQueries` must match the call that provided the page token. |+For example: creator == "users/[email protected]" |+| 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. |@@ -11157,8 +11176,8 @@ When paginating, all other parameters provided to `ListSavedQueries` must match| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| saved_queries | [SavedQuery](#bytebase-v1-SavedQuery) | repeated | The saved queries from the specified parent. |-| next_page_token | [string](#string) | | A token to retrieve next page of saved queries. Pass this value in the page_token field in the subsequent call to `ListSavedQueries` method to retrieve the next page of saved queries. |+| saved_queries | [SavedQuery](#bytebase-v1-SavedQuery) | repeated | |+| next_page_token | [string](#string) | | Pass to the next ListSavedQueries call to fetch the following page. Empty on the last page. |@@ -11173,17 +11192,56 @@ When paginating, all other parameters provided to `ListSavedQueries` must match| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| name | [string](#string) | | The name of the saved query resource, generated by the server. Canonical parent is project. Format: projects/{project}/savedQueries/{savedQuery} |-| project | [string](#string) | | The project resource name. Format: projects/{project} |-| database | [string](#string) | | The database resource name. Format: instances/{instance}/databases/{database} If the database parent doesn't exist, the database field is empty. |+| name | [string](#string) | | Server-generated. Format: projects/{project}/savedQueries/{savedQuery} |+| project | [string](#string) | | Format: projects/{project} |+| database | [string](#string) | | The connected database, which must belong to the saved query'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 creator of the SavedQuery — the fixed owner; ownership does not transfer. Format: users/{email} |-| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The create time of the saved query. |-| update_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The last update time of the saved query. |-| content | [bytes](#bytes) | | The content of the saved query. By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can use GetSavedQuery() request to retrieve the full content. |-| content_size | [int64](#int64) | | content_size is the full size of the content, may not match the size of the `content` field. |-| starred | [bool](#bool) | | starred indicates whether the saved query is starred by the current authenticated user. |-| folder | [string](#string) | | The folder path this saved query lives in, set by its creator (or an admin). Empty means unfiled. A saved query lives in exactly one folder; a folder is a path on saved queries, e.g. "a/b/c". |+| creator | [string](#string) | | The fixed 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_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 "a/b/c"; empty means unfiled. |+++++++<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.+++| 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 "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.++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. |+++++++<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.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| bindings | [SavedQueryBinding](#bytebase-v1-SavedQueryBinding) | repeated | At most one binding per level. A member listed under two levels is rejected rather than resolved to the higher one. |+| etag | [string](#string) | | The etag of the policy as read. SetSavedQueryPolicy requires it and fails with ABORTED when it no longer matches. |@@ -11198,14 +11256,16 @@ When paginating, all other parameters provided to `ListSavedQueries` must match| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| parent | [string](#string) | | The parent resource of the saved queries. Format: projects/{project} |-| filter | [string](#string) | | To filter the search result. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+| parent | [string](#string) | | Format: projects/{project} |+| filter | [string](#string) | | Filter the result, in CEL. See https://github.com/google/cel-spec-Supported filter: - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator. - title: the saved query title, support "contains" operator. - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator. - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator. - folder: the saved query folder path, support "==" operator.+Supported fields: - 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 "==". - starred: whether the caller starred it. Supports "==". - folder: the exact folder path. Supports "==".-For example: creator == "users/{email}" title.contains("saved query title") creator != "users/{email}" starred == true starred == false folder == "foo/bar" |-| page_size | [int32](#int32) | | The maximum number of saved queries to return. The service may return fewer than this value. If unspecified, at most 10 saved queries will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. |-| page_token | [string](#string) | | A page token, received from a previous `SearchSavedQueries` call. Provide this to retrieve the subsequent page. |+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.++For example: creator == "users/[email protected]" shared == true starred == true title.contains("weekly report") folder == "foo/bar" |+| 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. |@@ -11220,8 +11280,8 @@ For example: creator == "users/{email}" title.contains("saved query| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| saved_queries | [SavedQuery](#bytebase-v1-SavedQuery) | repeated | The saved queries that matched the search criteria. |-| next_page_token | [string](#string) | | A token to retrieve next page of saved queries. Pass this value in the page_token field in the subsequent call to `SearchSavedQueries` method to retrieve the next page of saved queries. |+| saved_queries | [SavedQuery](#bytebase-v1-SavedQuery) | repeated | |+| next_page_token | [string](#string) | | Pass to the next SearchSavedQueries call to fetch the following page. Empty on the last page. |@@ -11236,10 +11296,8 @@ For example: creator == "users/{email}" title.contains("saved query| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| parent | [string](#string) | | The parent resource whose saved query folders are searched. Format: projects/{project} |-| filter | [string](#string) | | To filter the folders by the saved queries they hold. Takes the same fields and syntax as `SearchSavedQueries.filter`, except `title`. A folder is returned when at least one saved query the caller can read matches, so the caller-scoping is the same as SearchSavedQueries: your own saved queries, plus everyone's for the admin backstop.--For example, to split a folder tree into your own and everyone else's: creator == "users/{email}" creator != "users/{email}" |+| parent | [string](#string) | | Format: projects/{project} |+| filter | [string](#string) | | Filter folders by the saved queries they hold. Takes the same fields and syntax as SearchSavedQueries.filter, except `title`. A folder is returned when at least one saved query the caller can read matches. |@@ -11254,7 +11312,23 @@ For example, to split a folder tree into your own and everyone else's: creat| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| folders | [string](#string) | repeated | The caller's folder paths, including every ancestor prefix, sorted. A folder is a path on saved queries ("a/b/c"), so empty folders cannot exist. |+| folders | [string](#string) | repeated | Folder paths, every ancestor prefix included, sorted. A folder is a path on saved queries ("a/b/c"), so empty folders cannot exist. |+++++++<a name="bytebase-v1-SetSavedQueryPolicyRequest"></a>++### SetSavedQueryPolicyRequest++++| 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. |@@ -11269,10 +11343,8 @@ For example, to split a folder tree into your own and everyone else's: creat| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| saved_query | [SavedQuery](#bytebase-v1-SavedQuery) | | The saved query to update.--The saved query's `name` field is used to identify the saved query to update. Format: projects/{project}/savedQueries/{savedQuery} |-| update_mask | [google.protobuf.FieldMask](#google-protobuf-FieldMask) | | The list of fields to be updated. Fields are specified relative to the saved query. (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`) Only support update the following fields for now: - `title` - `content` - `database` - `folder` |+| 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`. |@@ -11287,7 +11359,7 @@ The saved query's `name` field is used to identify the saved query to update| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| name | [string](#string) | | The name of the saved query to star or unstar. Format: projects/{project}/savedQueries/{savedQuery} |+| name | [string](#string) | | Format: projects/{project}/savedQueries/{savedQuery} || starred | [bool](#bool) | | Whether the caller stars the saved query. |@@ -11296,6 +11368,20 @@ The saved query's `name` field is used to identify the saved query to update++<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.++| 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. |++@@ -11306,23 +11392,34 @@ The saved query's `name` field is used to identify the saved query to update### SavedQueryServiceSavedQueryService manages saved queries for SQL Editor query development.-A saved query is private to its creator; `bb.savedQueries.manage` is the-admin backstop that can reach any saved query in scope. Per-object-VIEWER/EDITOR grants arrive with the access-model redesign, which brings-its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages-them.+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.| Method Name | Request Type | Response Type | Description || ----------- | ------------ | ------------- | ------------|-| CreateSavedQuery | [CreateSavedQueryRequest](#bytebase-v1-CreateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Creates a personal saved query used in SQL Editor. The creator becomes the fixed owner. Permissions required: bb.savedQueries.create on the parent project |-| GetSavedQuery | [GetSavedQueryRequest](#bytebase-v1-GetSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Get a saved query by name. Returns NotFound for saved queries the caller cannot read. Permissions required: creator, or bb.savedQueries.manage in scope |-| ListSavedQueries | [ListSavedQueriesRequest](#bytebase-v1-ListSavedQueriesRequest) | [ListSavedQueriesResponse](#bytebase-v1-ListSavedQueriesResponse) | List saved queries: the grant-independent governance surface. Supports listing in a project, or across all projects by using `projects/-`, with whole statements rather than the previews Search returns — e.g. an offboarding review filtering by creator. Permissions required: bb.savedQueries.list |-| SearchSavedQueries | [SearchSavedQueriesRequest](#bytebase-v1-SearchSavedQueriesRequest) | [SearchSavedQueriesResponse](#bytebase-v1-SearchSavedQueriesResponse) | Search for saved queries in a project: the SQL Editor's hot list path, returning only rows the caller can read, with content previews. Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project |-| SearchSavedQueryFolders | [SearchSavedQueryFoldersRequest](#bytebase-v1-SearchSavedQueryFoldersRequest) | [SearchSavedQueryFoldersResponse](#bytebase-v1-SearchSavedQueryFoldersResponse) | Search the folder paths of the caller's saved queries in a project. Folders are a derived view over the `folder` field rather than a resource collection, so this is a custom method on savedQueries and shares SearchSavedQueries' caller-scoped semantics — not the cross-creator reach of ListSavedQueries. Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project |-| UpdateSavedQuery | [UpdateSavedQueryRequest](#bytebase-v1-UpdateSavedQueryRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Update a saved query. `title`, `content`, and `database` require write access; `folder` re-files the saved query and is creator/admin only. Returns NotFound for saved queries the caller cannot read. Permissions required: creator, or bb.savedQueries.manage in scope |-| UpdateSavedQueryStar | [UpdateSavedQueryStarRequest](#bytebase-v1-UpdateSavedQueryStarRequest) | [SavedQuery](#bytebase-v1-SavedQuery) | Star or unstar a saved query for the caller. A star is always the caller's own per-user marker — invisible to others and carrying no access. The only requirement is that the caller can read the saved query being starred (which also keeps private saved query names unprobeable). Permissions required: read access to the saved query |-| BatchUpdateSavedQueries | [BatchUpdateSavedQueriesRequest](#bytebase-v1-BatchUpdateSavedQueriesRequest) | [BatchUpdateSavedQueriesResponse](#bytebase-v1-BatchUpdateSavedQueriesResponse) | Batch re-file saved queries into a folder. The update mask supports `folder` only; only rows the caller may re-file are updated (their own, or any in scope for admins). Permissions required: creator, or bb.savedQueries.manage in scope |-| DeleteSavedQuery | [DeleteSavedQueryRequest](#bytebase-v1-DeleteSavedQueryRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Delete a saved query. Only the creator (or an admin) can delete. Returns NotFound for saved queries the caller cannot read. Permissions required: creator, or bb.savedQueries.manage in scope |+| 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'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/-" |+| SearchSavedQueries | [SearchSavedQueriesRequest](#bytebase-v1-SearchSavedQueriesRequest) | [SearchSavedQueriesResponse](#bytebase-v1-SearchSavedQueriesResponse) | 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. 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 == "users/me"`) 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'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. A star is a per-user marker: invisible to everyone else and granting nothing. Read access is the gate only so unreadable saved queries stay unprobeable. Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage |+| BatchUpdateSavedQueries | [BatchUpdateSavedQueriesRequest](#bytebase-v1-BatchUpdateSavedQueriesRequest) | [BatchUpdateSavedQueriesResponse](#bytebase-v1-BatchUpdateSavedQueriesResponse) | Re-file saved queries into a folder in bulk; the update mask supports `folder` only. An EDITOR binding does not carry re-filing, so matched saved queries the caller cannot re-file are skipped rather than rejected, and the response counts what actually changed. Permissions required: creator, or bb.savedQueries.manage |+| DeleteSavedQuery | [DeleteSavedQueryRequest](#bytebase-v1-DeleteSavedQueryRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | 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 |+| GetSavedQueryPolicy | [GetSavedQueryPolicyRequest](#bytebase-v1-GetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | 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 |+| SetSavedQueryPolicy | [SetSavedQueryPolicyRequest](#bytebase-v1-SetSavedQueryPolicyRequest) | [SavedQueryPolicy](#bytebase-v1-SavedQueryPolicy) | 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 |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 6824ef4066..25c6f60932 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -2776,6 +2776,10 @@<a href="#bytebase.v1.DeleteSavedQueryRequest"><span class="badge">M</span>DeleteSavedQueryRequest</a></li>+ <li>+ <a href="#bytebase.v1.GetSavedQueryPolicyRequest"><span class="badge">M</span>GetSavedQueryPolicyRequest</a>+ </li>+<li><a href="#bytebase.v1.GetSavedQueryRequest"><span class="badge">M</span>GetSavedQueryRequest</a></li>@@ -2792,6 +2796,14 @@<a href="#bytebase.v1.SavedQuery"><span class="badge">M</span>SavedQuery</a></li>+ <li>+ <a href="#bytebase.v1.SavedQueryBinding"><span class="badge">M</span>SavedQueryBinding</a>+ </li>++ <li>+ <a href="#bytebase.v1.SavedQueryPolicy"><span class="badge">M</span>SavedQueryPolicy</a>+ </li>+<li><a href="#bytebase.v1.SearchSavedQueriesRequest"><span class="badge">M</span>SearchSavedQueriesRequest</a></li>@@ -2808,6 +2820,10 @@<a href="#bytebase.v1.SearchSavedQueryFoldersResponse"><span class="badge">M</span>SearchSavedQueryFoldersResponse</a></li>+ <li>+ <a href="#bytebase.v1.SetSavedQueryPolicyRequest"><span class="badge">M</span>SetSavedQueryPolicyRequest</a>+ </li>+<li><a href="#bytebase.v1.UpdateSavedQueryRequest"><span class="badge">M</span>UpdateSavedQueryRequest</a></li>@@ -2817,6 +2833,10 @@</li>+ <li>+ <a href="#bytebase.v1.SavedQueryBinding.Level"><span class="badge">E</span>SavedQueryBinding.Level</a>+ </li>+<li>@@ -2928,7 +2948,7 @@<li><a href="#bytebase.v1.ExportVCSProviderUsersResponse"><span class="badge">M</span>ExportVCSProviderUsersResponse</a></li>-+<li><a href="#bytebase.v1.GetPaymentInfoRequest"><span class="badge">M</span>GetPaymentInfoRequest</a></li>@@ -31601,38 +31621,35 @@ Permissions required: bb.roles.delete</p></td><td>parent</td><td><a href="#string">string</a></td><td></td>- <td><p>The parent resource whose saved queries are updated.-Format: projects/{project} </p></td>+ <td><p>Format: projects/{project} </p></td></tr><tr><td>filter</td><td><a href="#string">string</a></td><td></td>- <td><p>To filter the batch update target.-The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ <td><p>Select the saved queries to update, in CEL. See+https://github.com/google/cel-spec-Supported filter:-- name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.-- creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.-- starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.-- folder: the saved query folder path, support exact "==" operator. </p></td>+Supported fields:+- name: the saved query name. Supports "==" and "in [...]".+- creator: the creator in "users/{email}" format. Supports "==" and "!=".+- starred: whether the caller starred it. Supports "==".+- folder: the exact folder path. Supports "==". </p></td></tr><tr><td>saved_query</td><td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td><td></td>- <td><p>The fields to apply to every matched saved query. </p></td>+ <td><p>The values to apply to every matched saved query. </p></td></tr><tr><td>update_mask</td><td><a href="#google.protobuf.FieldMask">google.protobuf.FieldMask</a></td><td></td>- <td><p>The list of fields to be updated.-Only support update the following fields for now:-- `folder` </p></td>+ <td><p>Fields to update. Supported: `folder`. </p></td></tr></tbody>@@ -31656,7 +31673,8 @@ Only support update the following fields for now:<td>updated_count</td><td><a href="#int32">int32</a></td><td></td>- <td><p>The number of saved queries updated. </p></td>+ <td><p>How many saved queries were updated, which may be fewer than the filter+matched. </p></td></tr></tbody>@@ -31680,7 +31698,7 @@ Only support update the following fields for now:<td>parent</td><td><a href="#string">string</a></td><td></td>- <td><p>The parent resource where this saved query will be created.+ <td><p>The project to create the saved query in.Format: projects/{project} </p></td></tr>@@ -31712,8 +31730,31 @@ Format: projects/{project} </p></td><td>name</td><td><a href="#string">string</a></td><td></td>- <td><p>The name of the saved query to delete.-Format: projects/{project}/savedQueries/{savedQuery} </p></td>+ <td><p>Format: projects/{project}/savedQueries/{savedQuery} </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.GetSavedQueryPolicyRequest">GetSavedQueryPolicyRequest</h3>+ <p></p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>resource</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Format: projects/{project}/savedQueries/{savedQuery} </p></td></tr></tbody>@@ -31737,8 +31778,7 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td><td>name</td><td><a href="#string">string</a></td><td></td>- <td><p>The name of the saved query to retrieve.-Format: projects/{project}/savedQueries/{savedQuery} </p></td>+ <td><p>Format: projects/{project}/savedQueries/{savedQuery} </p></td></tr></tbody>@@ -31762,45 +31802,39 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td><td>parent</td><td><a href="#string">string</a></td><td></td>- <td><p>The parent resource of the saved queries.-Format: projects/{project}-Use "projects/-" to list saved queries across all projects. </p></td>+ <td><p>The project to list saved queries in, or "projects/-" for every project.+Format: projects/{project} </p></td></tr><tr><td>filter</td><td><a href="#string">string</a></td><td></td>- <td><p>To filter the list result.-The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ <td><p>Filter the result, in CEL. See https://github.com/google/cel-spec-Supported filter:-- creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+Supported fields:+- creator: the creator in "users/{email}" format. Supports "==" and "!=".For example:-creator == "users/{email}"-creator != "users/{email}" </p></td>+creator == "users/[email protected]" </p></td></tr><tr><td>page_size</td><td><a href="#int32">int32</a></td><td></td>- <td><p>The maximum number of saved queries to return. The service may return fewer than-this value.-If unspecified, at most 10 saved queries will be returned.-The maximum value is 1000; values above 1000 will be coerced to 1000. </p></td>+ <td><p>The maximum number of saved queries to return. The service may return+fewer. Defaults to 10; values above 1000 are coerced to 1000. </p></td></tr><tr><td>page_token</td><td><a href="#string">string</a></td><td></td>- <td><p>A page token, received from a previous `ListSavedQueries` call.-Provide this to retrieve the subsequent page.--When paginating, all other parameters provided to `ListSavedQueries` must match-the call that provided the page token. </p></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></tr></tbody>@@ -31824,16 +31858,15 @@ the call that provided the page token. </p></td><td>saved_queries</td><td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td><td>repeated</td>- <td><p>The saved queries from the specified parent. </p></td>+ <td><p> </p></td></tr><tr><td>next_page_token</td><td><a href="#string">string</a></td><td></td>- <td><p>A token to retrieve next page of saved queries.-Pass this value in the page_token field in the subsequent call to-`ListSavedQueries` method to retrieve the next page of saved queries. </p></td>+ <td><p>Pass to the next ListSavedQueries call to fetch the following page. Empty+on the last page. </p></td></tr></tbody>@@ -31857,8 +31890,7 @@ Pass this value in the page_token field in the subsequent call to<td>name</td><td><a href="#string">string</a></td><td></td>- <td><p>The name of the saved query resource, generated by the server.-Canonical parent is project.+ <td><p>Server-generated.Format: projects/{project}/savedQueries/{savedQuery} </p></td></tr>@@ -31866,17 +31898,17 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td><td>project</td><td><a href="#string">string</a></td><td></td>- <td><p>The project resource name.-Format: projects/{project} </p></td>+ <td><p>Format: projects/{project} </p></td></tr><tr><td>database</td><td><a href="#string">string</a></td><td></td>- <td><p>The database resource name.-Format: instances/{instance}/databases/{database}-If the database parent doesn't exist, the database field is empty. </p></td>+ <td><p>The connected database, which must belong to the saved query's own+project. Empty when none is connected, or when the database no longer+exists.+Format: instances/{instance}/databases/{database} </p></td></tr><tr>@@ -31890,8 +31922,7 @@ If the database parent doesn't exist, the database field is empty. </p></td><td>creator</td><td><a href="#string">string</a></td><td></td>- <td><p>The creator of the SavedQuery — the fixed owner; ownership does not-transfer.+ <td><p>The fixed owner. Ownership does not transfer.Format: users/{email} </p></td></tr>@@ -31899,46 +31930,119 @@ Format: users/{email} </p></td><td>create_time</td><td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td><td></td>- <td><p>The create time of the saved query. </p></td>+ <td><p> </p></td></tr><tr><td>update_time</td><td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td><td></td>- <td><p>The last update time of the saved query. </p></td>+ <td><p> </p></td></tr><tr><td>content</td><td><a href="#bytes">bytes</a></td><td></td>- <td><p>The content of the saved query.-By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can-use GetSavedQuery() request to retrieve the full content. </p></td>+ <td><p>The SQL text. SearchSavedQueries truncates it; when it is shorter than+`content_size`, GetSavedQuery returns the whole thing. </p></td></tr><tr><td>content_size</td><td><a href="#int64">int64</a></td><td></td>- <td><p>content_size is the full size of the content, may not match the size of the `content` field. </p></td>+ <td><p>The full size of the content, which may exceed the `content` returned. </p></td></tr><tr><td>starred</td><td><a href="#bool">bool</a></td><td></td>- <td><p>starred indicates whether the saved query is starred by the current authenticated user. </p></td>+ <td><p>Whether the calling user starred it. </p></td></tr><tr><td>folder</td><td><a href="#string">string</a></td><td></td>- <td><p>The folder path this saved query lives in, set by its creator (or an-admin). Empty means unfiled. A saved query lives in exactly one folder;-a folder is a path on saved queries, e.g. "a/b/c". </p></td>+ <td><p>The folder holding this saved query, set by its creator or an admin. A+path like "a/b/c"; empty means unfiled. </p></td>+ </tr>++ </tbody>+ </table>++++++ <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>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>level</td>+ <td><a href="#bytebase.v1.SavedQueryBinding.Level">SavedQueryBinding.Level</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <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 "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.++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>+ </tr>++ </tbody>+ </table>++++++ <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>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>bindings</td>+ <td><a href="#bytebase.v1.SavedQueryBinding">SavedQueryBinding</a></td>+ <td>repeated</td>+ <td><p>At most one binding per level. A member listed under two levels is+rejected rather than resolved to the higher one. </p></td>+ </tr>++ <tr>+ <td>etag</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The etag of the policy as read. SetSavedQueryPolicy requires it and fails+with ABORTED when it no longer matches. </p></td></tr></tbody>@@ -31962,30 +32066,35 @@ a folder is a path on saved queries, e.g. "a/b/c". </p></td><td>parent</td><td><a href="#string">string</a></td><td></td>- <td><p>The parent resource of the saved queries.-Format: projects/{project} </p></td>+ <td><p>Format: projects/{project} </p></td></tr><tr><td>filter</td><td><a href="#string">string</a></td><td></td>- <td><p>To filter the search result.-The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ <td><p>Filter the result, in CEL. See https://github.com/google/cel-spec-Supported filter:-- name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.-- title: the saved query title, support "contains" operator.-- creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.-- starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.-- folder: the saved query folder path, support "==" operator.+Supported fields:+- 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 "==".+- 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.For example:-creator == "users/{email}"-title.contains("saved query title")-creator != "users/{email}"+creator == "users/[email protected]"+shared == truestarred == true-starred == false+title.contains("weekly report")folder == "foo/bar" </p></td></tr>@@ -31993,18 +32102,19 @@ folder == "foo/bar" </p></td><td>page_size</td><td><a href="#int32">int32</a></td><td></td>- <td><p>The maximum number of saved queries to return. The service may return fewer than-this value.-If unspecified, at most 10 saved queries will be returned.-The maximum value is 1000; values above 1000 will be coerced to 1000. </p></td>+ <td><p>The maximum number of saved queries to return. The service may return+fewer. Defaults to 10; values above 1000 are coerced to 1000. </p></td></tr><tr><td>page_token</td><td><a href="#string">string</a></td><td></td>- <td><p>A page token, received from a previous `SearchSavedQueries` call.-Provide this to retrieve the subsequent page. </p></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></tr></tbody>@@ -32028,16 +32138,15 @@ Provide this to retrieve the subsequent page. </p></td><td>saved_queries</td><td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td><td>repeated</td>- <td><p>The saved queries that matched the search criteria. </p></td>+ <td><p> </p></td></tr><tr><td>next_page_token</td><td><a href="#string">string</a></td><td></td>- <td><p>A token to retrieve next page of saved queries.-Pass this value in the page_token field in the subsequent call to-`SearchSavedQueries` method to retrieve the next page of saved queries. </p></td>+ <td><p>Pass to the next SearchSavedQueries call to fetch the following page.+Empty on the last page. </p></td></tr></tbody>@@ -32061,23 +32170,16 @@ Pass this value in the page_token field in the subsequent call to<td>parent</td><td><a href="#string">string</a></td><td></td>- <td><p>The parent resource whose saved query folders are searched.-Format: projects/{project} </p></td>+ <td><p>Format: projects/{project} </p></td></tr><tr><td>filter</td><td><a href="#string">string</a></td><td></td>- <td><p>To filter the folders by the saved queries they hold. Takes the same-fields and syntax as `SearchSavedQueries.filter`, except `title`. A-folder is returned when at least one saved query the caller can read-matches, so the caller-scoping is the same as SearchSavedQueries: your-own saved queries, plus everyone's for the admin backstop.--For example, to split a folder tree into your own and everyone else's:-creator == "users/{email}"-creator != "users/{email}" </p></td>+ <td><p>Filter folders by the saved queries they hold. Takes the same fields and+syntax as SearchSavedQueries.filter, except `title`. A folder is returned+when at least one saved query the caller can read matches. </p></td></tr></tbody>@@ -32101,9 +32203,40 @@ creator != "users/{email}" </p></td><td>folders</td><td><a href="#string">string</a></td><td>repeated</td>- <td><p>The caller's folder paths, including every ancestor prefix, sorted.-A folder is a path on saved queries ("a/b/c"), so empty folders cannot-exist. </p></td>+ <td><p>Folder paths, every ancestor prefix included, sorted. A folder is a path+on saved queries ("a/b/c"), so empty folders cannot exist. </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.SetSavedQueryPolicyRequest">SetSavedQueryPolicyRequest</h3>+ <p></p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>resource</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Format: projects/{project}/savedQueries/{savedQuery} </p></td>+ </tr>++ <tr>+ <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></tr></tbody>@@ -32127,9 +32260,7 @@ exist. </p></td><td>saved_query</td><td><a href="#bytebase.v1.SavedQuery">SavedQuery</a></td><td></td>- <td><p>The saved query to update.--The saved query's `name` field is used to identify the saved query to update.+ <td><p>`saved_query.name` identifies the saved query to update.Format: projects/{project}/savedQueries/{savedQuery} </p></td></tr>@@ -32137,14 +32268,8 @@ Format: projects/{project}/savedQueries/{savedQuery} </p></td><td>update_mask</td><td><a href="#google.protobuf.FieldMask">google.protobuf.FieldMask</a></td><td></td>- <td><p>The list of fields to be updated.-Fields are specified relative to the saved query.-(e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)-Only support update the following fields for now:-- `title`-- `content`-- `database`-- `folder` </p></td>+ <td><p>Fields to update, relative to the saved query (`title`, not+`saved_query.title`). Supported: `title`, `content`, `database`, `folder`. </p></td></tr></tbody>@@ -32168,8 +32293,7 @@ Only support update the following fields for now:<td>name</td><td><a href="#string">string</a></td><td></td>- <td><p>The name of the saved query to star or unstar.-Format: projects/{project}/savedQueries/{savedQuery} </p></td>+ <td><p>Format: projects/{project}/savedQueries/{savedQuery} </p></td></tr><tr>@@ -32188,12 +32312,42 @@ 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>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>LEVEL_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>VIEWER</td>+ <td>1</td>+ <td><p>Open and read the saved query.</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>+ </tr>++ </tbody>+ </table>+<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; `bb.savedQueries.manage` is the</p><p>admin backstop that can reach any saved query in scope. Per-object</p><p>VIEWER/EDITOR grants arrive with the access-model redesign, which brings</p><p>its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages</p><p>them.</p>+ <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><table class="enum-table"><thead><tr><td>Method Name</td><td>Request Type</td><td>Response Type</td><td>Description</td></tr>@@ -32204,8 +32358,8 @@ Format: projects/{project}/savedQueries/{savedQuery} </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>Creates a personal saved query used in SQL Editor. The creator becomes-the fixed owner.+ <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></tr>@@ -32213,82 +32367,118 @@ Permissions required: bb.savedQueries.create on the parent project</p></td><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 by name. Returns NotFound for saved queries the-caller cannot read.-Permissions required: creator, or bb.savedQueries.manage in scope</p></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></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: the grant-independent governance surface. Supports-listing in a project, or across all projects by using `projects/-`, with-whole statements rather than the previews Search returns — e.g. an-offboarding review filtering by creator.-Permissions required: bb.savedQueries.list</p></td>+ <td><p>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/-"</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 for saved queries in a project: the SQL Editor's hot list path,-returning only rows the caller can read, with content previews.-Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project</p></td>+ <td><p>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.+Permissions required: bb.savedQueries.search on the project</p></td></tr><tr><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 of the caller's saved queries in a project.-Folders are a derived view over the `folder` field rather than a-resource collection, so this is a custom method on savedQueries and-shares SearchSavedQueries' caller-scoped semantics — not the-cross-creator reach of ListSavedQueries.-Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project</p></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 == "users/me"`)+from the ones reaching you through a grant (`shared == true`).+Permissions required: bb.savedQueries.search on the project</p></td></tr><tr><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` require write-access; `folder` re-files the saved query and is creator/admin only.-Returns NotFound for saved queries the caller cannot read.-Permissions required: creator, or bb.savedQueries.manage in scope</p></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'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></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. A star is always the-caller's own per-user marker — invisible to others and carrying no-access. The only requirement is that the caller can read the saved-query being starred (which also keeps private saved query names-unprobeable).-Permissions required: read access to the saved query</p></td>+ <td><p>Star or unstar a saved query for the caller. A star is a per-user marker:+invisible to everyone else and granting nothing. Read access is the gate+only so unreadable saved queries stay unprobeable.+Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.manage</p></td></tr><tr><td>BatchUpdateSavedQueries</td><td><a href="#bytebase.v1.BatchUpdateSavedQueriesRequest">BatchUpdateSavedQueriesRequest</a></td><td><a href="#bytebase.v1.BatchUpdateSavedQueriesResponse">BatchUpdateSavedQueriesResponse</a></td>- <td><p>Batch re-file saved queries into a folder. The update mask supports-`folder` only; only rows the caller may re-file are updated (their own,-or any in scope for admins).-Permissions required: creator, or bb.savedQueries.manage in scope</p></td>+ <td><p>Re-file saved queries into a folder in bulk; the update mask supports+`folder` only. An EDITOR binding does not carry re-filing, so matched+saved queries the caller cannot re-file are skipped rather than rejected,+and the response counts what actually changed.+Permissions required: creator, or bb.savedQueries.manage</p></td></tr><tr><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. Only the creator (or an admin) can delete.-Returns NotFound for saved queries the caller cannot read.-Permissions required: creator, or bb.savedQueries.manage in scope</p></td>+ <td><p>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</p></td>+ </tr>++ <tr>+ <td>GetSavedQueryPolicy</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'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>+ </tr>++ <tr>+ <td>SetSavedQueryPolicy</td>+ <td><a href="#bytebase.v1.SetSavedQueryPolicyRequest">SetSavedQueryPolicyRequest</a></td>+ <td><a href="#bytebase.v1.SavedQueryPolicy">SavedQueryPolicy</a></td>+ <td><p>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</p></td></tr></tbody>@@ -32399,6 +32589,26 @@ Permissions required: creator, or bb.savedQueries.manage in scope</p></td></tr>+++ <tr>+ <td>GetSavedQueryPolicy</td>+ <td>GET</td>+ <td>/v1/{resource=projects/*/savedQueries/*}:getPolicy</td>+ <td></td>+ </tr>+++++ <tr>+ <td>SetSavedQueryPolicy</td>+ <td>POST</td>+ <td>/v1/{resource=projects/*/savedQueries/*}:setPolicy</td>+ <td>*</td>+ </tr>++</tbody></table>@@ -33239,27 +33449,27 @@ Required. </p></td><h3 id="bytebase.v1.ExportVCSProviderUsersResponse">ExportVCSProviderUsersResponse</h3><p></p>-+<table class="field-table"><thead><tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr></thead><tbody>-+<tr><td>content</td><td><a href="#bytes">bytes</a></td><td></td><td><p> </p></td></tr>-+</tbody></table>+---++<h3 id="bytebase.v1.GetPaymentInfoRequest">GetPaymentInfoRequest</h3><p></p>diff --git a/proto/store/store/saved_query.proto b/proto/store/store/saved_query.protoindex 926ec7b435..463e3bc473 100644--- a/proto/store/store/saved_query.proto+++ b/proto/store/store/saved_query.proto@@ -13,3 +13,23 @@ message SavedQueryPayload {// is deleted or transferred, degrading to "no database" in the UI.string database = 1;}++// One grant on a saved query. Stored in saved_query.bindings, which holds a+// protojson array of these messages at the jsonb root rather than a wrapper+// object, so the `@>` containment probes the access queries run hit the GIN+// index directly.+message SavedQueryBinding {+ enum Level {+ LEVEL_UNSPECIFIED = 0;+ VIEWER = 1;+ EDITOR = 2;+ }++ Level level = 1;++ // Principals in the same resource-name form the IAM policy payloads use:+ // "users/{email}" and "groups/{email}". The v1 API takes the binding form+ // ("user:", "group:") and converts once on write, as the project policy+ // does. Groups are named by reference and never expanded.+ repeated string members = 2;+}diff --git a/proto/v1/v1/saved_query_service.proto b/proto/v1/v1/saved_query_service.protoindex c2e9b3665f..a9501163c7 100644--- a/proto/v1/v1/saved_query_service.proto+++ b/proto/v1/v1/saved_query_service.proto@@ -16,14 +16,17 @@ option go_package = "github.com/bytebase/bytebase/backend/generated-go/v1";// SavedQueryService manages saved queries for SQL Editor query development.//-// A saved query is private to its creator; `bb.savedQueries.manage` is the-// admin backstop that can reach any saved query in scope. Per-object-// VIEWER/EDITOR grants arrive with the access-model redesign, which brings-// its own policy shapes and the GetIamPolicy/SetIamPolicy pair that manages-// them.+// 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.service SavedQueryService {- // Creates a personal saved query used in SQL Editor. The creator becomes- // the fixed owner.+ // Create a saved query. The creator becomes its fixed owner, and the saved+ // query starts private.// Permissions required: bb.savedQueries.create on the parent projectrpc CreateSavedQuery(CreateSavedQueryRequest) returns (SavedQuery) {option (google.api.http) = {@@ -36,20 +39,21 @@ service SavedQueryService {option (bytebase.v1.audit) = true;}- // Get a saved query by name. Returns NotFound for saved queries the- // caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.managerpc 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: the grant-independent governance surface. Supports- // listing in a project, or across all projects by using `projects/-`, with- // whole statements rather than the previews Search returns — e.g. an- // offboarding review filtering by creator.- // Permissions required: bb.savedQueries.list+ // 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/-"rpc ListSavedQueries(ListSavedQueriesRequest) returns (ListSavedQueriesResponse) {option (google.api.http) = {get: "/v1/{parent=projects/*}/savedQueries"};option (google.api.method_signature) = "parent";@@ -57,9 +61,15 @@ service SavedQueryService {option (bytebase.v1.auth_method) = IAM;}- // Search for saved queries in a project: the SQL Editor's hot list path,- // returning only rows the caller can read, with content previews.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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.+ // Permissions required: bb.savedQueries.search on the projectrpc SearchSavedQueries(SearchSavedQueriesRequest) returns (SearchSavedQueriesResponse) {option (google.api.http) = {post: "/v1/{parent=projects/*}/savedQueries:search"@@ -69,12 +79,17 @@ service SavedQueryService {option (bytebase.v1.auth_method) = CUSTOM;}- // Search the folder paths of the caller's saved queries in a project.- // Folders are a derived view over the `folder` field rather than a- // resource collection, so this is a custom method on savedQueries and- // shares SearchSavedQueries' caller-scoped semantics — not the- // cross-creator reach of ListSavedQueries.- // Permissions required: bb.savedQueries.search or bb.savedQueries.manage on the project+ // 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`).+ // Permissions required: bb.savedQueries.search on the projectrpc SearchSavedQueryFolders(SearchSavedQueryFoldersRequest) returns (SearchSavedQueryFoldersResponse) {option (google.api.http) = {post: "/v1/{parent=projects/*}/savedQueries:searchFolders"@@ -84,10 +99,12 @@ service SavedQueryService {option (bytebase.v1.auth_method) = CUSTOM;}- // Update a saved query. `title`, `content`, and `database` require write- // access; `folder` re-files the saved query and is creator/admin only.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.managerpc UpdateSavedQuery(UpdateSavedQueryRequest) returns (SavedQuery) {option (google.api.http) = {patch: "/v1/{saved_query.name=projects/*/savedQueries/*}"@@ -98,12 +115,10 @@ service SavedQueryService {option (bytebase.v1.audit) = true;}- // Star or unstar a saved query for the caller. A star is always the- // caller's own per-user marker — invisible to others and carrying no- // access. The only requirement is that the caller can read the saved- // query being starred (which also keeps private saved query names- // unprobeable).- // Permissions required: read access to the saved query+ // Star or unstar a saved query for the caller. A star is a per-user marker:+ // invisible to everyone else and granting nothing. Read access is the gate+ // only so unreadable saved queries stay unprobeable.+ // Permissions required: creator, a VIEWER or EDITOR binding, or bb.savedQueries.managerpc UpdateSavedQueryStar(UpdateSavedQueryStarRequest) returns (SavedQuery) {option (google.api.http) = {post: "/v1/{name=projects/*/savedQueries/*}:updateStar"@@ -113,10 +128,11 @@ service SavedQueryService {option (bytebase.v1.auth_method) = CUSTOM;}- // Batch re-file saved queries into a folder. The update mask supports- // `folder` only; only rows the caller may re-file are updated (their own,- // or any in scope for admins).- // Permissions required: creator, or bb.savedQueries.manage in scope+ // Re-file saved queries into a folder in bulk; the update mask supports+ // `folder` only. An EDITOR binding does not carry re-filing, so matched+ // saved queries the caller cannot re-file are skipped rather than rejected,+ // and the response counts what actually changed.+ // Permissions required: creator, or bb.savedQueries.managerpc BatchUpdateSavedQueries(BatchUpdateSavedQueriesRequest) returns (BatchUpdateSavedQueriesResponse) {option (google.api.http) = {post: "/v1/{parent=projects/*}/savedQueries:batchUpdate"@@ -127,19 +143,46 @@ service SavedQueryService {option (bytebase.v1.audit) = true;}- // Delete a saved query. Only the creator (or an admin) can delete.- // Returns NotFound for saved queries the caller cannot read.- // Permissions required: creator, or bb.savedQueries.manage in scope+ // 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.managerpc DeleteSavedQuery(DeleteSavedQueryRequest) returns (google.protobuf.Empty) {option (google.api.http) = {delete: "/v1/{name=projects/*/savedQueries/*}"};option (google.api.method_signature) = "name";option (bytebase.v1.auth_method) = CUSTOM;option (bytebase.v1.audit) = true;}++ // 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+ rpc GetSavedQueryPolicy(GetSavedQueryPolicyRequest) returns (SavedQueryPolicy) {+ option (google.api.http) = {get: "/v1/{resource=projects/*/savedQueries/*}:getPolicy"};+ option (google.api.method_signature) = "resource";+ option (bytebase.v1.auth_method) = CUSTOM;+ }++ // 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+ rpc SetSavedQueryPolicy(SetSavedQueryPolicyRequest) returns (SavedQueryPolicy) {+ option (google.api.http) = {+ post: "/v1/{resource=projects/*/savedQueries/*}:setPolicy"+ body: "*"+ };+ option (google.api.method_signature) = "resource,policy";+ option (bytebase.v1.auth_method) = CUSTOM;+ option (bytebase.v1.audit) = true;+ }}message CreateSavedQueryRequest {- // The parent resource where this saved query will be created.+ // The project to create the saved query in.// Format: projects/{project}string parent = 1 [(google.api.field_behavior) = REQUIRED,@@ -151,102 +194,76 @@ message CreateSavedQueryRequest {}message GetSavedQueryRequest {- // The name of the saved query to retrieve.// Format: projects/{project}/savedQueries/{savedQuery}string name = 1 [(google.api.field_behavior) = REQUIRED];}message ListSavedQueriesRequest {- // The parent resource of the saved queries.+ // The project to list saved queries in, or "projects/-" for every project.// Format: projects/{project}- // Use "projects/-" to list saved queries across all projects.string parent = 1 [(google.api.field_behavior) = REQUIRED,(google.api.resource_reference) = {type: "bytebase.com/Project"}];- // To filter the list result.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Filter the result, in CEL. See https://github.com/google/cel-spec//- // Supported filter:- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.+ // Supported fields:+ // - creator: the creator in "users/{email}" format. Supports "==" and "!=".//// For example:- // creator == "users/{email}"- // creator != "users/{email}"+ // creator == "users/[email protected]"string filter = 2;- // The maximum number of saved queries to return. The service may return fewer than- // this value.- // If unspecified, at most 10 saved queries will be returned.- // The maximum value is 1000; values above 1000 will be coerced to 1000.+ // The maximum number of saved queries to return. The service may return+ // fewer. Defaults to 10; values above 1000 are coerced to 1000.int32 page_size = 3;- // A page token, received from a previous `ListSavedQueries` call.- // Provide this to retrieve the subsequent page.- //- // When paginating, all other parameters provided to `ListSavedQueries` must match- // the call that provided the page token.+ // 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.string page_token = 4;}message ListSavedQueriesResponse {- // The saved queries from the specified parent.repeated SavedQuery saved_queries = 1;- // A token to retrieve next page of saved queries.- // Pass this value in the page_token field in the subsequent call to- // `ListSavedQueries` method to retrieve the next page of saved queries.+ // Pass to the next ListSavedQueries call to fetch the following page. Empty+ // on the last page.string next_page_token = 2;}message SearchSavedQueryFoldersRequest {- // The parent resource whose saved query folders are searched.// Format: projects/{project}string parent = 1 [(google.api.field_behavior) = REQUIRED,(google.api.resource_reference) = {type: "bytebase.com/Project"}];- // To filter the folders by the saved queries they hold. Takes the same- // fields and syntax as `SearchSavedQueries.filter`, except `title`. A- // folder is returned when at least one saved query the caller can read- // matches, so the caller-scoping is the same as SearchSavedQueries: your- // own saved queries, plus everyone's for the admin backstop.- //- // For example, to split a folder tree into your own and everyone else's:- // creator == "users/{email}"- // creator != "users/{email}"+ // Filter folders by the saved queries they hold. Takes the same fields and+ // syntax as SearchSavedQueries.filter, except `title`. A folder is returned+ // when at least one saved query the caller can read matches.string filter = 2;}message SearchSavedQueryFoldersResponse {- // The caller's folder paths, including every ancestor prefix, sorted.- // A folder is a path on saved queries ("a/b/c"), so empty folders cannot- // exist.+ // Folder paths, every ancestor prefix included, sorted. A folder is a path+ // on saved queries ("a/b/c"), so empty folders cannot exist.repeated string folders = 1;}message UpdateSavedQueryRequest {- // The saved query to update.- //- // The saved query's `name` field is used to identify the saved query to update.+ // `saved_query.name` identifies the saved query to update.// Format: projects/{project}/savedQueries/{savedQuery}SavedQuery saved_query = 1 [(google.api.field_behavior) = REQUIRED];- // The list of fields to be updated.- // Fields are specified relative to the saved query.- // (e.g., `title`, `content`; *not* `saved_query.title` or `saved_query.content`)- // Only support update the following fields for now:- // - `title`- // - `content`- // - `database`- // - `folder`+ // Fields to update, relative to the saved query (`title`, not+ // `saved_query.title`). Supported: `title`, `content`, `database`, `folder`.google.protobuf.FieldMask update_mask = 2;}message UpdateSavedQueryStarRequest {- // The name of the saved query to star or unstar.// Format: projects/{project}/savedQueries/{savedQuery}string name = 1 [(google.api.field_behavior) = REQUIRED];@@ -255,39 +272,105 @@ message UpdateSavedQueryStarRequest {}message BatchUpdateSavedQueriesRequest {- // The parent resource whose saved queries are updated.// Format: projects/{project}string parent = 1 [(google.api.field_behavior) = REQUIRED,(google.api.resource_reference) = {type: "bytebase.com/Project"}];- // To filter the batch update target.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Select the saved queries to update, in CEL. See+ // https://github.com/google/cel-spec//- // Supported filter:- // - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- // - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- // - folder: the saved query folder path, support exact "==" operator.+ // Supported fields:+ // - name: the saved query name. Supports "==" and "in [...]".+ // - creator: the creator in "users/{email}" format. Supports "==" and "!=".+ // - starred: whether the caller starred it. Supports "==".+ // - folder: the exact folder path. Supports "==".string filter = 2;- // The fields to apply to every matched saved query.+ // The values to apply to every matched saved query.SavedQuery saved_query = 3 [(google.api.field_behavior) = REQUIRED];- // The list of fields to be updated.- // Only support update the following fields for now:- // - `folder`+ // Fields to update. Supported: `folder`.google.protobuf.FieldMask update_mask = 4 [(google.api.field_behavior) = REQUIRED];}message BatchUpdateSavedQueriesResponse {- // The number of saved queries updated.+ // How many saved queries were updated, which may be fewer than the filter+ // matched.int32 updated_count = 1;}+message GetSavedQueryPolicyRequest {+ // Format: projects/{project}/savedQueries/{savedQuery}+ string resource = 1 [+ (google.api.field_behavior) = REQUIRED,+ (google.api.resource_reference) = {type: "bytebase.com/SavedQuery"}+ ];+}++message SetSavedQueryPolicyRequest {+ // Format: projects/{project}/savedQueries/{savedQuery}+ string resource = 1 [+ (google.api.field_behavior) = REQUIRED,+ (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.+ 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.+message SavedQueryPolicy {+ // At most one binding per level. A member listed under two levels is+ // rejected rather than resolved to the higher one.+ repeated SavedQueryBinding bindings = 1;++ // The etag of the policy as read. SetSavedQueryPolicy requires it and fails+ // with ABORTED when it no longer matches.+ 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.+message SavedQueryBinding {+ // Nested because bytebase.v1 already defines a package-scoped EDITOR+ // (DatabaseChangeMode), and enum values live in the enclosing scope.+ enum Level {+ LEVEL_UNSPECIFIED = 0;++ // Open and read the saved query.+ VIEWER = 1;++ // VIEWER, plus write the title, content, and connected database. Sharing+ // and deletion stay with the creator and admins.+ 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.+ //+ // 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.+ repeated string members = 2 [+ (google.api.field_behavior) = REQUIRED,+ (buf.validate.field).repeated.min_items = 1+ ];+}+message DeleteSavedQueryRequest {- // The name of the saved query to delete.// Format: projects/{project}/savedQueries/{savedQuery}string name = 1 [(google.api.field_behavior) = REQUIRED,@@ -296,50 +379,54 @@ message DeleteSavedQueryRequest {}message SearchSavedQueriesRequest {- // The parent resource of the saved queries.// Format: projects/{project}string parent = 1 [(google.api.field_behavior) = REQUIRED,(google.api.resource_reference) = {type: "bytebase.com/Project"}];- // To filter the search result.- // The syntax and semantics of CEL are documented at https://github.com/google/cel-spec+ // Filter the result, in CEL. See https://github.com/google/cel-spec+ //+ // Supported fields:+ // - 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 "==".+ // - starred: whether the caller starred it. Supports "==".+ // - folder: the exact folder path. Supports "==".//- // Supported filter:- // - name: the saved query name in "projects/{project}/savedQueries/{savedQuery}" format, support "==" and "in [xx]" operator.- // - title: the saved query title, support "contains" operator.- // - creator: the saved query creator in "users/{email}" format, support "==" and "!=" operator.- // - starred: should be "true" or "false", filter starred/unstarred saved queries, support "==" operator.- // - folder: the saved query folder path, support "==" operator.+ // 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.//// For example:- // creator == "users/{email}"- // title.contains("saved query title")- // creator != "users/{email}"+ // creator == "users/[email protected]"+ // shared == true// starred == true- // starred == false+ // title.contains("weekly report")// folder == "foo/bar"string filter = 2;- // The maximum number of saved queries to return. The service may return fewer than- // this value.- // If unspecified, at most 10 saved queries will be returned.- // The maximum value is 1000; values above 1000 will be coerced to 1000.+ // The maximum number of saved queries to return. The service may return+ // fewer. Defaults to 10; values above 1000 are coerced to 1000.int32 page_size = 3;- // A page token, received from a previous `SearchSavedQueries` call.- // Provide this to retrieve the subsequent page.+ // 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.string page_token = 4;}message SearchSavedQueriesResponse {- // The saved queries that matched the search criteria.repeated SavedQuery saved_queries = 1;- // A token to retrieve next page of saved queries.- // Pass this value in the page_token field in the subsequent call to- // `SearchSavedQueries` method to retrieve the next page of saved queries.+ // Pass to the next SearchSavedQueries call to fetch the following page.+ // Empty on the last page.string next_page_token = 2;}@@ -349,21 +436,20 @@ message SavedQuery {pattern: "projects/{project}/savedQueries/{saved_query}"};- // The name of the saved query resource, generated by the server.- // Canonical parent is project.+ // Server-generated.// Format: projects/{project}/savedQueries/{savedQuery}string name = 1 [(google.api.field_behavior) = REQUIRED,(google.api.field_behavior) = IMMUTABLE];- // The project resource name.// Format: projects/{project}string project = 2 [(google.api.field_behavior) = OUTPUT_ONLY];- // The database resource name.+ // The connected database, which must belong to the saved query's own+ // project. Empty when none is connected, or when the database no longer+ // exists.// Format: instances/{instance}/databases/{database}- // If the database parent doesn't exist, the database field is empty.string database = 3;// The title of the saved query.@@ -372,35 +458,29 @@ message SavedQuery {(buf.validate.field).string.max_len = 200];- // The creator of the SavedQuery — the fixed owner; ownership does not- // transfer.+ // The fixed owner. Ownership does not transfer.// Format: users/{email}string creator = 5 [(google.api.field_behavior) = OUTPUT_ONLY];- // The create time of the saved query.google.protobuf.Timestamp create_time = 6 [(google.api.field_behavior) = OUTPUT_ONLY];- // The last update time of the saved query.google.protobuf.Timestamp update_time = 7 [(google.api.field_behavior) = OUTPUT_ONLY];- // The content of the saved query.- // By default, it will be cut off in SearchSavedQueries() method. If it doesn't match the `content_size`, you can- // use GetSavedQuery() request to retrieve the full content.+ // The SQL text. SearchSavedQueries truncates it; when it is shorter than+ // `content_size`, GetSavedQuery returns the whole thing.bytes content = 8 [(google.api.field_behavior) = REQUIRED];- // content_size is the full size of the content, may not match the size of the `content` field.+ // The full size of the content, which may exceed the `content` returned.int64 content_size = 9 [(google.api.field_behavior) = OUTPUT_ONLY];- // The removed visibility field (superseded by per-object grants) and the- // removed per-user folder segments (superseded by `folder`).+ // Removed: `visibility`, superseded by bindings; `folders`, superseded by+ // the `folder` path.reserved 10, 12;- reserved "visibility", "folders";- // starred indicates whether the saved query is starred by the current authenticated user.+ // Whether the calling user starred it.bool starred = 11 [(google.api.field_behavior) = OUTPUT_ONLY];- // The folder path this saved query lives in, set by its creator (or an- // admin). Empty means unfiled. A saved query lives in exactly one folder;- // a folder is a path on saved queries, e.g. "a/b/c".+ // The folder holding this saved query, set by its creator or an admin. A+ // path like "a/b/c"; empty means unfiled.string folder = 13 [(buf.validate.field).string.max_len = 256];}