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(frontend): access grant (#19338)
ecmadaoc770a44261ec
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 5f96975c09..30d07a29a8 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -11903,6 +11903,7 @@ components:- expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- query: the access query, support "==" and ".contains(xx)" operator+ - target: the target database fullname, support "==" operator.Examples:- creator == "users/[email protected]"@@ -11911,6 +11912,17 @@ components:- creator == "users/[email protected]" && status == "ACTIVE"- issue == "projects/x/issues/123"- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ - target == "instances/sample/databases/employee"+ orderBy:+ type: string+ title: order_by+ description: |-+ The order by of access grants.+ Support creator, expire_time, create_time. The default sorting order is ascending.+ For example:+ - order_by = "creator"+ - order_by = "expire_time desc"+ - order_by = "expire_time asc, create_time desc"title: ListAccessGrantsRequestadditionalProperties: falsebytebase.v1.ListAccessGrantsResponse:@@ -15887,13 +15899,11 @@ components:filter:type: stringtitle: filter- description: |-- Filter expression using AIP-160 syntax.- Supported fields: name, status, expire_time, create_time- Examples:- - 'name = "projects/x/accessGrants/uuid"'- - 'status = "ACTIVE"'- - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'+ description: Check the filter field in the ListAccessGrantsRequest message.+ orderBy:+ type: string+ title: order_by+ description: Check the order_by field in the ListAccessGrantsRequest message.title: SearchMyAccessGrantsRequestadditionalProperties: falsebytebase.v1.SearchMyAccessGrantsResponse:diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.goindex 1fcb56de96..0aaeb8605e 100644--- a/backend/api/v1/access_grant_service.go+++ b/backend/api/v1/access_grant_service.go@@ -93,6 +93,12 @@ func (s *AccessGrantService) ListAccessGrants(ctx context.Context, request *connfind.FilterQ = filterQ}+ orderByKeys, err := store.GetAccessGrantOrders(req.OrderBy)+ if err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)+ }+ find.OrderByKeys = orderByKeys+grants, err := s.store.ListAccessGrants(ctx, find)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list access grants"))@@ -356,6 +362,12 @@ func (s *AccessGrantService) SearchMyAccessGrants(ctx context.Context, request *find.FilterQ = filterQ}+ orderByKeys, err := store.GetAccessGrantOrders(req.OrderBy)+ if err != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, err)+ }+ find.OrderByKeys = orderByKeys+grants, err := s.store.ListAccessGrants(ctx, find)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to search access grants"))diff --git a/backend/generated-go/v1/access_grant_service.pb.go b/backend/generated-go/v1/access_grant_service.pb.goindex 0441b7cd8b..ce444879de 100644--- a/backend/generated-go/v1/access_grant_service.pb.go+++ b/backend/generated-go/v1/access_grant_service.pb.go@@ -330,6 +330,7 @@ type ListAccessGrantsRequest struct {// - expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.// - create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.// - query: the access query, support "==" and ".contains(xx)" operator+ // - target: the target database fullname, support "==" operator.//// Examples:// - creator == "users/[email protected]"@@ -338,7 +339,15 @@ type ListAccessGrantsRequest struct {// - creator == "users/[email protected]" && status == "ACTIVE"// - issue == "projects/x/issues/123"// - status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"- Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`+ // - target == "instances/sample/databases/employee"+ Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`+ // The order by of access grants.+ // Support creator, expire_time, create_time. The default sorting order is ascending.+ // For example:+ // - order_by = "creator"+ // - order_by = "expire_time desc"+ // - order_by = "expire_time asc, create_time desc"+ OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -401,6 +410,13 @@ func (x *ListAccessGrantsRequest) GetFilter() string {return ""}+func (x *ListAccessGrantsRequest) GetOrderBy() string {+ if x != nil {+ return x.OrderBy+ }+ return ""+}+type ListAccessGrantsResponse struct {state protoimpl.MessageState `protogen:"open.v1"`// The access grants from the specified request.@@ -612,13 +628,10 @@ type SearchMyAccessGrantsRequest struct {PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"`// A page token from a previous SearchMyAccessGrants call.PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`- // Filter expression using AIP-160 syntax.- // Supported fields: name, status, expire_time, create_time- // Examples:- // - 'name = "projects/x/accessGrants/uuid"'- // - 'status = "ACTIVE"'- // - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'- Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`+ // Check the filter field in the ListAccessGrantsRequest message.+ Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`+ // Check the order_by field in the ListAccessGrantsRequest message.+ OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -681,6 +694,13 @@ func (x *SearchMyAccessGrantsRequest) GetFilter() string {return ""}+func (x *SearchMyAccessGrantsRequest) GetOrderBy() string {+ if x != nil {+ return x.OrderBy+ }+ return ""+}+type SearchMyAccessGrantsResponse struct {state protoimpl.MessageState `protogen:"open.v1"`// The access grants from the specified request.@@ -769,14 +789,15 @@ const file_v1_access_grant_service_proto_rawDesc = "" +"expiration\"M\n" +"\x15GetAccessGrantRequest\x124\n" +"\x04name\x18\x01 \x01(\tB \xe0A\x02\xfaA\x1a\n" +- "\x18bytebase.com/AccessGrantR\x04name\"\xa3\x01\n" ++ "\x18bytebase.com/AccessGrantR\x04name\"\xbe\x01\n" +"\x17ListAccessGrantsRequest\x124\n" +"\x06parent\x18\x01 \x01(\tB\x1c\xe0A\x02\xfaA\x16\n" +"\x14bytebase.com/ProjectR\x06parent\x12\x1b\n" +"\tpage_size\x18\x02 \x01(\x05R\bpageSize\x12\x1d\n" +"\n" +"page_token\x18\x03 \x01(\tR\tpageToken\x12\x16\n" +- "\x06filter\x18\x04 \x01(\tR\x06filter\"\x81\x01\n" ++ "\x06filter\x18\x04 \x01(\tR\x06filter\x12\x19\n" ++ "\border_by\x18\x05 \x01(\tR\aorderBy\"\x81\x01\n" +"\x18ListAccessGrantsResponse\x12=\n" +"\raccess_grants\x18\x01 \x03(\v2\x18.bytebase.v1.AccessGrantR\faccessGrants\x12&\n" +"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x92\x01\n" +@@ -789,14 +810,15 @@ const file_v1_access_grant_service_proto_rawDesc = "" +"\x18bytebase.com/AccessGrantR\x04name\"P\n" +"\x18RevokeAccessGrantRequest\x124\n" +"\x04name\x18\x01 \x01(\tB \xe0A\x02\xfaA\x1a\n" +- "\x18bytebase.com/AccessGrantR\x04name\"\xa7\x01\n" ++ "\x18bytebase.com/AccessGrantR\x04name\"\xc2\x01\n" +"\x1bSearchMyAccessGrantsRequest\x124\n" +"\x06parent\x18\x01 \x01(\tB\x1c\xe0A\x02\xfaA\x16\n" +"\x14bytebase.com/ProjectR\x06parent\x12\x1b\n" +"\tpage_size\x18\x02 \x01(\x05R\bpageSize\x12\x1d\n" +"\n" +"page_token\x18\x03 \x01(\tR\tpageToken\x12\x16\n" +- "\x06filter\x18\x04 \x01(\tR\x06filter\"\x85\x01\n" ++ "\x06filter\x18\x04 \x01(\tR\x06filter\x12\x19\n" ++ "\border_by\x18\x05 \x01(\tR\aorderBy\"\x85\x01\n" +"\x1cSearchMyAccessGrantsResponse\x12=\n" +"\raccess_grants\x18\x01 \x03(\v2\x18.bytebase.v1.AccessGrantR\faccessGrants\x12&\n" +"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken2\xf0\b\n" +diff --git a/backend/generated-go/v1/access_grant_service_equal.pb.go b/backend/generated-go/v1/access_grant_service_equal.pb.goindex eb15c162db..35cf69eda0 100644--- a/backend/generated-go/v1/access_grant_service_equal.pb.go+++ b/backend/generated-go/v1/access_grant_service_equal.pb.go@@ -86,6 +86,9 @@ func (x *ListAccessGrantsRequest) Equal(y *ListAccessGrantsRequest) bool {if x.Filter != y.Filter {return false}+ if x.OrderBy != y.OrderBy {+ return false+ }return true}@@ -171,6 +174,9 @@ func (x *SearchMyAccessGrantsRequest) Equal(y *SearchMyAccessGrantsRequest) boolif x.Filter != y.Filter {return false}+ if x.OrderBy != y.OrderBy {+ return false+ }return true}diff --git a/backend/store/access_grant.go b/backend/store/access_grant.goindex f785340e11..3ddbf09b7c 100644--- a/backend/store/access_grant.go+++ b/backend/store/access_grant.go@@ -2,6 +2,7 @@ package storeimport ("context"+ "fmt""strings""time"@@ -42,7 +43,8 @@ type FindAccessGrantMessage struct {Limit *intOffset *int- FilterQ *qb.Query+ FilterQ *qb.Query+ OrderByKeys []*OrderByKey}// UpdateAccessGrantMessage is the message for updating an access grant.@@ -128,7 +130,15 @@ func (s *Store) ListAccessGrants(ctx context.Context, find *FindAccessGrantMessaq.And("creator = ?", *v)}- q.Space("ORDER BY created_at DESC")+ if len(find.OrderByKeys) > 0 {+ orderBy := []string{}+ for _, v := range find.OrderByKeys {+ orderBy = append(orderBy, fmt.Sprintf("%s %s", v.Key, v.SortOrder.String()))+ }+ q.Space(fmt.Sprintf("ORDER BY %s", strings.Join(orderBy, ", ")))+ } else {+ q.Space("ORDER BY created_at DESC")+ }if v := find.Limit; v != nil {q.Space("LIMIT ?", *v)}@@ -242,6 +252,38 @@ func (s *Store) UpdateAccessGrant(ctx context.Context, id string, update *Updatereturn &grant, nil}+// GetAccessGrantOrders parses an order_by string into OrderByKey slice for access grants.+func GetAccessGrantOrders(orderBy string) ([]*OrderByKey, error) {+ keys, err := parseOrderBy(orderBy)+ if err != nil {+ return nil, err+ }++ orderByKeys := []*OrderByKey{}+ for _, orderByKey := range keys {+ switch orderByKey.Key {+ case "creator":+ orderByKeys = append(orderByKeys, &OrderByKey{+ Key: "access_grant.creator",+ SortOrder: orderByKey.SortOrder,+ })+ case "expire_time":+ orderByKeys = append(orderByKeys, &OrderByKey{+ Key: "access_grant.expire_time",+ SortOrder: orderByKey.SortOrder,+ })+ case "create_time":+ orderByKeys = append(orderByKeys, &OrderByKey{+ Key: "access_grant.created_at",+ SortOrder: orderByKey.SortOrder,+ })+ default:+ return nil, errors.Errorf(`invalid order key "%v"`, orderByKey.Key)+ }+ }+ return orderByKeys, nil+}+// GetListAccessGrantFilter parses a CEL filter expression into a query builder query for listing access grants.func GetListAccessGrantFilter(filter string) (*qb.Query, error) {if filter == "" {@@ -319,6 +361,12 @@ func GetListAccessGrantFilter(filter string) (*qb.Query, error) {return nil, errors.Wrapf(err, "invalid issue name %q", issueStr)}return qb.Q().Space("(access_grant.payload->>'issueId')::bigint = ?", issueUID), nil+ case "target":+ targetStr, ok := value.(string)+ if !ok {+ return nil, errors.Errorf("target value must be a string")+ }+ return qb.Q().Space("access_grant.payload->'targets' @> jsonb_build_array(to_jsonb(?::text))", targetStr), nildefault:return nil, errors.Errorf("unsupported variable %q", variable)}@@ -340,7 +388,9 @@ func GetListAccessGrantFilter(filter string) (*qb.Query, error) {if !ok {return nil, errors.Errorf("contains argument must be a string")}- return qb.Q().Space("access_grant.payload->>'query' ILIKE ?", "%"+value+"%"), nil+ // Normalize whitespace on both sides so "SELECT *" matches "SELECT\n *".+ normalizedValue := strings.Join(strings.Fields(value), " ")+ return qb.Q().Space("regexp_replace(access_grant.payload->>'query', '\\s+', ' ', 'g') ILIKE ?", "%"+normalizedValue+"%"), nilcase celoperators.In:variable, value := getVariableAndValueFromExpr(expr)if variable != "status" {diff --git a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue b/frontend/src/components/AdvancedSearch/AdvancedSearch.vueindex 225fd8333b..11a95de3f2 100644--- a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue+++ b/frontend/src/components/AdvancedSearch/AdvancedSearch.vue@@ -2,6 +2,7 @@<div ref="containerRef" class="w-full relative"><NInputref="inputRef"+ v-bind="$attrs"v-model:value="inputText":placeholder="placeholder ?? $t('issue.advanced-search.self')"style="--n-padding-left: 8px; --n-padding-right: 4px"@@ -26,7 +27,7 @@<ScopeTags:params="params":scope-options="scopeOptions"- :focused-tag-id="focusedTagId"+ :focused-tag-index="focusedTagIndex"@select-scope="selectScopeFromTag"@remove-scope="removeScope"/>@@ -90,7 +91,7 @@ import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";import { useRouter } from "vue-router";import { useCurrentUserV1 } from "@/store";import { DEBOUNCE_SEARCH_DELAY } from "@/types";-import type { SearchParams, SearchScopeId } from "@/utils";+import type { SearchParams, SearchScope, SearchScopeId } from "@/utils";import {buildSearchParamsBySearchText,buildSearchTextBySearchParams,@@ -185,7 +186,7 @@ const tagsContainerRef = ref<HTMLElement>();const inputText = ref(props.params.query);const inputRef = ref<InputInst>();const menuIndex = ref(0);-const focusedTagId = ref<SearchScopeId>();+const focusedTagIndex = ref<number>();const editableScopes = computed(() => {return props.params.scopes.filter((s) => !s.readonly);@@ -348,7 +349,7 @@ const clearable = computed(() => {const hideMenu = () => {nextTick(() => {state.menuView = undefined;- focusedTagId.value = undefined;+ focusedTagIndex.value = undefined;});};@@ -362,15 +363,11 @@ const moveMenuIndex = (delta: -1 | 1) => {menuIndex.value = target;};-const removeScope = (id: SearchScopeId) => {- const updated = upsertScope({- params: props.params,- scopes: {- id,- value: "",- },+const removeScope = (index: number) => {+ emit("update:params", {+ ...props.params,+ scopes: props.params.scopes.filter((_, i) => i !== index),});- emit("update:params", updated);};const selectScope = (@@ -426,16 +423,16 @@ const selectValue = (value: string) => {hideMenu();};-const selectScopeFromTag = (id: SearchScopeId) => {- if (state.scopeOptions.find((opt) => opt.id === id)) {+const selectScopeFromTag = (scope: SearchScope) => {+ if (state.scopeOptions.some((opt) => opt.id === scope.id)) {// For AdvancedSearch supported scopes- selectScope(id);+ selectScope(scope.id);return;}// Unsupported scope for AdvancedSearch// emit an event and wish the parent UI can handle this- emit("select-unsupported-scope", id);+ emit("select-unsupported-scope", scope.id);hideMenu();};@@ -495,28 +492,25 @@ const handleKeyDown = (e: KeyboardEvent) => {if (e.defaultPrevented) return;const { key } = e;if (key === "Backspace" && inputText.value === "") {+ e.stopPropagation();+ e.preventDefault();// Pressing "backspace" when the input box is empty- if (focusedTagId.value) {- e.stopPropagation();- e.preventDefault();+ if (focusedTagIndex.value !== undefined) {// Delete the focusedTag if it exists- const id = focusedTagId.value;- focusedTagId.value = undefined;- removeScope(id);- return;+ const index = focusedTagIndex.value;+ focusedTagIndex.value = undefined;+ removeScope(index);} else {- e.stopPropagation();- e.preventDefault();// Otherwise mark the last editable scope as focused.- const id = last(editableScopes.value)?.id;- if (id) {- focusedTagId.value = id;- scrollScopeTagIntoViewIfNeeded(id);+ const scope = last(editableScopes.value);+ if (scope) {+ focusedTagIndex.value = editableScopes.value.length - 1;+ scrollScopeTagIntoViewIfNeeded(scope.id);}- return;}+ return;}- focusedTagId.value = undefined;+ focusedTagIndex.value = undefined;if (key === "ArrowUp") {moveMenuIndex(-1);@@ -541,7 +535,7 @@ const handleKeyUp = (e: KeyboardEvent) => {}if (key === "Backspace" && inputText.value === "") {// backspace key might be processed by KeyDown- if (focusedTagId.value) {+ if (focusedTagIndex.value !== undefined) {return;}}@@ -654,7 +648,7 @@ onMounted(() => {watch(() => state.menuView,() => {- focusedTagId.value = undefined;+ focusedTagIndex.value = undefined;menuIndex.value = 0;if (state.menuView === "value" && state.currentScope) {const value = getValueFromSearchParams(props.params, state.currentScope);diff --git a/frontend/src/components/AdvancedSearch/ScopeTags.vue b/frontend/src/components/AdvancedSearch/ScopeTags.vueindex ec6bfbe9da..cf4a9382a7 100644--- a/frontend/src/components/AdvancedSearch/ScopeTags.vue+++ b/frontend/src/components/AdvancedSearch/ScopeTags.vue@@ -8,8 +8,8 @@:bordered="false"size="small"style="--n-icon-size: 12px"- v-bind="tagProps(scope)"- @close="$emit('remove-scope', scope.id, scope.value)"+ v-bind="tagProps(i)"+ @close="$emit('remove-scope', i)"@click.stop.prevent="handleClick(scope)"><div class="flex items-center gap-1">@@ -25,25 +25,25 @@ import type { TagProps } from "naive-ui";import { NTag } from "naive-ui";import { useI18n } from "vue-i18n";import { UNKNOWN_ID } from "@/types";-import type { SearchParams, SearchScope, SearchScopeId } from "@/utils";+import type { SearchParams, SearchScope } from "@/utils";import { callCssVariable, extractDatabaseResourceName } from "@/utils";import type { ScopeOption } from "./types";const props = defineProps<{params: SearchParams;scopeOptions: ScopeOption[];- focusedTagId?: SearchScopeId;+ focusedTagIndex?: number;}>();const emit = defineEmits<{- (event: "remove-scope", id: SearchScopeId, value: string): void;- (event: "select-scope", id: SearchScopeId, value: string): void;+ (event: "remove-scope", index: number): void;+ (event: "select-scope", scope: SearchScope): void;}>();const { t } = useI18n();-const tagProps = (scope: SearchScope): TagProps => {- if (props.focusedTagId !== scope.id) {+const tagProps = (index: number): TagProps => {+ if (props.focusedTagIndex !== index) {return {};}return {@@ -79,6 +79,6 @@ const handleClick = (scope: SearchScope) => {return;}- emit("select-scope", scope.id, scope.value);+ emit("select-scope", scope);};</script>diff --git a/frontend/src/components/AdvancedSearch/ValueMenu.vue b/frontend/src/components/AdvancedSearch/ValueMenu.vueindex 7f6fd6675e..4c13285422 100644--- a/frontend/src/components/AdvancedSearch/ValueMenu.vue+++ b/frontend/src/components/AdvancedSearch/ValueMenu.vue@@ -41,7 +41,7 @@><div class="border-t border-block-border"><div- class="h-[38px] flex gap-x-2 px-3 items-center cursor-pointer overflow-hidden"+ class="h-9.5 flex gap-x-2 px-3 items-center cursor-pointer overflow-hidden":class="[index === menuIndex && 'bg-gray-200/75']":data-index="index":data-value="option.value"diff --git a/frontend/src/components/IssueV1/components/Panel/issueStatusAction.ts b/frontend/src/components/IssueV1/components/Panel/issueStatusAction.tsindex 7701f268d0..389828b5ee 100644--- a/frontend/src/components/IssueV1/components/Panel/issueStatusAction.ts+++ b/frontend/src/components/IssueV1/components/Panel/issueStatusAction.ts@@ -2,7 +2,11 @@ import type { ButtonProps } from "naive-ui";import { t } from "@/plugins/i18n";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { isDatabaseDataExportIssue, isGrantRequestIssue } from "@/utils";+import {+ isAccessGrantIssue,+ isDatabaseDataExportIssue,+ isGrantRequestIssue,+} from "@/utils";export type IssueStatusAction = "CLOSE" | "REOPEN";@@ -29,8 +33,12 @@ export const getApplicableIssueStatusActionList = (): IssueStatusAction[] => {const list = PossibleIssueStatusActionMap[issue.status];return list.filter((action) => {- if (isGrantRequestIssue(issue) || isDatabaseDataExportIssue(issue)) {- // Don't show REOPEN for grantRequest/dataExport issues.+ if (+ isGrantRequestIssue(issue) ||+ isAccessGrantIssue(issue) ||+ isDatabaseDataExportIssue(issue)+ ) {+ // Don't show REOPEN for grantRequest/accessGrant/dataExport issues.if (action === "REOPEN") {return false;}diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vue b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vuenew file mode 100644index 0000000000..9036cbd0c0--- /dev/null+++ b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vue@@ -0,0 +1,9 @@+<template>+ <div class="w-full flex flex-col gap-y-4">+ <AccessGrantDetailsSection />+ </div>+</template>++<script lang="ts" setup>+import { AccessGrantDetailsSection } from "./AccessGrantView";+</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vuenew file mode 100644index 0000000000..81f54437e5--- /dev/null+++ b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vue@@ -0,0 +1,122 @@+<template>+ <div class="flex flex-col gap-y-4">+ <h3 class="text-base font-medium">+ {{ $t("issue.access-grant.details") }}+ </h3>++ <div v-if="isLoading" class="flex items-center justify-center py-8">+ <BBSpin />+ </div>++ <div v-else-if="accessGrant" class="p-4 border rounded-sm flex flex-col gap-y-4">+ <!-- Target Databases -->+ <div v-if="accessGrant.targets.length > 0" class="flex flex-col gap-y-2">+ <span class="text-sm text-control-light">+ {{ $t("common.databases") }}+ </span>+ <div class="flex flex-wrap gap-2">+ <div+ v-for="target in accessGrant.targets"+ :key="target"+ class="inline-flex items-center gap-2 px-2 py-1.5 border rounded-sm min-w-0"+ >+ <DatabaseDisplay+ :database="target"+ :show-environment="true"+ size="medium"+ class="flex-1 min-w-0"+ />+ </div>+ </div>+ </div>++ <!-- Query -->+ <div v-if="accessGrant.query" class="flex flex-col gap-y-2">+ <span class="text-sm text-control-light">+ {{ $t("common.statement") }}+ </span>+ <div+ class="max-h-[10em] overflow-auto border rounded-sm p-2 font-mono text-sm whitespace-pre-wrap"+ >+ {{ accessGrant.query }}+ </div>+ <NCheckbox :checked="accessGrant.unmask" :disabled="true">+ {{ $t("sql-editor.access-type-unmask") }}+ </NCheckbox>+ </div>++ <!-- Expiration Time -->+ <div class="flex flex-col gap-y-2">+ <span class="text-sm text-control-light">+ {{ $t("issue.grant-request.expired-at") }}+ </span>+ <div class="text-base">+ {{+ expireTime+ ? dayjs(expireTime).format("LLL")+ : $t("project.members.never-expires")+ }}+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import dayjs from "dayjs";+import { NCheckbox } from "naive-ui";+import { computed, ref, watchEffect } from "vue";+import { BBSpin } from "@/bbkit";+import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";+import { useAccessGrantStore, useDatabaseV1Store } from "@/store";+import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";+import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";+import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";+import { usePlanContextWithIssue } from "../../../logic";++const { issue, project } = usePlanContextWithIssue();+const dbStore = useDatabaseV1Store();+const accessGrantStore = useAccessGrantStore();++const isLoading = ref(true);+const accessGrant = ref<AccessGrant>();++const expireTime = computed(() => {+ if (accessGrant.value?.expiration.case === "expireTime") {+ return getDateForPbTimestampProtoEs(accessGrant.value.expiration.value);+ }+ return undefined;+});++watchEffect(async () => {+ const name = issue.value.accessGrant;+ if (!name) {+ isLoading.value = false;+ return;+ }+ try {+ let grant: AccessGrant | undefined;+ if (hasProjectPermissionV2(project.value, "bb.accessGrants.get")) {+ grant = await accessGrantStore.getAccessGrant(name);+ } else {+ const parent = `projects/${extractProjectResourceName(issue.value.name)}`;+ const response = await accessGrantStore.searchMyAccessGrants({+ parent,+ filter: { name },+ });+ grant = response.accessGrants[0];+ }+ accessGrant.value = grant;+ // Pre-fetch databases for display+ if (accessGrant.value) {+ for (const target of accessGrant.value.targets) {+ if (isValidDatabaseName(target)) {+ dbStore.getOrFetchDatabaseByName(target);+ }+ }+ }+ } finally {+ isLoading.value = false;+ }+});+</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.tsnew file mode 100644index 0000000000..81d961574d--- /dev/null+++ b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.ts@@ -0,0 +1,3 @@+import AccessGrantDetailsSection from "./AccessGrantDetailsSection.vue";++export { AccessGrantDetailsSection };diff --git a/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue b/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vueindex 95ec7a8b20..b791936c50 100644--- a/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue+++ b/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue@@ -76,15 +76,18 @@ const isCreateDatabasePlan = computed(() => {);});-const isGrantRequestIssue = computed(() => {- return issue.value?.type === Issue_Type.GRANT_REQUEST;+const isGrantRequestOrAccessGrantIssue = computed(() => {+ return (+ issue.value?.type === Issue_Type.GRANT_REQUEST ||+ issue.value?.type === Issue_Type.ACCESS_GRANT+ );});const shouldShowSidebar = computed(() => {return (!isDataExportPlan.value &&!isCreateDatabasePlan.value &&- !isGrantRequestIssue.value+ !isGrantRequestOrAccessGrantIssue.value);});diff --git a/frontend/src/components/Plan/logic/initialize/index.ts b/frontend/src/components/Plan/logic/initialize/index.tsindex b7d85ebb9d..9d5bc9f766 100644--- a/frontend/src/components/Plan/logic/initialize/index.ts+++ b/frontend/src/components/Plan/logic/initialize/index.ts@@ -135,7 +135,10 @@ export function useInitializePlan(if (!issueResult.plan) {// Issue without plan - allow it to stay in CICD layout for issue-only view// This is expected for grant requests, but may indicate a problem for other issue types- if (issueResult.type !== Issue_Type.GRANT_REQUEST) {+ if (+ issueResult.type !== Issue_Type.GRANT_REQUEST &&+ issueResult.type !== Issue_Type.ACCESS_GRANT+ ) {console.warn(`Issue ${issueUid} of type ${issueResult.type} has no associated plan`,issueResultdiff --git a/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue b/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vueindex 4c984f482b..78407e6b9c 100644--- a/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue+++ b/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue@@ -20,32 +20,6 @@@update:value="onLabelsUpdate"/></div>- <div>- <div class="flex items-center gap-x-2">- <Switch- v-model:value="state.allowRequestRole"- :text="true"- :disabled="- !allowUpdateIssueProjectSetting ||- loading- "- />- <div class="textlabel flex items-center gap-x-2">- {{- $t(- "project.settings.issue-related.allow-request-role.self"- )- }}- </div>- </div>- <div class="mt-1 text-sm text-gray-400">- {{- $t(- "project.settings.issue-related.allow-request-role.description"- )- }}- </div>- </div><div><div class="flex items-center gap-x-2"><Switch@@ -304,7 +278,6 @@ import {interface LocalState {issueLabels: Label[];- allowRequestRole: boolean;enforceSqlReview: boolean;forceIssueLabels: boolean;enforceIssueTitle: boolean;@@ -321,7 +294,6 @@ const getInitialLocalState = (): LocalState => {if (!props.project) {return {issueLabels: [],- allowRequestRole: false,forceIssueLabels: false,enforceIssueTitle: false,enforceSqlReview: false,@@ -338,7 +310,6 @@ const getInitialLocalState = (): LocalState => {}return {issueLabels: cloneDeep(props.project.issueLabels),- allowRequestRole: props.project.allowRequestRole,forceIssueLabels: props.project.forceIssueLabels,enforceIssueTitle: props.project.enforceIssueTitle,enforceSqlReview: props.project.enforceSqlReview,@@ -470,9 +441,6 @@ const updateMask = computed(() => {if (state.allowSelfApproval !== props.project.allowSelfApproval) {mask.push("allow_self_approval");}- if (!isEqual(state.allowRequestRole, props.project.allowRequestRole)) {- mask.push("allow_request_role");- }if (!isEqual(state.postgresDatabaseTenantMode,diff --git a/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vue b/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vueindex 550e8644d5..430962928a 100644--- a/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vue+++ b/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vue@@ -1,30 +1,123 @@<template><div class="w-full flex flex-col justify-start items-start gap-y-6">- <SQLReviewForResource- ref="sqlReviewForResourceRef"- :resource="project.name"- />-- <MaximumSQLResultSizeSetting- ref="maximumSQLResultSizeSettingRef"- :resource="project.name"- :policy="policyPayload"- />+ <ComponentPermissionGuard+ :project="project"+ :permissions="['bb.policies.get']"+ >+ <div class="w-full flex flex-col justify-start items-start gap-y-6">+ <SQLReviewForResource+ ref="sqlReviewForResourceRef"+ :resource="project.name"+ />++ <MaximumSQLResultSizeSetting+ ref="maximumSQLResultSizeSettingRef"+ :resource="project.name"+ :policy="policyPayload"+ />+ </div>+ </ComponentPermissionGuard>++ <div>+ <div class="flex items-center gap-x-2">+ <PermissionGuardWrapper+ v-slot="slotProps"+ :project="project"+ :permissions="[+ 'bb.projects.update'+ ]"+ >+ <Switch+ v-model:value="allowRequestRole"+ :text="true"+ :disabled="+ slotProps.disabled ||+ loading+ "+ />+ </PermissionGuardWrapper>+ <div class="textlabel flex items-center gap-x-2">+ {{+ $t(+ "project.settings.issue-related.allow-request-role.self"+ )+ }}+ </div>+ </div>+ <div class="mt-1 text-sm text-gray-400">+ {{+ $t(+ "project.settings.issue-related.allow-request-role.description"+ )+ }}+ </div>+ </div>++ <div v-if="isDev()">+ <div class="flex items-center gap-x-2">+ <PermissionGuardWrapper+ v-slot="slotProps"+ :project="project"+ :permissions="[+ 'bb.projects.update'+ ]"+ >+ <Switch+ v-model:value="allowJustInTimeAccess"+ :text="true"+ :disabled="+ slotProps.disabled ||+ loading+ "+ />+ </PermissionGuardWrapper>+ <div class="textlabel flex items-center gap-x-2">+ {{+ $t(+ "project.settings.issue-related.allow-jit.self"+ )+ }}+ </div>+ </div>+ <div class="mt-1 text-sm text-gray-400">+ {{+ $t(+ "project.settings.issue-related.allow-jit.description"+ )+ }}+ </div>+ </div></div></template><script setup lang="ts">+import { cloneDeep } from "lodash-es";import { computed, ref, watch } from "vue";import MaximumSQLResultSizeSetting from "@/components/GeneralSetting/MaximumSQLResultSizeSetting.vue";+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";import { SQLReviewForResource } from "@/components/SQLReview";-import { usePolicyByParentAndType, usePolicyV1Store } from "@/store";+import { Switch } from "@/components/v2";+import {+ usePolicyByParentAndType,+ usePolicyV1Store,+ useProjectV1Store,+} from "@/store";import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { isDev } from "@/utils";const props = defineProps<{project: Project;}>();+const projectStore = useProjectV1Store();+const policyV1Store = usePolicyV1Store();++const allowRequestRole = ref<boolean>(props.project.allowRequestRole);+const allowJustInTimeAccess = ref<boolean>(props.project.allowJustInTimeAccess);+const loading = ref<boolean>(false);+const sqlReviewForResourceRef =ref<InstanceType<typeof SQLReviewForResource>>();const maximumSQLResultSizeSettingRef =@@ -46,7 +139,6 @@ watch(});-const policyV1Store = usePolicyV1Store();const policyPayload = computed(() => {return policyV1Store.getQueryDataPolicyByParent(props.project.name);});@@ -54,9 +146,42 @@ const policyPayload = computed(() => {const isDirty = computed(() =>sqlReviewForResourceRef.value?.isDirty ||- maximumSQLResultSizeSettingRef.value?.isDirty+ maximumSQLResultSizeSettingRef.value?.isDirty ||+ allowRequestRole.value !== props.project.allowRequestRole ||+ allowJustInTimeAccess.value !== props.project.allowJustInTimeAccess);+const updateMask = computed(() => {+ const mask: string[] = [];+ if (allowRequestRole.value !== props.project.allowRequestRole) {+ mask.push("allow_request_role");+ }+ if (allowJustInTimeAccess.value !== props.project.allowJustInTimeAccess) {+ mask.push("allow_just_in_time_access");+ }+ return mask;+});++const doUpdateProject = async () => {+ if (loading.value) {+ return;+ }+ if (updateMask.value.length === 0) {+ return;+ }+ loading.value = true;+ const projectPatch = {+ ...cloneDeep(props.project),+ allowRequestRole: allowRequestRole.value,+ allowJustInTimeAccess: allowJustInTimeAccess.value,+ };+ try {+ await projectStore.updateProject(projectPatch, updateMask.value);+ } finally {+ loading.value = false;+ }+};+const onUpdate = async () => {if (sqlReviewForResourceRef.value?.isDirty) {await sqlReviewForResourceRef.value.update();@@ -64,11 +189,14 @@ const onUpdate = async () => {if (maximumSQLResultSizeSettingRef.value?.isDirty) {await maximumSQLResultSizeSettingRef.value.update();}+ await doUpdateProject();};const resetState = () => {sqlReviewForResourceRef.value?.revert();maximumSQLResultSizeSettingRef.value?.revert();+ allowRequestRole.value = props.project.allowRequestRole;+ allowJustInTimeAccess.value = props.project.allowJustInTimeAccess;};defineExpose({diff --git a/frontend/src/components/Project/useProjectSidebar.ts b/frontend/src/components/Project/useProjectSidebar.tsindex 318b0cf7c4..9c3b8ecffc 100644--- a/frontend/src/components/Project/useProjectSidebar.ts+++ b/frontend/src/components/Project/useProjectSidebar.ts@@ -11,6 +11,7 @@ import { useRoute } from "vue-router";import type { SidebarItem } from "@/components/v2/Sidebar/type";import { t } from "@/plugins/i18n";import {+ PROJECT_V1_ROUTE_ACCESS_GRANTS,PROJECT_V1_ROUTE_AUDIT_LOGS,PROJECT_V1_ROUTE_DATABASE_GROUPS,PROJECT_V1_ROUTE_DATABASES,@@ -29,6 +30,7 @@ import {} from "@/router/dashboard/projectV1";import { DEFAULT_PROJECT_NAME } from "@/types";import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { isDev } from "@/utils";interface ProjectSidebarItem extends SidebarItem {title: string;@@ -142,6 +144,12 @@ export const useProjectSidebar = (project: MaybeRef<Project>) => {path: PROJECT_V1_ROUTE_WEBHOOKS,type: "div",},+ {+ title: t("sql-editor.access-grants"),+ path: PROJECT_V1_ROUTE_ACCESS_GRANTS,+ type: "div",+ hide: !isDev(),+ },{title: t("project.masking-exemption.self"),path: PROJECT_V1_ROUTE_MASKING_EXEMPTION,diff --git a/frontend/src/components/ProjectSettingPanel.vue b/frontend/src/components/ProjectSettingPanel.vueindex edd4e72dd1..ae0a7f7697 100644--- a/frontend/src/components/ProjectSettingPanel.vue+++ b/frontend/src/components/ProjectSettingPanel.vue@@ -24,15 +24,10 @@</h1></div><div class="flex-1 mt-4 lg:px-4 lg:mt-0">- <ComponentPermissionGuard+ <ProjectSecuritySettingPanel+ ref="projectSecuritySettingPanelRef":project="project"- :permissions="['bb.policies.get']"- >- <ProjectSecuritySettingPanel- ref="projectSecuritySettingPanelRef"- :project="project"- />- </ComponentPermissionGuard>+ /></div></div>@@ -50,11 +45,11 @@'bb.projects.update']">- <ProjectIssueRelatedSettingPanel- ref="projectIssueRelatedSettingPanelRef"- :project="project"- :allow-edit="!slotProps.disabled"- />+ <ProjectIssueRelatedSettingPanel+ ref="projectIssueRelatedSettingPanelRef"+ :project="project"+ :allow-edit="!slotProps.disabled"+ /></PermissionGuardWrapper></div></div>@@ -164,7 +159,6 @@ import { computed, reactive, ref } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { BBButtonConfirm } from "@/bbkit";-import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex 91e2afad5e..e1604d9845 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -71,12 +71,12 @@ import {extractWorksheetUID,getDefaultPagination,getSheetStatement,- isDatabaseV1Queryable,isWorksheetReadableV1,STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,suggestedTabTitleForSQLEditorConnection,} from "@/utils";import {+ ASIDE_PANEL_TABS,type AsidePanelTab,useSQLEditorContext,} from "@/views/sql-editor/context";@@ -222,15 +222,6 @@ const prepareConnectionParams = async () => {const database =await useDatabaseV1Store().getOrFetchDatabaseByName(databaseName);await maybeSwitchProject(database.project);- if (!isDatabaseV1Queryable(database)) {- const tabs = tabStore.openTabList.filter(- (tab) => tab.connection.database === database.name- );- for (const tab of tabs) {- tabStore.closeTab(tab.id);- }- return false;- }// connected to dbconst { instance } = extractDatabaseResourceName(database.name);const connection = {@@ -293,7 +284,8 @@ const syncURLWithConnection = () => {"filter","project","schema",- "database"+ "database",+ "panel");if (sheetName) {@@ -319,15 +311,6 @@ const syncURLWithConnection = () => {if (isValidDatabaseName(databaseName)) {const database =await databaseStore.getOrFetchDatabaseByName(databaseName);- if (!isDatabaseV1Queryable(database)) {- return router.replace({- name: SQL_EDITOR_PROJECT_MODULE,- params: {- project: extractProjectResourceName(database.project),- },- query,- });- }if (schema) {query.schema = schema;}@@ -385,7 +368,19 @@ const restoreLastVisitedSidebarTab = () => {STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,"WORKSHEET");- asidePanelTab.value = storedLastVisitedSidebarTab.value;++ // Check for ?panel= query param to allow deep-linking to a specific tab.+ const panelQuery = route.query.panel;+ if (typeof panelQuery === "string" && panelQuery) {+ const tab = panelQuery.toUpperCase() as AsidePanelTab;+ if (ASIDE_PANEL_TABS.includes(tab)) {+ asidePanelTab.value = tab;+ } else {+ asidePanelTab.value = storedLastVisitedSidebarTab.value;+ }+ } else {+ asidePanelTab.value = storedLastVisitedSidebarTab.value;+ }watch(asidePanelTab,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 92b167646b..fe04090699 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -175,6 +175,9 @@"download": "Download","deleted": "Deleted","active": "Active",+ "activated": "Activated",+ "pending": "Pending",+ "revoked": "Revoked","reopen": "Reopen","plan": "Plan","rollout": "Rollout",@@ -1072,6 +1075,9 @@"high": "High"},"issue-name": "Issue name",+ "access-grant": {+ "details": "Access Grant Details"+ },"grant-request": {"details": "Request Details","expired-at": "Expired at",@@ -1874,6 +1880,10 @@"allow-request-role": {"self": "Allow request role","description": "Non-project-owner users can request project-level roles themselves"+ },+ "allow-jit": {+ "self": "Allow just-in-time access",+ "description": "Once enabled, users can request and use the just-in-time access in the SQL Editor."}},"project-labels": {@@ -1993,7 +2003,6 @@"invalid-database": "Invalid database {database}","request-aborted": "User aborted the request","no-data-source": "No queriable data source. Please check the data source query policy on environment or project.",- "database-not-queriable": "Database is not queriable","no-queriable-database": "No queriable database","rows": "row | rows","vertical-display": "Vertical display",@@ -2127,7 +2136,28 @@"search-scope-row-number-title": "Row number","search-scope-row-number-description": "Enter a row number to jump to that row.","scroll-to-top": "Scroll to the top",- "scroll-to-bottom": "Scroll to the bottom"+ "scroll-to-bottom": "Scroll to the bottom",+ "jit": "Just-In-Time Access",+ "request-access": "Request Access",+ "no-access-requests": "No access requests",+ "request-jit": "Request just-in-time access",+ "view-issue": "View Issue",+ "expire-at": "Expire at {time}",+ "expire-in": "Expire in {time}",+ "and-n-more-databases": "and {n} more databases",+ "expired": "Expired",+ "grant-type-unmask": "Unmask",+ "request-data-access": "Request Data Access",+ "access-type-unmask": "See unmasked sensitive data",+ "duration-hours": "{hours} hour | {hours} hours",+ "duration-day": "{days} day",+ "duration-days": "{days} days",+ "access-grants": "Access Grants",+ "access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",+ "revoke-access": "Revoke",+ "revoke-confirm": "Are you sure you want to revoke this access grant?",+ "activate-access": "Activate",+ "activate-confirm": "Are you sure you want to activate this access grant?"},"schema-editor": {"self": "Schema Editor",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex c6468f647f..38fe4822e1 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -175,6 +175,9 @@"download": "Descargar","deleted": "Eliminado","active": "Activo",+ "activated": "Activado",+ "pending": "Pendiente",+ "revoked": "Revocado","reopen": "Reabrir","plan": "Plan","rollout": "Implementar",@@ -1072,6 +1075,9 @@"high": "Alto"},"issue-name": "Nombre de la incidencia",+ "access-grant": {+ "details": "Access Grant Details"+ },"grant-request": {"details": "Detalles de la solicitud","expired-at": "tiempo de caducidad",@@ -1872,6 +1878,10 @@"allow-request-role": {"self": "Permitir solicitar rol","description": "Los usuarios que no son propietarios del proyecto pueden solicitar roles a nivel de proyecto por sí mismos"+ },+ "allow-jit": {+ "self": "Permitir acceso justo a tiempo",+ "description": "Una vez habilitado, los usuarios pueden solicitar y usar el acceso justo a tiempo en el Editor SQL."}},"project-labels": {@@ -1993,7 +2003,6 @@"invalid-database": "Base de datos no válida {database}","request-aborted": "El usuario abortó la solicitud","no-data-source": "No se puede consultar ninguna fuente de datos. Consulte la política de consulta de fuentes de datos del entorno o proyecto.",- "database-not-queriable": "La base de datos no se puede consultar","no-queriable-database": "No hay base de datos consultable","rows": "fila | filas","vertical-display": "Pantalla vertical",@@ -2127,7 +2136,28 @@"search-scope-row-number-title": "Número de fila","search-scope-row-number-description": "Ingrese un número de fila para saltar a esa fila.","scroll-to-top": "Desplazarse hacia arriba",- "scroll-to-bottom": "Desplazarse hacia abajo"+ "scroll-to-bottom": "Desplazarse hacia abajo",+ "jit": "Just-In-Time Access",+ "request-access": "Request Access",+ "no-access-requests": "No access requests",+ "request-jit": "Request just-in-time access",+ "view-issue": "View Issue",+ "expire-at": "Expire at {time}",+ "expire-in": "Expire in {time}",+ "and-n-more-databases": "and {n} more databases",+ "expired": "Expired",+ "grant-type-unmask": "Unmask",+ "request-data-access": "Request Data Access",+ "access-type-unmask": "See unmasked sensitive data",+ "duration-hours": "{hours} hour | {hours} hours",+ "duration-day": "{days} day",+ "duration-days": "{days} days",+ "access-grants": "Access Grants",+ "access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",+ "revoke-access": "Revoke",+ "revoke-confirm": "Are you sure you want to revoke this access grant?",+ "activate-access": "Activate",+ "activate-confirm": "Are you sure you want to activate this access grant?"},"schema-editor": {"self": "Editor de esquema",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 8bf5574198..845f9701da 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -175,6 +175,9 @@"download": "ダウンロード","deleted": "削除されました","active": "アクティブ",+ "activated": "有効化しました",+ "pending": "保留中",+ "revoked": "取り消し済み","reopen": "再開","plan": "プラン","rollout": "リリース",@@ -1072,6 +1075,9 @@"high": "高い"},"issue-name": "イシュー名",+ "access-grant": {+ "details": "Access Grant Details"+ },"grant-request": {"details": "リクエストの詳細","expired-at": "有効期限",@@ -1872,6 +1878,10 @@"allow-request-role": {"self": "ロールリクエストを許可","description": "プロジェクト所有者以外のユーザーがプロジェクトレベルのロールを自分でリクエストできます"+ },+ "allow-jit": {+ "self": "ジャストインタイムアクセスを許可",+ "description": "有効にすると、ユーザーは SQL エディタでジャストインタイムアクセスをリクエストして使用できます。"}},"project-labels": {@@ -1993,7 +2003,6 @@"invalid-database": "無効なデータベース {database}","request-aborted": "ユーザーがリクエストを中止しました","no-data-source": "クエリ可能なデータソースがありません。環境またはプロジェクトのデータソースクエリポリシーを確認してください。",- "database-not-queriable": "データベースはクエリできません","no-queriable-database": "クエリ可能なデータベースがありません","rows": "記録","vertical-display": "縦型表示",@@ -2127,7 +2136,28 @@"search-scope-row-number-title": "行番号","search-scope-row-number-description": "行番号を入力してその行にジャンプします。","scroll-to-top": "先頭へスクロール",- "scroll-to-bottom": "末尾へスクロール"+ "scroll-to-bottom": "末尾へスクロール",+ "jit": "Just-In-Time Access",+ "request-access": "Request Access",+ "no-access-requests": "No access requests",+ "request-jit": "Request just-in-time access",+ "view-issue": "View Issue",+ "expire-at": "Expire at {time}",+ "expire-in": "Expire in {time}",+ "and-n-more-databases": "and {n} more databases",+ "expired": "Expired",+ "grant-type-unmask": "Unmask",+ "request-data-access": "Request Data Access",+ "access-type-unmask": "See unmasked sensitive data",+ "duration-hours": "{hours} hour | {hours} hours",+ "duration-day": "{days} day",+ "duration-days": "{days} days",+ "access-grants": "Access Grants",+ "access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",+ "revoke-access": "Revoke",+ "revoke-confirm": "Are you sure you want to revoke this access grant?",+ "activate-access": "Activate",+ "activate-confirm": "Are you sure you want to activate this access grant?"},"schema-editor": {"self": "スキーマエディタ",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 6707047c5f..d8d439fe91 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -175,6 +175,9 @@"download": "Tải xuống","deleted": "Đã xóa","active": "Hoạt động",+ "activated": "Đã kích hoạt",+ "pending": "Đang chờ",+ "revoked": "Đã thu hồi","reopen": "Mở lại","plan": "Kế hoạch","rollout": "Triển khai",@@ -1072,6 +1075,9 @@"high": "Cao"},"issue-name": "Tên vấn đề",+ "access-grant": {+ "details": "Access Grant Details"+ },"grant-request": {"details": "Yêu cầu chi tiết","expired-at": "Hết hạn vào",@@ -1872,6 +1878,10 @@"allow-request-role": {"self": "Cho phép yêu cầu vai trò","description": "Người dùng không phải chủ sở hữu dự án có thể tự yêu cầu vai trò cấp dự án"+ },+ "allow-jit": {+ "self": "Cho phép truy cập tức thời",+ "description": "Khi được bật, người dùng có thể yêu cầu và sử dụng quyền truy cập tức thời trong Trình soạn thảo SQL."}},"project-labels": {@@ -1993,7 +2003,6 @@"invalid-database": "Cơ sở dữ liệu không hợp lệ {database}","request-aborted": "Người dùng đã hủy yêu cầu","no-data-source": "Không có nguồn dữ liệu có thể truy vấn. Vui lòng kiểm tra chính sách truy vấn nguồn dữ liệu trên môi trường hoặc dự án.",- "database-not-queriable": "Cơ sở dữ liệu không thể truy vấn","no-queriable-database": "Không có cơ sở dữ liệu có thể truy vấn","rows": "dòng | dòng","vertical-display": "Hiển thị dọc",@@ -2127,7 +2136,28 @@"search-scope-row-number-title": "Số dòng","search-scope-row-number-description": "Nhập số dòng để chuyển đến dòng đó.","scroll-to-top": "Cuộn lên đầu",- "scroll-to-bottom": "Cuộn xuống cuối"+ "scroll-to-bottom": "Cuộn xuống cuối",+ "jit": "Just-In-Time Access",+ "request-access": "Request Access",+ "no-access-requests": "No access requests",+ "request-jit": "Request just-in-time access",+ "view-issue": "View Issue",+ "expire-at": "Expire at {time}",+ "expire-in": "Expire in {time}",+ "and-n-more-databases": "and {n} more databases",+ "expired": "Expired",+ "grant-type-unmask": "Unmask",+ "request-data-access": "Request Data Access",+ "access-type-unmask": "See unmasked sensitive data",+ "duration-hours": "{hours} hour | {hours} hours",+ "duration-day": "{days} day",+ "duration-days": "{days} days",+ "access-grants": "Access Grants",+ "access-grants-redirect-hint": "Go to {link} to view and manage your own access grants.",+ "revoke-access": "Revoke",+ "revoke-confirm": "Are you sure you want to revoke this access grant?",+ "activate-access": "Activate",+ "activate-confirm": "Are you sure you want to activate this access grant?"},"schema-editor": {"self": "Trình soạn thảo lược đồ",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 3deb708731..bd5abf5ac2 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -175,6 +175,9 @@"download": "下载","deleted": "已删除","active": "开启",+ "activated": "已激活",+ "pending": "待审批",+ "revoked": "已撤销","reopen": "重开","plan": "变更计划","rollout": "发布",@@ -1072,6 +1075,9 @@"high": "高风险"},"issue-name": "工单名称",+ "access-grant": {+ "details": "访问授权详情"+ },"grant-request": {"details": "请求详细","expired-at": "过期时间",@@ -1872,6 +1878,10 @@"allow-request-role": {"self": "允许申请角色","description": "非项目所有者可以自行申请项目级角色"+ },+ "allow-jit": {+ "self": "允许即时访问",+ "description": "启用后,用户可以在 SQL 编辑器中请求并使用即时数据访问权限。"}},"project-labels": {@@ -1993,7 +2003,6 @@"invalid-database": "数据库 {database} 无效","request-aborted": "用户中止了请求","no-data-source": "没有可查询的数据源。请检查环境或项目的数据源查询策略。",- "database-not-queriable": "数据库不可查询","no-queriable-database": "没有可查询的数据库","rows": "条记录","vertical-display": "竖向展示",@@ -2127,7 +2136,28 @@"search-scope-row-number-title": "行号","search-scope-row-number-description": "输入行号跳转到指定行。","scroll-to-top": "滚动到顶部",- "scroll-to-bottom": "滚动到底部"+ "scroll-to-bottom": "滚动到底部",+ "jit": "即时访问",+ "request-access": "申请访问",+ "no-access-requests": "暂无访问请求",+ "request-jit": "申请即时访问",+ "view-issue": "查看工单",+ "expire-at": "{time} 过期",+ "expire-in": "{time} 后过期",+ "and-n-more-databases": "及其他 {n} 个数据库",+ "expired": "已过期",+ "grant-type-unmask": "脱敏豁免",+ "request-data-access": "申请数据访问",+ "access-type-unmask": "查看未脱敏的敏感数据",+ "duration-hours": "{hours} 小时",+ "duration-day": "{days} 天",+ "duration-days": "{days} 天",+ "access-grants": "访问授权",+ "access-grants-redirect-hint": "前往 {link} 查看和管理您自己的访问授权。",+ "revoke-access": "撤销",+ "revoke-confirm": "确定要撤销此访问授权吗?",+ "activate-access": "激活",+ "activate-confirm": "确定要激活此访问授权吗?"},"schema-editor": {"self": "Schema 编辑器",diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.tsindex 6b61d5c765..4a1c89c584 100644--- a/frontend/src/router/dashboard/projectV1.ts+++ b/frontend/src/router/dashboard/projectV1.ts@@ -24,6 +24,7 @@ export const PROJECT_V1_ROUTE_AUDIT_LOGS = `${PROJECT_V1_ROUTE_DASHBOARD}.audit-export const PROJECT_V1_ROUTE_WEBHOOKS = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook`;export const PROJECT_V1_ROUTE_WEBHOOK_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.create`;export const PROJECT_V1_ROUTE_WEBHOOK_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.detail`;+export const PROJECT_V1_ROUTE_ACCESS_GRANTS = `${PROJECT_V1_ROUTE_DASHBOARD}.access-grants`;export const PROJECT_V1_ROUTE_MEMBERS = `${PROJECT_V1_ROUTE_DASHBOARD}.members`;export const PROJECT_V1_ROUTE_SERVICE_ACCOUNTS = `${PROJECT_V1_ROUTE_DASHBOARD}.service-accounts`;export const PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES = `${PROJECT_V1_ROUTE_DASHBOARD}.workload-identities`;@@ -150,6 +151,16 @@ const projectV1Routes: RouteRecordRaw[] = [component: () => import("@/views/project/ProjectDatabaseDashboard.vue"),props: true,},+ {+ path: "access-grants",+ name: PROJECT_V1_ROUTE_ACCESS_GRANTS,+ meta: {+ title: () => t("sql-editor.access-grants"),+ },+ component: () =>+ import("@/views/project/ProjectAccessGrantDashboard.vue"),+ props: true,+ },{path: "masking-exemption",meta: {diff --git a/frontend/src/store/modules/accessGrant.ts b/frontend/src/store/modules/accessGrant.tsindex 9293bcd476..466b06c08d 100644--- a/frontend/src/store/modules/accessGrant.ts+++ b/frontend/src/store/modules/accessGrant.ts@@ -4,7 +4,11 @@ import { accessGrantServiceClientConnect } from "@/connect";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import {AccessGrant_Status,+ ActivateAccessGrantRequestSchema,CreateAccessGrantRequestSchema,+ GetAccessGrantRequestSchema,+ ListAccessGrantsRequestSchema,+ RevokeAccessGrantRequestSchema,SearchMyAccessGrantsRequestSchema,} from "@/types/proto-es/v1/access_grant_service_pb";@@ -14,6 +18,7 @@ export interface AccessFilter {creator?: string;status?: AccessGrant_Status;issue?: string;+ target?: string;createdTsAfter?: number;createdTsBefore?: number;expireTsAfter?: number;@@ -34,7 +39,7 @@ const getListAccessFilter = (filter: AccessFilter | undefined): string => {parts.push(`status == "${AccessGrant_Status[filter.status]}"`);}if (filter.statement) {- parts.push(`query == "${filter.statement}"`);+ parts.push(`query.matches("${filter.statement.trim()}")`);}if (filter.creator) {parts.push(`creator == "${filter.creator}"`);@@ -42,6 +47,9 @@ const getListAccessFilter = (filter: AccessFilter | undefined): string => {if (filter.issue) {parts.push(`issue == "${filter.issue}"`);}+ if (filter.target) {+ parts.push(`target == "${filter.target}"`);+ }if (filter.createdTsAfter !== undefined) {parts.push(`create_time >= "${new Date(filter.createdTsAfter).toISOString()}"`@@ -66,19 +74,29 @@ const getListAccessFilter = (filter: AccessFilter | undefined): string => {return parts.join(" && ");};+interface ListAccessGrantsParams {+ parent: string;+ filter?: AccessFilter;+ pageSize?: number;+ pageToken?: string;+ orderBy?: string;+}+export const useAccessGrantStore = defineStore("accessGrant", () => {- const searchMyAccessGrants = async (- parent: string,- filter?: AccessFilter,- pageSize?: number,- pageToken?: string- ) => {+ const getAccessGrant = async (name: string) => {+ return await accessGrantServiceClientConnect.getAccessGrant(+ create(GetAccessGrantRequestSchema, { name })+ );+ };++ const searchMyAccessGrants = async (params: ListAccessGrantsParams) => {return await accessGrantServiceClientConnect.searchMyAccessGrants(create(SearchMyAccessGrantsRequestSchema, {- parent,- filter: getListAccessFilter(filter),- pageSize: pageSize ?? 0,- pageToken: pageToken ?? "",+ parent: params.parent,+ filter: getListAccessFilter(params.filter),+ pageSize: params.pageSize ?? 0,+ pageToken: params.pageToken ?? "",+ orderBy: params.orderBy ?? "",}));};@@ -95,8 +113,36 @@ export const useAccessGrantStore = defineStore("accessGrant", () => {);};+ const listAccessGrants = async (params: ListAccessGrantsParams) => {+ return await accessGrantServiceClientConnect.listAccessGrants(+ create(ListAccessGrantsRequestSchema, {+ parent: params.parent,+ filter: getListAccessFilter(params.filter),+ pageSize: params.pageSize ?? 0,+ pageToken: params.pageToken ?? "",+ orderBy: params.orderBy ?? "",+ })+ );+ };++ const activateAccessGrant = async (name: string) => {+ return await accessGrantServiceClientConnect.activateAccessGrant(+ create(ActivateAccessGrantRequestSchema, { name })+ );+ };++ const revokeAccessGrant = async (name: string) => {+ return await accessGrantServiceClientConnect.revokeAccessGrant(+ create(RevokeAccessGrantRequestSchema, { name })+ );+ };+return {+ getAccessGrant,searchMyAccessGrants,createAccessGrant,+ listAccessGrants,+ activateAccessGrant,+ revokeAccessGrant,};});diff --git a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.tsindex 269177193f..561a7dc39d 100644--- a/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/access_grant_service_pb.d.ts@@ -215,6 +215,7 @@ export declare type ListAccessGrantsRequest = Message<"bytebase.v1.ListAccessGra* - expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.* - create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.* - query: the access query, support "==" and ".contains(xx)" operator+ * - target: the target database fullname, support "==" operator.** Examples:* - creator == "users/[email protected]"@@ -223,10 +224,23 @@ export declare type ListAccessGrantsRequest = Message<"bytebase.v1.ListAccessGra* - creator == "users/[email protected]" && status == "ACTIVE"* - issue == "projects/x/issues/123"* - status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ * - target == "instances/sample/databases/employee"** @generated from field: string filter = 4;*/filter: string;++ /**+ * The order by of access grants.+ * Support creator, expire_time, create_time. The default sorting order is ascending.+ * For example:+ * - order_by = "creator"+ * - order_by = "expire_time desc"+ * - order_by = "expire_time asc, create_time desc"+ *+ * @generated from field: string order_by = 5;+ */+ orderBy: string;};/**@@ -352,16 +366,18 @@ export declare type SearchMyAccessGrantsRequest = Message<"bytebase.v1.SearchMyApageToken: string;/**- * Filter expression using AIP-160 syntax.- * Supported fields: name, status, expire_time, create_time- * Examples:- * - 'name = "projects/x/accessGrants/uuid"'- * - 'status = "ACTIVE"'- * - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'+ * Check the filter field in the ListAccessGrantsRequest message.** @generated from field: string filter = 4;*/filter: string;++ /**+ * Check the order_by field in the ListAccessGrantsRequest message.+ *+ * @generated from field: string order_by = 5;+ */+ orderBy: string;};/**diff --git a/frontend/src/types/proto-es/v1/access_grant_service_pb.js b/frontend/src/types/proto-es/v1/access_grant_service_pb.jsindex 3936505d93..22d1512aab 100644--- a/frontend/src/types/proto-es/v1/access_grant_service_pb.js+++ b/frontend/src/types/proto-es/v1/access_grant_service_pb.js@@ -14,7 +14,7 @@ import { file_v1_annotation } from "./annotation_pb";* Describes the file v1/access_grant_service.proto.*/export const file_v1_access_grant_service = /*@__PURE__*/- fileDesc("Ch12MS9hY2Nlc3NfZ3JhbnRfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiswQKC0FjY2Vzc0dyYW50EgwKBG5hbWUYASABKAkSFAoHY3JlYXRvchgCIAEoCUID4EECEjQKBnN0YXR1cxgDIAEoDjIfLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50LlN0YXR1c0ID4EEDEjEKC2V4cGlyZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgAEi0KA3R0bBgLIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbkID4EEESAASEgoFaXNzdWUYBSABKAlCA+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAogASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEg4KBnJlYXNvbhgMIAEoCSJGCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgoKBkFDVElWRRACEgsKB1JFVk9LRUQQAzpN6kFKChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQSLnByb2plY3RzL3twcm9qZWN0fS9hY2Nlc3NHcmFudHMve2FjY2Vzc19ncmFudH1CDAoKZXhwaXJhdGlvbiJHChVHZXRBY2Nlc3NHcmFudFJlcXVlc3QSLgoEbmFtZRgBIAEoCUIg4EEC+kEaChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQifgoXTGlzdEFjY2Vzc0dyYW50c1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0EhEKCXBhZ2Vfc2l6ZRgCIAEoBRISCgpwYWdlX3Rva2VuGAMgASgJEg4KBmZpbHRlchgEIAEoCSJkChhMaXN0QWNjZXNzR3JhbnRzUmVzcG9uc2USLwoNYWNjZXNzX2dyYW50cxgBIAMoCzIYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSJ9ChhDcmVhdGVBY2Nlc3NHcmFudFJlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0EjMKDGFjY2Vzc19ncmFudBgCIAEoCzIYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50QgPgQQIiTAoaQWN0aXZhdGVBY2Nlc3NHcmFudFJlcXVlc3QSLgoEbmFtZRgBIAEoCUIg4EEC+kEaChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQiSgoYUmV2b2tlQWNjZXNzR3JhbnRSZXF1ZXN0Ei4KBG5hbWUYASABKAlCIOBBAvpBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50IoIBChtTZWFyY2hNeUFjY2Vzc0dyYW50c1JlcXVlc3QSLAoGcGFyZW50GAEgASgJQhzgQQL6QRYKFGJ5dGViYXNlLmNvbS9Qcm9qZWN0EhEKCXBhZ2Vfc2l6ZRgCIAEoBRISCgpwYWdlX3Rva2VuGAMgASgJEg4KBmZpbHRlchgEIAEoCSJoChxTZWFyY2hNeUFjY2Vzc0dyYW50c1Jlc3BvbnNlEi8KDWFjY2Vzc19ncmFudHMYASADKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAky8AgKEkFjY2Vzc0dyYW50U2VydmljZRKeAQoOR2V0QWNjZXNzR3JhbnQSIi5ieXRlYmFzZS52MS5HZXRBY2Nlc3NHcmFudFJlcXVlc3QaGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudCJO2kEEbmFtZYrqMBNiYi5hY2Nlc3NHcmFudHMuZ2V0kOowAYLT5JMCJhIkL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9ErIBChBMaXN0QWNjZXNzR3JhbnRzEiQuYnl0ZWJhc2UudjEuTGlzdEFjY2Vzc0dyYW50c1JlcXVlc3QaJS5ieXRlYmFzZS52MS5MaXN0QWNjZXNzR3JhbnRzUmVzcG9uc2UiUdpBBnBhcmVudIrqMBRiYi5hY2Nlc3NHcmFudHMubGlzdJDqMAGC0+STAiYSJC92MS97cGFyZW50PXByb2plY3RzLyp9L2FjY2Vzc0dyYW50cxLIAQoRQ3JlYXRlQWNjZXNzR3JhbnQSJS5ieXRlYmFzZS52MS5DcmVhdGVBY2Nlc3NHcmFudFJlcXVlc3QaGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudCJy2kETcGFyZW50LGFjY2Vzc19ncmFudIrqMBZiYi5hY2Nlc3NHcmFudHMuY3JlYXRlkOowAZjqMAGC0+STAjQ6DGFjY2Vzc19ncmFudCIkL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYWNjZXNzR3JhbnRzEr0BChNBY3RpdmF0ZUFjY2Vzc0dyYW50EicuYnl0ZWJhc2UudjEuQWN0aXZhdGVBY2Nlc3NHcmFudFJlcXVlc3QaGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudCJj2kEEbmFtZYrqMBhiYi5hY2Nlc3NHcmFudHMuYWN0aXZhdGWQ6jABmOowAYLT5JMCMjoBKiItL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9OmFjdGl2YXRlErUBChFSZXZva2VBY2Nlc3NHcmFudBIlLmJ5dGViYXNlLnYxLlJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBoYLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50Il/aQQRuYW1liuowFmJiLmFjY2Vzc0dyYW50cy5yZXZva2WQ6jABmOowAYLT5JMCMDoBKiIrL3YxL3tuYW1lPXByb2plY3RzLyovYWNjZXNzR3JhbnRzLyp9OnJldm9rZRLAAQoUU2VhcmNoTXlBY2Nlc3NHcmFudHMSKC5ieXRlYmFzZS52MS5TZWFyY2hNeUFjY2Vzc0dyYW50c1JlcXVlc3QaKS5ieXRlYmFzZS52MS5TZWFyY2hNeUFjY2Vzc0dyYW50c1Jlc3BvbnNlIlOK6jATYmIuYWNjZXNzR3JhbnRzLmdldJDqMAKC0+STAjI6ASoiLS92MS97cGFyZW50PXByb2plY3RzLyp9L2FjY2Vzc0dyYW50czpzZWFyY2hNeUKtAQoPY29tLmJ5dGViYXNlLnYxQhdBY2Nlc3NHcmFudFNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_timestamp, file_v1_annotation]);+ fileDesc("Ch12MS9hY2Nlc3NfZ3JhbnRfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiswQKC0FjY2Vzc0dyYW50EgwKBG5hbWUYASABKAkSFAoHY3JlYXRvchgCIAEoCUID4EECEjQKBnN0YXR1cxgDIAEoDjIfLmJ5dGViYXNlLnYxLkFjY2Vzc0dyYW50LlN0YXR1c0ID4EEDEjEKC2V4cGlyZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgAEi0KA3R0bBgLIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbkID4EEESAASEgoFaXNzdWUYBSABKAlCA+BBAxIUCgd0YXJnZXRzGAYgAygJQgPgQQISDQoFcXVlcnkYByABKAkSDgoGdW5tYXNrGAggASgIEjQKC2NyZWF0ZV90aW1lGAkgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAogASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEg4KBnJlYXNvbhgMIAEoCSJGCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgoKBkFDVElWRRACEgsKB1JFVk9LRUQQAzpN6kFKChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQSLnByb2plY3RzL3twcm9qZWN0fS9hY2Nlc3NHcmFudHMve2FjY2Vzc19ncmFudH1CDAoKZXhwaXJhdGlvbiJHChVHZXRBY2Nlc3NHcmFudFJlcXVlc3QSLgoEbmFtZRgBIAEoCUIg4EEC+kEaChhieXRlYmFzZS5jb20vQWNjZXNzR3JhbnQikAEKF0xpc3RBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiZAoYTGlzdEFjY2Vzc0dyYW50c1Jlc3BvbnNlEi8KDWFjY2Vzc19ncmFudHMYASADKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkifQoYQ3JlYXRlQWNjZXNzR3JhbnRSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIzCgxhY2Nlc3NfZ3JhbnQYAiABKAsyGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudEID4EECIkwKGkFjdGl2YXRlQWNjZXNzR3JhbnRSZXF1ZXN0Ei4KBG5hbWUYASABKAlCIOBBAvpBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50IkoKGFJldm9rZUFjY2Vzc0dyYW50UmVxdWVzdBIuCgRuYW1lGAEgASgJQiDgQQL6QRoKGGJ5dGViYXNlLmNvbS9BY2Nlc3NHcmFudCKUAQobU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSEAoIb3JkZXJfYnkYBSABKAkiaAocU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXNwb25zZRIvCg1hY2Nlc3NfZ3JhbnRzGAEgAygLMhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJMvAIChJBY2Nlc3NHcmFudFNlcnZpY2USngEKDkdldEFjY2Vzc0dyYW50EiIuYnl0ZWJhc2UudjEuR2V0QWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQiTtpBBG5hbWWK6jATYmIuYWNjZXNzR3JhbnRzLmdldJDqMAGC0+STAiYSJC92MS97bmFtZT1wcm9qZWN0cy8qL2FjY2Vzc0dyYW50cy8qfRKyAQoQTGlzdEFjY2Vzc0dyYW50cxIkLmJ5dGViYXNlLnYxLkxpc3RBY2Nlc3NHcmFudHNSZXF1ZXN0GiUuYnl0ZWJhc2UudjEuTGlzdEFjY2Vzc0dyYW50c1Jlc3BvbnNlIlHaQQZwYXJlbnSK6jAUYmIuYWNjZXNzR3JhbnRzLmxpc3SQ6jABgtPkkwImEiQvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9hY2Nlc3NHcmFudHMSyAEKEUNyZWF0ZUFjY2Vzc0dyYW50EiUuYnl0ZWJhc2UudjEuQ3JlYXRlQWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQictpBE3BhcmVudCxhY2Nlc3NfZ3JhbnSK6jAWYmIuYWNjZXNzR3JhbnRzLmNyZWF0ZZDqMAGY6jABgtPkkwI0OgxhY2Nlc3NfZ3JhbnQiJC92MS97cGFyZW50PXByb2plY3RzLyp9L2FjY2Vzc0dyYW50cxK9AQoTQWN0aXZhdGVBY2Nlc3NHcmFudBInLmJ5dGViYXNlLnYxLkFjdGl2YXRlQWNjZXNzR3JhbnRSZXF1ZXN0GhguYnl0ZWJhc2UudjEuQWNjZXNzR3JhbnQiY9pBBG5hbWWK6jAYYmIuYWNjZXNzR3JhbnRzLmFjdGl2YXRlkOowAZjqMAGC0+STAjI6ASoiLS92MS97bmFtZT1wcm9qZWN0cy8qL2FjY2Vzc0dyYW50cy8qfTphY3RpdmF0ZRK1AQoRUmV2b2tlQWNjZXNzR3JhbnQSJS5ieXRlYmFzZS52MS5SZXZva2VBY2Nlc3NHcmFudFJlcXVlc3QaGC5ieXRlYmFzZS52MS5BY2Nlc3NHcmFudCJf2kEEbmFtZYrqMBZiYi5hY2Nlc3NHcmFudHMucmV2b2tlkOowAZjqMAGC0+STAjA6ASoiKy92MS97bmFtZT1wcm9qZWN0cy8qL2FjY2Vzc0dyYW50cy8qfTpyZXZva2USwAEKFFNlYXJjaE15QWNjZXNzR3JhbnRzEiguYnl0ZWJhc2UudjEuU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXF1ZXN0GikuYnl0ZWJhc2UudjEuU2VhcmNoTXlBY2Nlc3NHcmFudHNSZXNwb25zZSJTiuowE2JiLmFjY2Vzc0dyYW50cy5nZXSQ6jACgtPkkwIyOgEqIi0vdjEve3BhcmVudD1wcm9qZWN0cy8qfS9hY2Nlc3NHcmFudHM6c2VhcmNoTXlCrQEKD2NvbS5ieXRlYmFzZS52MUIXQWNjZXNzR3JhbnRTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_timestamp, file_v1_annotation]);/*** Describes the message bytebase.v1.AccessGrant.diff --git a/frontend/src/utils/accessGrant.ts b/frontend/src/utils/accessGrant.tsnew file mode 100644index 0000000000..5d514c108d--- /dev/null+++ b/frontend/src/utils/accessGrant.ts@@ -0,0 +1,59 @@+import { getTimeForPbTimestampProtoEs } from "@/types";+import {+ type AccessGrant,+ AccessGrant_Status,+} from "@/types/proto-es/v1/access_grant_service_pb";++export type AccessGrantDisplayStatus =+ | "ACTIVE"+ | "PENDING"+ | "EXPIRED"+ | "REVOKED"+ | "UNKNOWN";++export const getAccessGrantExpireTimeMs = (+ grant: AccessGrant+): number | undefined => {+ if (grant.expiration.case === "expireTime") {+ return getTimeForPbTimestampProtoEs(grant.expiration.value);+ }+ return undefined;+};++export const getAccessGrantDisplayStatus = (+ grant: AccessGrant+): AccessGrantDisplayStatus => {+ const expireMs = getAccessGrantExpireTimeMs(grant);+ if (+ grant.status === AccessGrant_Status.ACTIVE &&+ expireMs !== undefined &&+ expireMs < Date.now()+ ) {+ return "EXPIRED";+ }+ switch (grant.status) {+ case AccessGrant_Status.PENDING:+ return "PENDING";+ case AccessGrant_Status.ACTIVE:+ return "ACTIVE";+ case AccessGrant_Status.REVOKED:+ return "REVOKED";+ default:+ return "UNKNOWN";+ }+};++export const getAccessGrantStatusTagType = (+ status: AccessGrantDisplayStatus+): "success" | "warning" | "error" | "default" => {+ switch (status) {+ case "ACTIVE":+ return "success";+ case "PENDING":+ return "warning";+ case "REVOKED":+ return "error";+ default:+ return "default";+ }+};diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex dba74c5c42..0dedbf2fc7 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -25,5 +25,6 @@ export * from "./iam";export * from "./auto-route";export * from "./pagination";export * from "./expr";+export * from "./accessGrant";export * from "./storage-keys";export * from "./storage-migrate";diff --git a/frontend/src/utils/v1/issue/issue.ts b/frontend/src/utils/v1/issue/issue.tsindex 501e4c0115..bac78d932b 100644--- a/frontend/src/utils/v1/issue/issue.ts+++ b/frontend/src/utils/v1/issue/issue.ts@@ -49,6 +49,10 @@ export const isGrantRequestIssue = (issue: Issue): boolean => {return issue.type === Issue_Type.GRANT_REQUEST;};+export const isAccessGrantIssue = (issue: Issue): boolean => {+ return issue.type === Issue_Type.ACCESS_GRANT;+};+export const isDatabaseDataExportIssue = (issue: Issue): boolean => {return issue.type === Issue_Type.DATABASE_EXPORT;};diff --git a/frontend/src/utils/v1/worksheet.ts b/frontend/src/utils/v1/worksheet.tsindex 917d4a69b6..35c16f58b5 100644--- a/frontend/src/utils/v1/worksheet.ts+++ b/frontend/src/utils/v1/worksheet.ts@@ -16,7 +16,6 @@ import {getInstanceResource,hasProjectPermissionV2,hasWorkspacePermissionV2,- isDatabaseV1Queryable,} from "@/utils";export const extractWorksheetUID = (name: string) => {@@ -119,9 +118,6 @@ export const extractWorksheetConnection = async (worksheet: {const database = await useDatabaseV1Store().getOrFetchDatabaseByName(worksheet.database);- if (!isDatabaseV1Queryable(database)) {- return connection;- }const { instance } = extractDatabaseResourceName(database.name);connection.instance = instance;connection.database = database.name;diff --git a/frontend/src/views/DatabaseDetail/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail/DatabaseDetail.vueindex a672b40036..0e7e264e84 100644--- a/frontend/src/views/DatabaseDetail/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail/DatabaseDetail.vue@@ -79,7 +79,6 @@<span>{{ extractReleaseUID(database.release) }}</span></dd><SQLEditorButtonV1- v-if="allowQuery"class="text-sm md:mr-4":database="database":label="true"@@ -261,7 +260,6 @@ import {getDatabaseProject,getInstanceResource,instanceV1HasAlterSchema,- isDatabaseV1Queryable,PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE,} from "@/utils";import { extractReleaseUID } from "@/utils/v1/release";@@ -355,10 +353,6 @@ const hasSchemaDiagramFeature = computed((): boolean => {return instanceV1HasAlterSchema(getInstanceResource(database.value));});-const allowQuery = computed(() => {- return isDatabaseV1Queryable(database.value);-});-const tryTransferProject = () => {state.showTransferDatabaseModal = true;};diff --git a/frontend/src/views/project/IssueDetailV1View.vue b/frontend/src/views/project/IssueDetailV1View.vueindex bc58894379..afcadf3d83 100644--- a/frontend/src/views/project/IssueDetailV1View.vue+++ b/frontend/src/views/project/IssueDetailV1View.vue@@ -12,6 +12,9 @@<!-- Grant Request View --><GrantRequestView v-else-if="issueType === IssueType.GRANT_REQUEST" />+ <!-- Access Grant View -->+ <AccessGrantView v-else-if="issueType === IssueType.ACCESS_GRANT" />+<!-- Database Change View --><DatabaseChangeView v-else-if="issueType === IssueType.DATABASE_CHANGE" /></IssueBaseLayout>@@ -21,6 +24,7 @@import { computed, onMounted, ref } from "vue";import { BBSpin } from "@/bbkit";import { usePlanContextWithIssue } from "@/components/Plan";+import AccessGrantView from "@/components/Plan/components/IssueReviewView/AccessGrantView.vue";import { DatabaseChangeView } from "@/components/Plan/components/IssueReviewView/DatabaseChangeView";import DatabaseCreateView from "@/components/Plan/components/IssueReviewView/DatabaseCreateView.vue";import DatabaseExportView from "@/components/Plan/components/IssueReviewView/DatabaseExportView.vue";@@ -32,6 +36,7 @@ enum IssueType {CREATE_DATABASE = "CREATE_DATABASE",EXPORT_DATA = "EXPORT_DATA",GRANT_REQUEST = "GRANT_REQUEST",+ ACCESS_GRANT = "ACCESS_GRANT",DATABASE_CHANGE = "DATABASE_CHANGE",}@@ -46,6 +51,8 @@ const isLoading = ref(true);const issueType = computed(() => {if (issue.value.type === Issue_Type.GRANT_REQUEST)return IssueType.GRANT_REQUEST;+ if (issue.value.type === Issue_Type.ACCESS_GRANT)+ return IssueType.ACCESS_GRANT;const specs = plan.value.specs;if (specs.every((s) => s.config.case === "createDatabaseConfig"))diff --git a/frontend/src/views/project/ProjectAccessGrantDashboard.vue b/frontend/src/views/project/ProjectAccessGrantDashboard.vuenew file mode 100644index 0000000000..f248f9bfa8--- /dev/null+++ b/frontend/src/views/project/ProjectAccessGrantDashboard.vue@@ -0,0 +1,493 @@+<template>+ <div class="w-full flex flex-col gap-y-4">+ <FeatureAttention :feature="PlanFeature.FEATURE_JIT" />++ <ComponentPermissionGuard+ :project="project"+ :permissions="['bb.accessGrants.list']"+ >+ <div class="flex items-center gap-x-2">+ <AdvancedSearch+ class="flex-1"+ :params="searchParams"+ :scope-options="scopeOptions"+ :placeholder="$t('issue.advanced-search.filter')"+ :autofocus="false"+ :cache-query="true"+ @update:params="searchParams = $event"+ />+ </div>++ <PagedTable+ ref="pagedTableRef"+ :key="projectName"+ :session-key="`project-${projectName}-access-grants`"+ :fetch-list="fetchList"+ :order-keys="ORDER_KEYS"+ >+ <template #table="{ list, loading, sorters, onSortersUpdate }">+ <NDataTable+ v-if="hasJITFeature"+ :columns="getSortedColumns(sorters)"+ :data="list"+ :bordered="true"+ :striped="true"+ :loading="loading"+ :row-key="(row: AccessGrant) => row.name"+ @update:sorter="onSortersUpdate"+ />+ <NEmpty v-else class="py-12 border rounded-sm" />+ </template>+ </PagedTable>+ </ComponentPermissionGuard>++ <NAlert v-if="!canList" type="info">+ <i18n-t keypath="sql-editor.access-grants-redirect-hint" tag="span">+ <template #link>+ <router-link+ class="normal-link"+ :to="{+ name: 'sql-editor.project',+ params: { project: projectId },+ query: { panel: 'access' },+ }"+ >+ {{ $t("sql-editor.self") }}+ </router-link>+ </template>+ </i18n-t>+ </NAlert>+ </div>+</template>++<script setup lang="ts">+import type { DataTableColumn, DataTableSortState } from "naive-ui";+import {+ NAlert,+ NButton,+ NDataTable,+ NEmpty,+ NTag,+ NTooltip,+ useDialog,+} from "naive-ui";+import { computed, h, ref, type VNode, watch } from "vue";+import type { ComponentExposed } from "vue-component-type-helpers";+import { useI18n } from "vue-i18n";+import BBAvatar from "@/bbkit/BBAvatar.vue";+import AdvancedSearch from "@/components/AdvancedSearch";+import type {+ ScopeOption,+ ValueOption,+} from "@/components/AdvancedSearch/types";+import { FeatureAttention } from "@/components/FeatureGuard";+import YouTag from "@/components/misc/YouTag.vue";+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";+import { RichDatabaseName } from "@/components/v2";+import PagedTable from "@/components/v2/Model/PagedTable.vue";+import { mapSorterStatus } from "@/components/v2/Model/utils";+import {+ type AccessFilter,+ featureToRef,+ pushNotification,+ useAccessGrantStore,+ useCurrentUserV1,+ useDatabaseV1Store,+ useProjectByName,+ useUserStore,+} from "@/store";+import { extractUserEmail, projectNamePrefix } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs } from "@/types";+import {+ type AccessGrant,+ AccessGrant_Status,+} from "@/types/proto-es/v1/access_grant_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ extractDatabaseResourceName,+ getAccessGrantDisplayStatus,+ getAccessGrantStatusTagType,+ getDefaultPagination,+ hasProjectPermissionV2,+ type SearchParams,+} from "@/utils";+import {+ getValueFromSearchParams,+ getValuesFromSearchParams,+} from "@/utils/v1/advanced-search/common";++const PAGE_SIZE = getDefaultPagination();+const ORDER_KEYS = ["creator", "create_time"];++const props = defineProps<{+ projectId: string;+}>();++const { t } = useI18n();+const dialog = useDialog();+const me = useCurrentUserV1();+const userStore = useUserStore();+const databaseStore = useDatabaseV1Store();+const accessGrantStore = useAccessGrantStore();++const projectName = computed(() => `${projectNamePrefix}${props.projectId}`);+const { project } = useProjectByName(projectName);++const pagedTableRef = ref<ComponentExposed<typeof PagedTable<AccessGrant>>>();++const hasJITFeature = featureToRef(PlanFeature.FEATURE_JIT);+const canList = computed(() =>+ hasProjectPermissionV2(project.value, "bb.accessGrants.list")+);+const canActivate = computed(() =>+ hasProjectPermissionV2(project.value, "bb.accessGrants.activate")+);+const canRevoke = computed(() =>+ hasProjectPermissionV2(project.value, "bb.accessGrants.revoke")+);++const searchParams = ref<SearchParams>({+ query: "",+ scopes: [],+});++const scopeOptions = computed((): ScopeOption[] => [+ {+ id: "status",+ title: t("common.status"),+ options: [+ {+ value: AccessGrant_Status[AccessGrant_Status.ACTIVE],+ keywords: ["active"],+ render: () => t("common.active"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.PENDING],+ keywords: ["pending"],+ render: () => t("common.pending"),+ },+ {+ value: "EXPIRED",+ keywords: ["expired"],+ render: () => t("sql-editor.expired"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.REVOKED],+ keywords: ["revoked"],+ render: () => t("common.revoked"),+ },+ ],+ },+ {+ id: "creator",+ title: t("common.creator"),+ search: ({ keyword, nextPageToken: pageToken }) =>+ userStore+ .fetchUserList({+ pageToken,+ pageSize: PAGE_SIZE,+ filter: { query: keyword },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: resp.users.map<ValueOption>((user) => ({+ value: user.email,+ keywords: [user.email, user.title],+ render: () => {+ const children = [+ h(BBAvatar, { size: "TINY", username: user.title }),+ h("span", user.title),+ ];+ if (user.name === me.value.name) {+ children.push(h(YouTag));+ }+ return h("div", { class: "flex items-center gap-x-1" }, children);+ },+ })),+ })),+ },+ {+ id: "database",+ title: t("common.database"),+ search: ({ keyword, nextPageToken: pageToken }) =>+ databaseStore+ .fetchDatabases({+ parent: projectName.value,+ pageToken: pageToken,+ pageSize: PAGE_SIZE,+ filter: { query: keyword },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: resp.databases.map<ValueOption>((db) => {+ const { database: dbName } = extractDatabaseResourceName(db.name);+ return {+ value: db.name,+ keywords: [dbName, db.name],+ render: () =>+ h(RichDatabaseName, {+ database: db,+ showInstance: true,+ showEngineIcon: true,+ }),+ };+ }),+ })),+ },+]);++const statusMap: Record<string, AccessGrant_Status> = {+ ACTIVE: AccessGrant_Status.ACTIVE,+ PENDING: AccessGrant_Status.PENDING,+ REVOKED: AccessGrant_Status.REVOKED,+ EXPIRED: AccessGrant_Status.ACTIVE,+};++const filter = computed((): AccessFilter => {+ const f: AccessFilter = {};+ const statuses = getValuesFromSearchParams(searchParams.value, "status");+ if (statuses.length === 1) {+ f.status = statusMap[statuses[0]];+ if (statuses[0] === "EXPIRED") {+ f.expireTsBefore = Date.now();+ } else if (statuses[0] === "ACTIVE") {+ f.expireTsAfter = Date.now();+ }+ }+ const creator = getValueFromSearchParams(+ searchParams.value,+ "creator",+ undefined+ );+ if (creator) {+ f.creator = `users/${creator}`;+ }+ const database = getValueFromSearchParams(+ searchParams.value,+ "database",+ undefined+ );+ if (database) {+ f.target = database;+ }+ const queryText = searchParams.value.query.trim();+ if (queryText) {+ f.statement = queryText;+ }+ return f;+});++const fetchList = async ({+ pageToken,+ pageSize,+ orderBy,+}: {+ pageToken: string;+ pageSize: number;+ orderBy?: string;+}) => {+ const response = await accessGrantStore.listAccessGrants({+ parent: projectName.value,+ filter: filter.value,+ pageSize,+ pageToken: pageToken || undefined,+ orderBy: orderBy ?? "",+ });+ return {+ nextPageToken: response.nextPageToken,+ list: response.accessGrants,+ };+};++watch(+ () => JSON.stringify(filter.value),+ () => pagedTableRef.value?.refresh()+);++const getDatabaseNames = (targets: string[]) => {+ return targets.map((target) => {+ const match = target.match(/databases\/(.+)$/);+ return match ? match[1] : target;+ });+};++const handleActivate = (grant: AccessGrant) => {+ dialog.info({+ title: t("sql-editor.activate-access"),+ content: t("sql-editor.activate-confirm"),+ negativeText: t("common.cancel"),+ positiveText: t("sql-editor.activate-access"),+ onPositiveClick: async () => {+ await accessGrantStore.activateAccessGrant(grant.name);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.activated"),+ });+ pagedTableRef.value?.refresh();+ },+ });+};++const handleRevoke = (grant: AccessGrant) => {+ dialog.warning({+ title: t("sql-editor.revoke-access"),+ content: t("sql-editor.revoke-confirm"),+ negativeText: t("common.cancel"),+ positiveText: t("sql-editor.revoke-access"),+ onPositiveClick: async () => {+ await accessGrantStore.revokeAccessGrant(grant.name);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.revoked"),+ });+ pagedTableRef.value?.refresh();+ },+ });+};++const columns = computed((): DataTableColumn<AccessGrant>[] => [+ {+ key: "status",+ title: t("common.status"),+ width: 100,+ render: (grant) => {+ const status = getAccessGrantDisplayStatus(grant);+ return h(+ NTag,+ {+ type: getAccessGrantStatusTagType(status),+ size: "small",+ bordered: false,+ },+ { default: () => status }+ );+ },+ },+ {+ key: "creator",+ title: t("common.creator"),+ width: 180,+ ellipsis: true,+ render: (grant) => extractUserEmail(grant.creator),+ },+ {+ key: "create_time",+ title: t("common.created-at"),+ width: 180,+ render: (grant) => {+ if (!grant.createTime) return "-";+ const ms = getTimeForPbTimestampProtoEs(grant.createTime);+ return h("span", { class: "text-sm" }, new Date(ms).toLocaleString());+ },+ },+ {+ key: "query",+ title: t("common.statement"),+ ellipsis: true,+ render: (grant) =>+ h(+ NTooltip,+ {},+ {+ trigger: () => h("span", { class: "font-mono text-xs" }, grant.query),+ default: () =>+ h("pre", { class: "max-w-lg whitespace-pre-wrap" }, grant.query),+ }+ ),+ },+ {+ key: "targets",+ title: t("common.databases"),+ width: 200,+ render: (grant) => {+ const names = getDatabaseNames(grant.targets);+ if (names.length === 0) return "-";+ const display =+ names.length <= 2+ ? names.join(", ")+ : `${names.slice(0, 2).join(", ")} +${names.length - 2}`;+ if (names.length <= 2) {+ return h("span", { class: "text-sm" }, display);+ }+ return h(+ NTooltip,+ {},+ {+ trigger: () => h("span", { class: "text-sm" }, display),+ default: () =>+ h(+ "div",+ { class: "flex flex-col" },+ names.map((name) => h("span", { key: name }, name))+ ),+ }+ );+ },+ },+ {+ key: "actions",+ title: "",+ width: 160,+ render: (grant) => {+ const buttons: VNode[] = [];+ const status = getAccessGrantDisplayStatus(grant);+ if (status === "REVOKED" && canActivate.value) {+ buttons.push(+ h(+ NButton,+ {+ tertiary: true,+ size: "tiny",+ type: "primary",+ onClick: () => handleActivate(grant),+ },+ () => t("sql-editor.activate-access")+ )+ );+ }+ if (status === "ACTIVE" && canRevoke.value) {+ buttons.push(+ h(+ NButton,+ {+ tertiary: true,+ size: "tiny",+ type: "error",+ onClick: () => handleRevoke(grant),+ },+ () => t("sql-editor.revoke-access")+ )+ );+ }+ if (grant.issue) {+ const issuePath = grant.issue.startsWith("/")+ ? grant.issue+ : `/${grant.issue}`;+ buttons.push(+ h(+ "a",+ {+ href: issuePath,+ target: "_blank",+ onClick: (e: Event) => e.stopPropagation(),+ },+ h(NButton, { tertiary: true, size: "tiny" }, () =>+ t("sql-editor.view-issue")+ )+ )+ );+ }+ return h(+ "div",+ { class: "flex items-center justify-end gap-x-1" },+ buttons+ );+ },+ },+]);++const getSortedColumns = (sorters: DataTableSortState[]) =>+ mapSorterStatus(columns.value, sorters);+</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vuenew file mode 100644index 0000000000..0aefa5b413--- /dev/null+++ b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantItem.vue@@ -0,0 +1,176 @@+<template>+ <div+ class="w-full p-2 gap-y-2 border-b flex flex-col justify-start items-start cursor-pointer hover:bg-gray-50"+ :class="highlight ? 'highlight-pulse' : 'transition-colors duration-1000'"+ >+ <div class="w-full flex flex-row justify-between items-center gap-x-2">+ <div class="flex items-center gap-x-1">+ <NTag :type="statusTagType" size="tiny" :bordered="false" round>+ {{ statusLabel }}+ </NTag>+ <NTag v-if="grant.unmask" size="tiny" :bordered="false" round>+ {{ $t("sql-editor.grant-type-unmask") }}+ </NTag>+ </div>+ <span class="text-xs text-gray-500 shrink-0">+ {{ expirationText }}+ </span>+ </div>++ <NTooltip placement="right">+ <template #trigger>+ <p+ class="max-w-full text-xs wrap-break-word whitespace-pre-wrap font-mono line-clamp-2"+ :class="{ 'line-through text-gray-400': isExpired || isRevoked }"+ >+ {{ grant.query }}+ </p>+ </template>+ <pre class="max-w-lg whitespace-pre-wrap text-xs">{{ grant.query }}</pre>+ </NTooltip>++ <div class="w-full flex flex-col gap-y-2">+ <NTooltip :disabled="allDatabaseNames.length <= 2" placement="right">+ <template #trigger>+ <span class="text-xs text-gray-400 truncate">+ {{ databaseNamesDisplay }}+ </span>+ </template>+ <div class="flex flex-col">+ <span v-for="name in allDatabaseNames" :key="name">{{ name }}</span>+ </div>+ </NTooltip>+ <div class="flex items-center gap-x-1">+ <NButton+ v-if="isActive && !isExpired"+ tertiary+ size="tiny"+ type="primary"+ @click.stop="$emit('run', grant)"+ >+ {{ $t("common.run") }}+ </NButton>+ <NButton+ v-if="grant.issue"+ tertiary+ size="tiny"+ tag="a"+ :href="issueLink"+ target="_blank"+ @click.stop+ >+ {{ $t("sql-editor.view-issue") }}+ </NButton>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { NButton, NTag, NTooltip } from "naive-ui";+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import {+ type AccessGrant,+ AccessGrant_Status,+} from "@/types/proto-es/v1/access_grant_service_pb";+import {+ getAccessGrantDisplayStatus,+ getAccessGrantExpireTimeMs,+ getAccessGrantStatusTagType,+} from "@/utils/accessGrant";++const props = defineProps<{+ grant: AccessGrant;+ highlight?: boolean;+}>();++defineEmits<{+ (e: "run", grant: AccessGrant): void;+}>();++const { t } = useI18n();++const isActive = computed(+ () => props.grant.status === AccessGrant_Status.ACTIVE+);++const isRevoked = computed(+ () => props.grant.status === AccessGrant_Status.REVOKED+);++const expireTimeMs = computed(() => getAccessGrantExpireTimeMs(props.grant));++const isExpired = computed(() => {+ if (!isActive.value || expireTimeMs.value === undefined) return false;+ return expireTimeMs.value < Date.now();+});++const displayStatus = computed(() => getAccessGrantDisplayStatus(props.grant));++const statusTagType = computed(() =>+ getAccessGrantStatusTagType(displayStatus.value)+);++const statusLabel = computed(() => {+ return displayStatus.value;+});++const expirationText = computed(() => {+ if (expireTimeMs.value === undefined) return "";+ const dateStr = new Date(expireTimeMs.value).toLocaleString();+ if (isActive.value && !isExpired.value) {+ const diff = expireTimeMs.value - Date.now();+ const hours = Math.floor(diff / (1000 * 60 * 60));+ if (hours >= 24) {+ return t("sql-editor.expire-at", { time: dateStr });+ }+ const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));+ const duration = hours > 0 ? `${hours}h${minutes}m` : `${minutes}m`;+ return t("sql-editor.expire-in", { time: duration });+ }+ return t("sql-editor.expire-at", { time: dateStr });+});++const allDatabaseNames = computed(() => {+ return props.grant.targets.map((t) => {+ const match = t.match(/databases\/(.+)$/);+ return match ? match[1] : t;+ });+});++const databaseNamesDisplay = computed(() => {+ const names = allDatabaseNames.value;+ if (names.length <= 2) {+ return names.join(", ");+ }+ return `${names.slice(0, 2).join(", ")} ${t("sql-editor.and-n-more-databases", { n: names.length - 2 })}`;+});++const issueLink = computed(() => {+ if (!props.grant.issue) return "";+ let path = props.grant.issue;+ if (!path.startsWith("/")) {+ path = `/${path}`;+ }+ return path;+});+</script>++<style scoped>+.highlight-pulse {+ animation: highlight-fade 3s ease-in-out;+}++@keyframes highlight-fade {+ 0% {+ background-color: rgb(219 234 254); /* bg-blue-100 */+ }+ 60% {+ background-color: rgb(219 234 254);+ }+ 100% {+ background-color: transparent;+ }+}+</style>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vuenew file mode 100644index 0000000000..25eb6f39bf--- /dev/null+++ b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue@@ -0,0 +1,256 @@+<template>+ <Drawer+ :show="true"+ width="auto"+ @update:show="(show: boolean) => !show && $emit('close')"+ >+ <DrawerContent+ :title="$t('sql-editor.request-data-access')"+ :closable="true"+ class="w-[40rem] max-w-[100vw]"+ >+ <div class="flex flex-col gap-y-6">+ <div class="flex flex-col gap-y-2">+ <div class="text-sm font-medium text-control">+ {{ $t("common.databases") }}+ <RequiredStar class="ml-0.5" />+ </div>+ <DatabaseSelect+ :value="form.targets"+ :project-name="editorStore.project"+ :multiple="true"+ @update:value="+ (val) => (form.targets = (val as string[] | undefined) ?? [])+ "+ />+ </div>++ <div class="flex flex-col gap-y-2">+ <div class="text-sm font-medium text-control">+ {{ $t("common.statement") }}+ <RequiredStar class="ml-0.5" />+ </div>+ <MonacoEditor+ class="border rounded-[3px] h-40"+ :content="form.query"+ language="sql"+ :auto-complete-context="autoCompleteContext"+ @update:content="form.query = $event"+ />+ </div>++ <div class="flex flex-col gap-y-2">+ <div class="text-sm font-medium text-control">+ {{ $t("sql-editor.grant-type-unmask") }}+ </div>+ <div class="flex flex-col gap-y-1">+ <NCheckbox v-model:checked="form.unmask">+ {{ $t("sql-editor.access-type-unmask") }}+ </NCheckbox>+ </div>+ </div>++ <div class="flex flex-col gap-y-2">+ <div class="text-sm font-medium text-control">+ {{ $t("common.duration") }}+ <RequiredStar class="ml-0.5" />+ </div>+ <NSelect+ v-model:value="form.duration"+ :options="durationOptions"+ />+ <NDatePicker+ v-if="form.duration === -1"+ v-model:value="form.customExpireTime"+ type="datetime"+ :is-date-disabled="isDateDisabled"+ clearable+ />+ </div>++ <div class="flex flex-col gap-y-2">+ <div class="text-sm font-medium text-control">+ {{ $t("common.reason") }}+ </div>+ <NInput+ v-model:value="form.reason"+ type="textarea"+ :rows="3"+ :placeholder="$t('common.optional')"+ />+ </div>+ </div>++ <template #footer>+ <div class="flex items-center justify-end gap-x-2">+ <NButton @click="$emit('close')">+ {{ $t("common.cancel") }}+ </NButton>+ <NButton+ type="primary"+ :disabled="!allowSubmit"+ :loading="isRequesting"+ @click="handleSubmit"+ >+ {{ $t("common.submit") }}+ </NButton>+ </div>+ </template>+ </DrawerContent>+ </Drawer>+</template>++<script lang="ts" setup>+import { create } from "@bufbuild/protobuf";+import { DurationSchema } from "@bufbuild/protobuf/wkt";+import { NButton, NCheckbox, NDatePicker, NInput, NSelect } from "naive-ui";+import { computed, reactive, ref } from "vue";+import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";+import { MonacoEditor } from "@/components/MonacoEditor";+import RequiredStar from "@/components/RequiredStar.vue";+import { DatabaseSelect, Drawer, DrawerContent } from "@/components/v2";+import { accessGrantServiceClientConnect } from "@/connect";+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";+import {+ pushNotification,+ useCurrentUserV1,+ useSQLEditorStore,+ useSQLEditorTabStore,+} from "@/store";+import {+ AccessGrant_Status,+ AccessGrantSchema,+ CreateAccessGrantRequestSchema,+} from "@/types/proto-es/v1/access_grant_service_pb";+import {+ extractDatabaseResourceName,+ extractIssueUID,+ extractProjectResourceName,+} from "@/utils";+import { useSQLEditorContext } from "../../context";++const props = withDefaults(+ defineProps<{+ // Pre-selected database resource names.+ // Format: "instances/{instance}/databases/{database}"+ targets?: string[];+ // Pre-filled SQL statement.+ query?: string;+ // Pre-check the "Unmask" access type checkbox.+ unmask?: boolean;+ }>(),+ {+ targets: undefined,+ query: "",+ unmask: false,+ }+);++const emit = defineEmits<{+ (event: "close"): void;+}>();++const { t } = useI18n();+const router = useRouter();+const currentUser = useCurrentUserV1();+const editorStore = useSQLEditorStore();+const tabStore = useSQLEditorTabStore();+const isRequesting = ref(false);+const { asidePanelTab, highlightAccessGrantName } = useSQLEditorContext();++// Default to the currently connected database if no targets provided.+const defaultTargets = computed(() => {+ if (props.targets) return props.targets;+ const database = tabStore.currentTab?.connection?.database;+ return database ? [database] : [];+});++const form = reactive({+ targets: [...defaultTargets.value],+ query: props.query,+ unmask: props.unmask,+ duration: 4,+ customExpireTime: undefined as number | undefined,+ reason: "",+});++const autoCompleteContext = computed(() => {+ const db = form.targets[0];+ if (!db) return undefined;+ const { instance } = extractDatabaseResourceName(db);+ return { instance, database: db };+});++const durationOptions = computed(() => [+ { label: t("sql-editor.duration-hours", { hours: 1 }), value: 1 },+ { label: t("sql-editor.duration-hours", { hours: 4 }), value: 4 },+ { label: t("sql-editor.duration-day", { days: 1 }), value: 24 },+ { label: t("sql-editor.duration-days", { days: 7 }), value: 168 },+ { label: t("common.custom"), value: -1 },+]);++const isDateDisabled = (ts: number) => {+ return ts < Date.now();+};++const allowSubmit = computed(() => {+ if (form.targets.length === 0) return false;+ if (!form.query.trim()) return false;+ if (form.duration === -1 && !form.customExpireTime) return false;+ return true;+});++const handleSubmit = async () => {+ if (isRequesting.value) return;+ isRequesting.value = true;+ try {+ const ttlSeconds =+ form.duration === -1+ ? BigInt(Math.floor((form.customExpireTime! - Date.now()) / 1000))+ : BigInt(form.duration * 3600);++ const accessGrant = create(AccessGrantSchema, {+ creator: `users/${currentUser.value.email}`,+ targets: form.targets,+ query: form.query,+ unmask: form.unmask,+ reason: form.reason,+ expiration: {+ case: "ttl",+ value: create(DurationSchema, { seconds: ttlSeconds }),+ },+ });++ const response = await accessGrantServiceClientConnect.createAccessGrant(+ create(CreateAccessGrantRequestSchema, {+ parent: editorStore.project,+ accessGrant,+ })+ );++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });++ if (response.status === AccessGrant_Status.PENDING && response.issue) {+ const route = router.resolve({+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,+ params: {+ projectId: extractProjectResourceName(response.issue),+ issueId: extractIssueUID(response.issue),+ },+ });+ window.open(route.fullPath, "_blank");+ } else {+ asidePanelTab.value = "ACCESS";+ highlightAccessGrantName.value = response.name;+ }+ emit("close");+ } finally {+ isRequesting.value = false;+ }+};+</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vue b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vuenew file mode 100644index 0000000000..c74f8ce88b--- /dev/null+++ b/frontend/src/views/sql-editor/AsidePanel/AccessPane/AccessPane.vue@@ -0,0 +1,329 @@+<template>+ <div class="relative w-full h-full flex flex-col justify-start items-start gap-y-1">+ <div+ ref="containerRef"+ class="w-full px-1 flex flex-wrap items-center gap-x-2 gap-y-1"+ >+ <AdvancedSearch+ class="flex-1"+ :class="useSmallLayout ? 'min-w-full' : ''"+ :size="'small'"+ :params="searchParams"+ :scope-options="scopeOptions"+ :placeholder="$t('issue.advanced-search.filter')"+ :autofocus="false"+ :cache-query="false"+ @update:params="searchParams = $event"+ />+ <NButton+ ghost+ size="small"+ type="primary"+ :style="{+ width: useSmallLayout ? '100%' : 'auto'+ }"+ :disabled="!hasJITFeature"+ @click="showDrawer = true"+ >+ <template v-if="!hasJITFeature" #icon>+ <FeatureBadge :clickable="false" :feature="PlanFeature.FEATURE_JIT" />+ </template>+ {{ $t("sql-editor.request-access") }}+ </NButton>+ </div>+ <div class="w-full flex flex-col justify-start items-start overflow-y-auto">+ <AccessGrantItem+ v-for="grant in accessGrantList"+ :key="grant.name"+ :grant="grant"+ :highlight="grant.name === highlightAccessGrantName"+ @run="handleRun"+ />+ <div+ v-if="nextPageToken"+ class="w-full flex flex-col items-center my-2"+ >+ <NButton+ quaternary+ size="small"+ :loading="loading"+ @click="fetchAccessGrants(false)"+ >+ <span class="textinfolabel">+ {{ $t("common.load-more") }}+ </span>+ </NButton>+ </div>+ </div>++ <template v-if="accessGrantList.length === 0">+ <MaskSpinner v-if="loading" class="bg-white/75!" />+ <div+ v-else+ class="w-full flex items-center justify-center py-8 textinfolabel"+ >+ {{ $t("sql-editor.no-access-requests") }}+ </div>+ </template>++ <AccessGrantRequestDrawer+ v-if="showDrawer"+ @close="handleDrawerClose"+ />+ </div>+</template>++<script lang="ts" setup>+import { useElementSize } from "@vueuse/core";+import { NButton } from "naive-ui";+import { computed, h, nextTick, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import AdvancedSearch from "@/components/AdvancedSearch";+import type {+ ScopeOption,+ ValueOption,+} from "@/components/AdvancedSearch/types";+import { FeatureBadge } from "@/components/FeatureGuard";+import MaskSpinner from "@/components/misc/MaskSpinner.vue";+import { RichDatabaseName } from "@/components/v2";+import { useExecuteSQL } from "@/composables/useExecuteSQL";+import {+ type AccessFilter,+ hasFeature,+ useAccessGrantStore,+ useConnectionOfCurrentSQLEditorTab,+ useDatabaseV1Store,+ useSQLEditorStore,+ useSQLEditorTabStore,+} from "@/store";+import {+ type AccessGrant,+ AccessGrant_Status,+} from "@/types/proto-es/v1/access_grant_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ extractDatabaseResourceName,+ getDefaultPagination,+ type SearchParams,+} from "@/utils";+import {+ getValueFromSearchParams,+ getValuesFromSearchParams,+} from "@/utils/v1/advanced-search/common";+import { useSQLEditorContext } from "../../context";+import AccessGrantItem from "./AccessGrantItem.vue";+import AccessGrantRequestDrawer from "./AccessGrantRequestDrawer.vue";++const PAGE_SIZE = getDefaultPagination();++const { t } = useI18n();+const editorStore = useSQLEditorStore();+const tabStore = useSQLEditorTabStore();+const databaseStore = useDatabaseV1Store();+const accessGrantStore = useAccessGrantStore();+const { instance: currentInstance } = useConnectionOfCurrentSQLEditorTab();+const { execute } = useExecuteSQL();+const { highlightAccessGrantName } = useSQLEditorContext();++const showDrawer = ref(false);+const loading = ref(false);+const accessGrantList = ref<AccessGrant[]>([]);+const nextPageToken = ref("");+const containerRef = ref<HTMLDivElement>();+const { width: containerWidth } = useElementSize(containerRef);+const useSmallLayout = computed(+ () => containerWidth.value > 0 && containerWidth.value < 250+);++const hasJITFeature = computed(() => hasFeature(PlanFeature.FEATURE_JIT));++const searchParams = ref<SearchParams>({+ query: "",+ scopes: [],+});++const scopeOptions = computed((): ScopeOption[] => {+ const options: ScopeOption[] = [+ {+ id: "status",+ title: t("common.status"),+ allowMultiple: true,+ options: [+ {+ value: AccessGrant_Status[AccessGrant_Status.ACTIVE],+ keywords: ["active"],+ render: () => t("common.active"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.PENDING],+ keywords: ["pending"],+ render: () => t("common.pending"),+ },+ {+ value: "EXPIRED",+ keywords: ["expired"],+ render: () => t("sql-editor.expired"),+ },+ {+ value: AccessGrant_Status[AccessGrant_Status.REVOKED],+ keywords: ["revoked"],+ render: () => t("common.revoked"),+ },+ ],+ },+ ];+ const project = editorStore.project;+ if (project) {+ options.push({+ id: "database",+ title: t("common.database"),+ search: ({ keyword, nextPageToken: pageToken }) =>+ databaseStore+ .fetchDatabases({+ parent: project,+ pageToken: pageToken,+ pageSize: PAGE_SIZE,+ filter: { query: keyword },+ })+ .then((resp) => ({+ nextPageToken: resp.nextPageToken,+ options: resp.databases.map<ValueOption>((db) => {+ const { database: dbName } = extractDatabaseResourceName(db.name);+ return {+ value: db.name,+ keywords: [dbName, db.name],+ render: () =>+ h(RichDatabaseName, {+ database: db,+ showInstance: true,+ showEngineIcon: true,+ }),+ };+ }),+ })),+ });+ }+ return options;+});++const selectedStatuses = computed(() =>+ getValuesFromSearchParams(searchParams.value, "status")+);++const statusMap: Record<string, AccessGrant_Status> = {+ ACTIVE: AccessGrant_Status.ACTIVE,+ PENDING: AccessGrant_Status.PENDING,+ REVOKED: AccessGrant_Status.REVOKED,+ EXPIRED: AccessGrant_Status.ACTIVE,+};++// Build AccessFilter from search params.+const filter = computed((): AccessFilter => {+ const f: AccessFilter = {};++ const statuses = selectedStatuses.value;+ if (statuses.length === 1) {+ f.status = statusMap[statuses[0]];+ if (statuses[0] === "EXPIRED") {+ f.expireTsBefore = Date.now();+ } else if (statuses[0] === "ACTIVE") {+ f.expireTsAfter = Date.now();+ }+ }++ const database = getValueFromSearchParams(+ searchParams.value,+ "database",+ undefined+ );+ if (database) {+ f.target = database;+ }++ const queryText = searchParams.value.query.trim();+ if (queryText) {+ f.statement = queryText;+ }++ return f;+});++const fetchAccessGrants = async (resetList = true) => {+ const project = editorStore.project;+ if (!project) return;++ loading.value = true;+ try {+ const response = await accessGrantStore.searchMyAccessGrants({+ parent: project,+ filter: filter.value,+ pageSize: PAGE_SIZE,+ pageToken: resetList ? undefined : nextPageToken.value,+ });+ if (resetList) {+ accessGrantList.value = response.accessGrants;+ } else {+ accessGrantList.value.push(...response.accessGrants);+ }+ nextPageToken.value = response.nextPageToken;+ } finally {+ loading.value = false;+ }+};++// Re-fetch when project or filter changes.+watch([() => editorStore.project, filter], () => fetchAccessGrants(), {+ immediate: true,+ deep: true,+});++// When a new grant is highlighted (e.g. created from the drawer in other panels),+// refresh the list so it appears, then auto-clear the highlight after 3 seconds.+watch(+ highlightAccessGrantName,+ async (name) => {+ if (name) {+ await fetchAccessGrants();+ setTimeout(() => {+ if (highlightAccessGrantName.value === name) {+ highlightAccessGrantName.value = undefined;+ }+ }, 3000);+ }+ },+ { immediate: true }+);++const handleDrawerClose = () => {+ showDrawer.value = false;+ fetchAccessGrants();+};++const handleRun = async (grant: AccessGrant) => {+ const database = grant.targets[0] ?? "";+ const instanceName = database.replace(/\/databases\/.*$/, "");+ // Pre-fetch the database so the connection is fully resolved+ // before the tab is created and the query is executed.+ await useDatabaseV1Store().getOrFetchDatabaseByName(database);+ const tab = tabStore.addTab(+ {+ connection: { instance: instanceName, database },+ statement: grant.query,+ batchQueryContext: {+ databases: grant.targets,+ },+ },+ /* beside */ true+ );+ nextTick(() => {+ execute({+ connection: { ...tab.connection },+ statement: grant.query,+ engine: currentInstance.value.engine,+ explain: false,+ selection: null,+ accessGrant: grant.name,+ });+ });+};+</script>diff --git a/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.tsnew file mode 100644index 0000000000..59368ea352--- /dev/null+++ b/frontend/src/views/sql-editor/AsidePanel/AccessPane/index.ts@@ -0,0 +1,3 @@+import AccessPane from "./AccessPane.vue";++export default AccessPane;diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vueindex 4450410fc1..f83733320f 100644--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue@@ -55,6 +55,7 @@<WorksheetPane v-if="asidePanelTab === 'WORKSHEET'" /><SchemaPane v-if="asidePanelTab === 'SCHEMA'" /><HistoryPane v-if="asidePanelTab === 'HISTORY'" />+ <AccessPane v-if="asidePanelTab === 'ACCESS'" /></div></div></div>@@ -71,6 +72,7 @@ import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";import { defaultProject, isValidProjectName } from "@/types";import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";import { useSQLEditorContext } from "../context";+import AccessPane from "./AccessPane";import ActionBar from "./ActionBar";import GutterBar from "./GutterBar";import HistoryPane from "./HistoryPane";diff --git a/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue b/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vueindex aed6f2998c..9b5b88e8fc 100644--- a/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue+++ b/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue@@ -7,7 +7,7 @@<div class="flex flex-col justify-center items-center pb-1"><router-link target="_blank" rel="noopener noreferrer" :to="linkTarget"><img- class="w-[36px] h-auto"+ class="w-9 h-auto"src="@/assets/logo-icon.svg"alt="Bytebase"/>@@ -21,6 +21,7 @@/><TabItem tab="SCHEMA" :size="size" @click="handleClickTab('SCHEMA')" /><TabItem tab="HISTORY" :size="size" @click="handleClickTab('HISTORY')" />+ <TabItem v-if="project.allowJustInTimeAccess" tab="ACCESS" :size="size" @click="handleClickTab('ACCESS')" /></div><div class="flex flex-col justify-end items-center"></div>@@ -32,6 +33,7 @@ import { computed } from "vue";import { useRoute } from "vue-router";import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";+import { useProjectV1Store, useSQLEditorStore } from "@/store";import { type AsidePanelTab, useSQLEditorContext } from "../../context";import { type Size } from "./common";import TabItem from "./TabItem.vue";@@ -47,6 +49,12 @@ withDefaults(const route = useRoute();const { asidePanelTab } = useSQLEditorContext();+const editorStore = useSQLEditorStore();+const projectStore = useProjectV1Store();++const project = computed(() =>+ projectStore.getProjectByName(editorStore.project)+);const linkTarget = computed(() => {// If we have a project in the route, navigate to that project's detail pagediff --git a/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue b/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vueindex ccdc31b93e..57025ae39a 100644--- a/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue+++ b/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue@@ -6,6 +6,7 @@<FileCodeIcon v-if="tab === 'WORKSHEET'" /><DatabaseIcon v-else-if="tab === 'SCHEMA'" /><HistoryIcon v-else-if="tab === 'HISTORY'" />+ <ShieldCheckIcon v-else-if="tab === 'ACCESS'" /></template></NButton></template>@@ -16,7 +17,7 @@</template><script setup lang="ts">-import { FileCodeIcon, HistoryIcon } from "lucide-vue-next";+import { FileCodeIcon, HistoryIcon, ShieldCheckIcon } from "lucide-vue-next";import { NButton, NTooltip } from "naive-ui";import { computed, toRef } from "vue";import { useI18n } from "vue-i18n";@@ -47,6 +48,8 @@ const text = computed(() => {return t("worksheet.self");case "HISTORY":return t("common.history");+ case "ACCESS":+ return t("sql-editor.jit");}console.assert(false, "should never reach this line");return "";diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vueindex 37cd9ad2b3..63dfdda019 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue@@ -254,7 +254,6 @@ import {getConnectionForSQLEditorTab,getValueFromSearchParams,getValuesFromSearchParams,- isDatabaseV1Queryable,storageKeySqlEditorShowMissingQueryDb,useDynamicLocalStorage,} from "@/utils";@@ -391,23 +390,17 @@ const onBatchQueryContextChange = async (};const getQueryableDatabase = async (batchQueryContext: BatchQueryContext) => {- for (const databaseName of batchQueryContext.databases) {- const database = databaseStore.getDatabaseByName(databaseName);- if (isDatabaseV1Queryable(database)) {- return database;- }+ if (batchQueryContext.databases.length > 0) {+ return databaseStore.getDatabaseByName(batchQueryContext.databases[0]);}for (const databaseGroupName of batchQueryContext.databaseGroups ?? []) {const databaseGroup = dbGroupStore.getDBGroupByName(databaseGroupName);- await databaseStore.batchGetOrFetchDatabases(+ const databases = await databaseStore.batchGetOrFetchDatabases(databaseGroup.matchedDatabases.map((db) => db.name));- for (const matchedDatabase of databaseGroup.matchedDatabases) {- const database = databaseStore.getDatabaseByName(matchedDatabase.name);- if (isDatabaseV1Queryable(database)) {- return database;- }+ if (databases.length > 0) {+ return databases[0];}}};@@ -607,9 +600,6 @@ const connect = (node: SQLEditorTreeNode) => {return;}const database = node.meta.target as Database;- if (!isDatabaseV1Queryable(database)) {- return;- }const batchQueryDatabases = [...selectedDatabaseGroupNames.value,@@ -642,11 +632,6 @@ const renderLabel = ({ option }: { option: TreeOption }) => {checkTooltip = t("sql-editor.matched-in-group", { title: checkedByGroup });} else if (tabStore.currentTab?.connection.database === databaseName) {checkTooltip = t("sql-editor.current-connection");- } else if (databaseName) {- const database = (node as SQLEditorTreeNode<"database">).meta.target;- if (!isDatabaseV1Queryable(database)) {- checkTooltip = t("sql-editor.database-not-queriable");- }}return h(Label, {diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vueindex 6cfedac354..3f0176ca50 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue@@ -5,7 +5,7 @@<NCheckboxclass="mr-2":checked="checked"- :disabled="checkDisabled || !canQuery"+ :disabled="checkDisabled"@click.stop.prevent=""@update:checked="$emit('update:checked', $event)"/>@@ -25,9 +25,10 @@/><RequestQueryButton- v-if="showRequestQueryButton"+ v-if="!canQuery"class="ml-auto":text="true"+ :prefer-jit="false":permission-denied-detail="create(PermissionDeniedDetailSchema, {resources: [database.name],requiredPermissions: ['bb.sql.select']@@ -68,8 +69,4 @@ const database = computed();const canQuery = computed(() => isDatabaseV1Queryable(database.value));--const showRequestQueryButton = computed(() => {- return !canQuery.value;-});</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/DataTable/SensitiveDataIcon.vue b/frontend/src/views/sql-editor/EditorCommon/DataTable/SensitiveDataIcon.vuedeleted file mode 100644index 2f83aba0e9..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/DataTable/SensitiveDataIcon.vue+++ /dev/null@@ -1,40 +0,0 @@-<template>- <NTooltip :animated="false" :delay="250">- <template #trigger>- <heroicons-outline:eye-slash- class="w-[12px] h-[12px] -mb-[2px]"- :class="[clickable && 'cursor-pointer']"- v-bind="$attrs"- @click="handleClick"- />- </template>-- <span class="whitespace-nowrap">- {{ $t("sensitive-data.self") }}- </span>- </NTooltip>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useRouter } from "vue-router";-import { WORKSPACE_ROUTE_GLOBAL_MASKING } from "@/router/dashboard/workspaceRoutes";-import { hasWorkspacePermissionV2 } from "@/utils";--const router = useRouter();--const clickable = computed(() => {- return hasWorkspacePermissionV2("bb.policies.update");-});--const handleClick = () => {- if (!clickable.value) {- return;- }- const url = router.resolve({- name: WORKSPACE_ROUTE_GLOBAL_MASKING,- });- window.open(url.href, "_BLANK");-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/DataTable/index.ts b/frontend/src/views/sql-editor/EditorCommon/DataTable/index.tsdeleted file mode 100644index f025066b16..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/DataTable/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import SensitiveDataIcon from "./SensitiveDataIcon.vue";--export { SensitiveDataIcon };diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex 722aaf43b0..6701920cea 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -168,11 +168,7 @@ import {} from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- isDatabaseV1Queryable,- isWorksheetWritableV1,- keyboardShortcutStr,-} from "@/utils";+import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";import { useSQLEditorContext } from "../context";import AdminModeButton from "./AdminModeButton.vue";import ContainerChooser from "./ContainerChooser.vue";@@ -210,7 +206,7 @@ const isEmptyStatement = computed(() => {}return tab.statement === "";});-const { instance, database } = useConnectionOfCurrentSQLEditorTab();+const { instance } = useConnectionOfCurrentSQLEditorTab();const { t } = useI18n();const showSheetsFeature = computed(() => {@@ -236,7 +232,7 @@ const allowQuery = computed(() => {return !!currentTab.value?.connection.table;}- return isDatabaseV1Queryable(database.value);+ return true;});const canWriteSheet = computed(() => {diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vueindex 0025b74963..08e79a51be 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue@@ -50,7 +50,7 @@v-bind="tableResize.getColumnProps(columnIndex + 1)"@click="e => handleSelectColumn(e, columnIndex)">- <div class="flex items-center overflow-hidden">+ <div class="flex items-center overflow-hidden gap-x-1"><span class="flex flex-row items-center select-none"><templatev-if="String(header.name).length > 0"@@ -63,11 +63,9 @@<MaskingReasonPopoverv-if="getMaskingReason && getMaskingReason(columnIndex)":reason="getMaskingReason(columnIndex)!"- class="ml-0.5 shrink-0"- />- <SensitiveDataIcon- v-else-if="isSensitiveColumn(columnIndex)"- class="ml-0.5 shrink-0"+ :statement="statement"+ :database="database.name"+ class="shrink-0"/><ColumnSortedIcon@@ -222,7 +220,6 @@ import {} from "./common/binary-format-store";import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";import MaskingReasonPopover from "./common/MaskingReasonPopover.vue";-import SensitiveDataIcon from "./common/SensitiveDataIcon.vue";import { useSelectionContext } from "./common/selection-logic";import type {ResultTableColumn,@@ -241,6 +238,7 @@ const props = defineProps<{isSensitiveColumn: (index: number) => boolean;getMaskingReason?: (index: number) => MaskingReason | undefined;database: Database;+ statement?: string;sortState?: SortState;search: SearchParams;}>();diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vueindex 131fba0181..e504d59c20 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vue@@ -1,5 +1,5 @@<template>- <span class="w-4 h-auto opacity-80 ml-1 shrink-0">+ <span class="w-4 h-auto opacity-80 shrink-0"><ArrowDownWideNarrowv-if="!isSorted || isSorted === 'desc'"class="w-full h-auto"diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vueindex b2c6cfb278..532cd5c326 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/MaskingReasonPopover.vue@@ -9,7 +9,7 @@class="w-3 h-3 object-contain"alt=""/>- <heroicons:eye-slash+ <EyeOffIconclass="w-3 h-3 cursor-pointer text-gray-500 hover:text-gray-700"@click="handleClick"/>@@ -49,17 +49,43 @@><span class="ml-1">{{ props.reason.classificationLevel }}</span></div>++ <div v-if="hasJITFeature && statement" class="mb-2">+ <NButton+ size="small"+ type="primary"+ tertiary+ @click="showDrawer = true"+ >+ {{ $t("sql-editor.request-jit") }}+ </NButton>+ </div></div></NPopover>++ <AccessGrantRequestDrawer+ v-if="showDrawer"+ :query="statement"+ :targets="targets"+ :unmask="true"+ @close="showDrawer = false"+ /></template><script setup lang="ts">-import { NPopover } from "naive-ui";+import { EyeOffIcon } from "lucide-vue-next";+import { NButton, NPopover } from "naive-ui";+import { computed, ref } from "vue";import { useI18n } from "vue-i18n";+import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import AccessGrantRequestDrawer from "@/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue";const props = defineProps<{reason: MaskingReason;+ statement?: string;+ database?: string;}>();const emit = defineEmits<{@@ -67,14 +93,26 @@ const emit = defineEmits<{}>();const { t } = useI18n();+const showDrawer = ref(false);+const editorStore = useSQLEditorStore();+const projectStore = useProjectV1Store();++const project = computed(() =>+ projectStore.getProjectByName(editorStore.project)+);++const hasJITFeature = computed(+ () =>+ project.value.allowJustInTimeAccess && hasFeature(PlanFeature.FEATURE_JIT)+);++const targets = computed(() => (props.database ? [props.database] : []));const formatAlgorithm = (algorithm: string): string => {const algorithmKey = algorithm.toLowerCase().replace(/\s+/g, "-");const key = `masking.algorithms.${algorithmKey}`;- // Check if translation existsconst translated = t(key);if (translated === key) {- // If no translation found, return originalreturn algorithm;}return translated;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vueindex 2f83aba0e9..96cee766bc 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vue@@ -1,8 +1,8 @@<template><NTooltip :animated="false" :delay="250"><template #trigger>- <heroicons-outline:eye-slash- class="w-[12px] h-[12px] -mb-[2px]"+ <EyeOffIcon+ class="w-3 h-3 -mb-0.5":class="[clickable && 'cursor-pointer']"v-bind="$attrs"@click="handleClick"@@ -16,6 +16,7 @@</template><script lang="ts" setup>+import { EyeOffIcon } from "lucide-vue-next";import { NTooltip } from "naive-ui";import { computed } from "vue";import { useRouter } from "vue-router";diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vueindex 05a1067b70..d5e2b0d55b 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/RequestQueryButton.vue@@ -3,20 +3,20 @@<PermissionGuardWrapperv-slot="slotProps":project="project"- :permissions="['bb.issues.create']"+ :permissions="[requiredPermission]"><NButtontype="primary":text="text":size="size"- :disabled="slotProps.disabled || !hasRequestRoleFeature"+ :disabled="slotProps.disabled || !hasRequestFeature"@click="onClick"><template #icon>- <ShieldUserIcon v-if="hasRequestRoleFeature" class="w-4 h-4" />- <FeatureBadge v-else :clickable="false" :feature="PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW" />+ <ShieldUserIcon v-if="hasRequestFeature" class="w-4 h-4" />+ <FeatureBadge v-else :clickable="false" :feature="requiredFeature" /></template>- {{ $t("sql-editor.request-query") }}+ {{ useJIT ? $t("sql-editor.request-jit") : $t("sql-editor.request-query") }}</NButton></PermissionGuardWrapper>@@ -29,6 +29,12 @@:required-permissions="permissionDeniedDetail.requiredPermissions"@close="showPanel = false"/>+ <AccessGrantRequestDrawer+ v-if="showJITDrawer"+ :query="statement"+ :targets="missingResources.map(r => r.databaseFullName)"+ @close="showJITDrawer = false"+ /></div></template>@@ -41,14 +47,21 @@ import GrantRequestPanel from "@/components/GrantRequestPanel";import { parseStringToResource } from "@/components/GrantRequestPanel/DatabaseResourceForm/common";import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";-import { type DatabaseResource, PresetRoleType } from "@/types";+import {+ type DatabaseResource,+ type Permission,+ PresetRoleType,+} from "@/types";import { type PermissionDeniedDetail } from "@/types/proto-es/v1/common_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import AccessGrantRequestDrawer from "@/views/sql-editor/AsidePanel/AccessPane/AccessGrantRequestDrawer.vue";const props = withDefaults(defineProps<{size?: "tiny" | "medium";text: boolean;+ preferJit: boolean;+ statement?: string;permissionDeniedDetail: PermissionDeniedDetail;}>(),{@@ -57,12 +70,37 @@ const props = withDefaults();const showPanel = ref(false);+const showJITDrawer = ref(false);const editorStore = useSQLEditorStore();const projectStore = useProjectV1Store();-const hasRequestRoleFeature = computed(() =>- hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW)++const project = computed(() =>+ projectStore.getProjectByName(editorStore.project));+const useJIT = computed(() => {+ return (+ props.preferJit &&+ project.value.allowJustInTimeAccess &&+ props.permissionDeniedDetail.requiredPermissions.some((p) =>+ p.startsWith("bb.sql.")+ )+ );+});++const requiredPermission = computed(+ (): Permission =>+ useJIT.value ? "bb.accessGrants.create" : "bb.issues.create"+);++const requiredFeature = computed(() =>+ useJIT.value+ ? PlanFeature.FEATURE_JIT+ : PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW+);++const hasRequestFeature = computed(() => hasFeature(requiredFeature.value));+const missingResources = computed((): DatabaseResource[] => {const resources: DatabaseResource[] = [];for (const resourceString of props.permissionDeniedDetail.resources) {@@ -74,10 +112,6 @@ const missingResources = computed((): DatabaseResource[] => {return resources;});-const project = computed(() =>- projectStore.getProjectByName(editorStore.project)-);-const available = computed(() => {return project.value.allowRequestRole;});@@ -85,6 +119,11 @@ const available = computed(() => {const onClick = (e: MouseEvent) => {e.stopPropagation();e.preventDefault();- showPanel.value = true;++ if (useJIT.value) {+ showJITDrawer.value = true;+ } else {+ showPanel.value = true;+ }};</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vueindex 0c1482f3b7..7be5919056 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue@@ -18,6 +18,8 @@<RequestQueryButtonv-if="!!permissionDeniedError":text="false"+ :prefer-jit="true"+ :statement="resultSet.results[0]?.statement":permission-denied-detail="permissionDeniedError"/></template>@@ -73,6 +75,8 @@<RequestQueryButtonv-if="!!permissionDeniedError":text="false"+ :prefer-jit="true"+ :statement="result.statement":permission-denied-detail="permissionDeniedError"/></template>@@ -136,6 +140,8 @@<RequestQueryButtonv-if="!!permissionDeniedError":text="false"+ :prefer-jit="true"+ :statement="resultSet.results[0]?.statement":permission-denied-detail="permissionDeniedError"/><SyncDatabaseButtondiff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vueindex 9420a2def2..bf472fb66e 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue@@ -104,6 +104,7 @@:is-sensitive-column="isSensitiveColumn":get-masking-reason="getMaskingReason":database="database"+ :statement="params.statement":active-row-index="activeRowIndex":search="state.searchParams"/>@@ -115,6 +116,7 @@:is-sensitive-column="isSensitiveColumn":get-masking-reason="getMaskingReason":database="database"+ :statement="params.statement":sort-state="state.sortState":active-row-index="activeRowIndex":search="state.searchParams"diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vueindex a578e9614a..179e9ebaa5 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue@@ -41,10 +41,8 @@<MaskingReasonPopoverv-if="getMaskingReason && getMaskingReason(columnIndex)":reason="getMaskingReason(columnIndex)!"- class="ml-0.5 shrink-0"- />- <SensitiveDataIcon- v-else-if="isSensitiveColumn(columnIndex)"+ :statement="statement"+ :database="database.name"class="ml-0.5 shrink-0"/>:@@ -80,7 +78,6 @@ import type {import { type SearchParams } from "@/utils";import { useBinaryFormatContext } from "./DataTable/common/binary-format-store";import MaskingReasonPopover from "./DataTable/common/MaskingReasonPopover.vue";-import SensitiveDataIcon from "./DataTable/common/SensitiveDataIcon.vue";import type {ResultTableColumn,ResultTableRow,@@ -95,6 +92,7 @@ const props = defineProps<{isSensitiveColumn: (index: number) => boolean;getMaskingReason?: (index: number) => MaskingReason | undefined;database: Database;+ statement?: string;search: SearchParams;}>();diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex eb17fce637..f26ec19cda 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -31,7 +31,13 @@ import {} from "@/utils";import { openWorksheetByName } from "@/views/sql-editor/Sheet";-export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY";+export const ASIDE_PANEL_TABS = [+ "SCHEMA",+ "WORKSHEET",+ "HISTORY",+ "ACCESS",+] as const;+export type AsidePanelTab = (typeof ASIDE_PANEL_TABS)[number];const minimumEditorPanelSize = 0.5;@@ -78,6 +84,9 @@ export type SQLEditorContext = {pendingInsertAtCaret: Ref<string | undefined>;+ // The resource name of a newly created access grant to highlight in the list.+ highlightAccessGrantName: Ref<string | undefined>;+events: SQLEditorEvents;maybeSwitchProject: (project: string) => Promise<string | undefined>;@@ -299,6 +308,7 @@ export const provideSQLEditorContext = () => {editorPanelSize,schemaViewer: ref(undefined),pendingInsertAtCaret: ref(),+ highlightAccessGrantName: ref<string | undefined>(),events: new Emittery(),maybeSwitchProject,diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 34098448bc..cc67566b70 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -7220,6 +7220,7 @@ paths:- expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- query: the access query, support "==" and ".contains(xx)" operator+ - target: the target database fullname, support "==" operator.Examples:- creator == "users/[email protected]"@@ -7228,6 +7229,7 @@ paths:- creator == "users/[email protected]" && status == "ACTIVE"- issue == "projects/x/issues/123"- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ - target == "instances/sample/databases/employee"schema:type: stringtitle: filter@@ -7241,6 +7243,7 @@ paths:- expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- query: the access query, support "==" and ".contains(xx)" operator+ - target: the target database fullname, support "==" operator.Examples:- creator == "users/[email protected]"@@ -7249,6 +7252,26 @@ paths:- creator == "users/[email protected]" && status == "ACTIVE"- issue == "projects/x/issues/123"- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ - target == "instances/sample/databases/employee"+ - name: orderBy+ in: query+ description: |-+ The order by of access grants.+ Support creator, expire_time, create_time. The default sorting order is ascending.+ For example:+ - order_by = "creator"+ - order_by = "expire_time desc"+ - order_by = "expire_time asc, create_time desc"+ schema:+ type: string+ title: order_by+ description: |-+ The order by of access grants.+ Support creator, expire_time, create_time. The default sorting order is ascending.+ For example:+ - order_by = "creator"+ - order_by = "expire_time desc"+ - order_by = "expire_time asc, create_time desc"responses:"200":description: Success@@ -7397,13 +7420,11 @@ paths:filter:type: stringtitle: filter- description: |-- Filter expression using AIP-160 syntax.- Supported fields: name, status, expire_time, create_time- Examples:- - 'name = "projects/x/accessGrants/uuid"'- - 'status = "ACTIVE"'- - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'+ description: Check the filter field in the ListAccessGrantsRequest message.+ orderBy:+ type: string+ title: order_by+ description: Check the order_by field in the ListAccessGrantsRequest message.title: SearchMyAccessGrantsRequestadditionalProperties: falserequired: true@@ -21124,6 +21145,7 @@ components:- expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- query: the access query, support "==" and ".contains(xx)" operator+ - target: the target database fullname, support "==" operator.Examples:- creator == "users/[email protected]"@@ -21132,6 +21154,17 @@ components:- creator == "users/[email protected]" && status == "ACTIVE"- issue == "projects/x/issues/123"- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ - target == "instances/sample/databases/employee"+ orderBy:+ type: string+ title: order_by+ description: |-+ The order by of access grants.+ Support creator, expire_time, create_time. The default sorting order is ascending.+ For example:+ - order_by = "creator"+ - order_by = "expire_time desc"+ - order_by = "expire_time asc, create_time desc"title: ListAccessGrantsRequestrequired:- parent@@ -25198,13 +25231,11 @@ components:filter:type: stringtitle: filter- description: |-- Filter expression using AIP-160 syntax.- Supported fields: name, status, expire_time, create_time- Examples:- - 'name = "projects/x/accessGrants/uuid"'- - 'status = "ACTIVE"'- - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'+ description: Check the filter field in the ListAccessGrantsRequest message.+ orderBy:+ type: string+ title: order_by+ description: Check the order_by field in the ListAccessGrantsRequest message.title: SearchMyAccessGrantsRequestrequired:- parentdiff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 92c4b6a6d8..f250a2bf5c 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -837,9 +837,10 @@ Authorization method for RPC calls.| parent | [string](#string) | | The parent project of the access grants. Format: projects/{project} || page_size | [int32](#int32) | | The maximum number of access grants to return. || page_token | [string](#string) | | A page token from a previous ListAccessGrants call. |-| filter | [string](#string) | | Filter expression using AIP-160 syntax. Supported fields: - name: the fullname in "projects/{project}/accessGrants/{access_grant}" format, support "==" operator. - creator: the creator name in "users/{email}" format, support "==" operator. - status: the access status, support "==" and "in" operator. - issue: the access issue fullname, support "==" operator. - expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator. - create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator. - query: the access query, support "==" and ".contains(xx)" operator+| filter | [string](#string) | | Filter expression using AIP-160 syntax. Supported fields: - name: the fullname in "projects/{project}/accessGrants/{access_grant}" format, support "==" operator. - creator: the creator name in "users/{email}" format, support "==" operator. - status: the access status, support "==" and "in" operator. - issue: the access issue fullname, support "==" operator. - expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator. - create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator. - query: the access query, support "==" and ".contains(xx)" operator - target: the target database fullname, support "==" operator.-Examples: - creator == "users/[email protected]" - status == "ACTIVE" - status in ["ACTIVE", "PENDING"] - creator == "users/[email protected]" && status == "ACTIVE" - issue == "projects/x/issues/123" - status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z" |+Examples: - creator == "users/[email protected]" - status == "ACTIVE" - status in ["ACTIVE", "PENDING"] - creator == "users/[email protected]" && status == "ACTIVE" - issue == "projects/x/issues/123" - status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z" - target == "instances/sample/databases/employee" |+| order_by | [string](#string) | | The order by of access grants. Support creator, expire_time, create_time. The default sorting order is ascending. For example: - order_by = "creator" - order_by = "expire_time desc" - order_by = "expire_time asc, create_time desc" |@@ -888,7 +889,8 @@ Examples: - creator == "users/[email protected]" - status == "ACTIVE&#| parent | [string](#string) | | The parent project to search in. Format: projects/{project} || page_size | [int32](#int32) | | The maximum number of access grants to return. || page_token | [string](#string) | | A page token from a previous SearchMyAccessGrants call. |-| filter | [string](#string) | | Filter expression using AIP-160 syntax. Supported fields: name, status, expire_time, create_time Examples: - 'name = "projects/x/accessGrants/uuid"' - 'status = "ACTIVE"' - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"' |+| filter | [string](#string) | | Check the filter field in the ListAccessGrantsRequest message. |+| order_by | [string](#string) | | Check the order_by field in the ListAccessGrantsRequest message. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 2dbe71899d..44eccde7e3 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3191,6 +3191,7 @@ Supported fields:- expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.- query: the access query, support "==" and ".contains(xx)" operator+- target: the target database fullname, support "==" operator.Examples:- creator == "users/[email protected]"@@ -3198,7 +3199,20 @@ Examples:- status in ["ACTIVE", "PENDING"]- creator == "users/[email protected]" && status == "ACTIVE"- issue == "projects/x/issues/123"-- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z" </p></td>+- status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+- target == "instances/sample/databases/employee" </p></td>+ </tr>++ <tr>+ <td>order_by</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The order by of access grants.+Support creator, expire_time, create_time. The default sorting order is ascending.+For example:+- order_by = "creator"+- order_by = "expire_time desc"+- order_by = "expire_time asc, create_time desc" </p></td></tr></tbody>@@ -3301,12 +3315,14 @@ Format: projects/{project} </p></td><td>filter</td><td><a href="#string">string</a></td><td></td>- <td><p>Filter expression using AIP-160 syntax.-Supported fields: name, status, expire_time, create_time-Examples:- - 'name = "projects/x/accessGrants/uuid"'- - 'status = "ACTIVE"'- - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"' </p></td>+ <td><p>Check the filter field in the ListAccessGrantsRequest message. </p></td>+ </tr>++ <tr>+ <td>order_by</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Check the order_by field in the ListAccessGrantsRequest message. </p></td></tr></tbody>diff --git a/proto/v1/v1/access_grant_service.proto b/proto/v1/v1/access_grant_service.protoindex db758334d1..64c8799ebe 100644--- a/proto/v1/v1/access_grant_service.proto+++ b/proto/v1/v1/access_grant_service.proto@@ -176,6 +176,7 @@ message ListAccessGrantsRequest {// - expire_time: the access expire time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.// - create_time: the access creation time in "2006-01-02T15:04:05Z07:00" format, support ">=", ">", "<=" and "<" operator.// - query: the access query, support "==" and ".contains(xx)" operator+ // - target: the target database fullname, support "==" operator.//// Examples:// - creator == "users/[email protected]"@@ -184,7 +185,16 @@ message ListAccessGrantsRequest {// - creator == "users/[email protected]" && status == "ACTIVE"// - issue == "projects/x/issues/123"// - status == "ACTIVE" && expire_time > "2024-02-01T00:00:00Z"+ // - target == "instances/sample/databases/employee"string filter = 4;++ // The order by of access grants.+ // Support creator, expire_time, create_time. The default sorting order is ascending.+ // For example:+ // - order_by = "creator"+ // - order_by = "expire_time desc"+ // - order_by = "expire_time asc, create_time desc"+ string order_by = 5;}message ListAccessGrantsResponse {@@ -240,13 +250,11 @@ message SearchMyAccessGrantsRequest {// A page token from a previous SearchMyAccessGrants call.string page_token = 3;- // Filter expression using AIP-160 syntax.- // Supported fields: name, status, expire_time, create_time- // Examples:- // - 'name = "projects/x/accessGrants/uuid"'- // - 'status = "ACTIVE"'- // - 'status = "ACTIVE" AND expire_time > "2024-02-01T00:00:00Z"'+ // Check the filter field in the ListAccessGrantsRequest message.string filter = 4;++ // Check the order_by field in the ListAccessGrantsRequest message.+ string order_by = 5;}message SearchMyAccessGrantsResponse {