Skip to content

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

feat(iam): policy permission (#18864)

ecmadao1b0f72a623d1
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index 01fea7597d..679b455315 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -11,6 +11,8 @@ import (
"google.golang.org/protobuf/types/known/emptypb"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/permission"
+ "github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/enterprise"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -36,13 +38,19 @@ type OrgPolicyService struct {
v1connect.UnimplementedOrgPolicyServiceHandler
store *store.Store
licenseService *enterprise.LicenseService
+ iamManager *iam.Manager
}
// NewOrgPolicyService creates a new OrgPolicyService.
-func NewOrgPolicyService(store *store.Store, licenseService *enterprise.LicenseService) *OrgPolicyService {
+func NewOrgPolicyService(
+ store *store.Store,
+ licenseService *enterprise.LicenseService,
+ iamManager *iam.Manager,
+) *OrgPolicyService {
return &OrgPolicyService{
store: store,
licenseService: licenseService,
+ iamManager: iamManager,
}
}
@@ -55,13 +63,30 @@ func (s *OrgPolicyService) GetPolicy(ctx context.Context, req *connect.Request[v
if connectErr == connect.CodeNotFound {
policyType, extractErr := extractPolicyTypeFromName(req.Msg.Name)
if extractErr == nil && policyType == storepb.Policy_ROLLOUT {
- defaultPolicy, defaultErr := s.getDefaultRolloutPolicy(parent, req.Msg.Name)
+ defaultPolicy, defaultErr := s.getDefaultRolloutPolicy(parent)
if defaultErr != nil {
return nil, defaultErr
}
- return connect.NewResponse(defaultPolicy), nil
+ policy = defaultPolicy
}
+ } else {
+ return nil, err
}
+ }
+ if policy == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("cannot found the policy %v", req.Msg.Name))
+ }
+
+ var perm permission.Permission
+ switch policy.Type {
+ case storepb.Policy_MASKING_EXEMPTION:
+ perm = permission.PoliciesGetMaskingExemptionPolicy
+ case storepb.Policy_MASKING_RULE:
+ perm = permission.PoliciesGetMaskingRulePolicy
+ default:
+ perm = permission.PoliciesGet
+ }
+ if err := s.checkPolicyPermission(ctx, req, perm, policy); err != nil {
return nil, err
}
@@ -125,7 +150,7 @@ func (s *OrgPolicyService) CreatePolicy(ctx context.Context, req *connect.Reques
}
// TODO(d): validate policy.
- response, err := s.createPolicyMessage(ctx, req.Msg.Parent, req.Msg.Policy)
+ response, err := s.createPolicyMessage(ctx, req)
if err != nil {
return nil, err
}
@@ -146,15 +171,31 @@ func (s *OrgPolicyService) UpdatePolicy(ctx context.Context, req *connect.Reques
if err != nil {
connectErr := connect.CodeOf(err)
if connectErr == connect.CodeNotFound && req.Msg.AllowMissing {
- response, err := s.createPolicyMessage(ctx, parent, req.Msg.Policy)
+ response, err := s.CreatePolicy(ctx, connect.NewRequest(&v1pb.CreatePolicyRequest{
+ Parent: parent,
+ Policy: req.Msg.Policy,
+ }))
if err != nil {
return nil, err
}
- return connect.NewResponse(response), nil
+ return response, nil
}
return nil, err
}
+ var perm permission.Permission
+ switch policy.Type {
+ case storepb.Policy_MASKING_EXEMPTION:
+ perm = permission.PoliciesUpdateMaskingExemptionPolicy
+ case storepb.Policy_MASKING_RULE:
+ perm = permission.PoliciesUpdateMaskingRulePolicy
+ default:
+ perm = permission.PoliciesUpdate
+ }
+ if err := s.checkPolicyPermission(ctx, req, perm, policy); err != nil {
+ return nil, err
+ }
+
if req.Msg.UpdateMask == nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("update_mask must be set"))
}
@@ -235,6 +276,19 @@ func (s *OrgPolicyService) DeletePolicy(ctx context.Context, req *connect.Reques
return nil, err
}
+ var perm permission.Permission
+ switch policy.Type {
+ case storepb.Policy_MASKING_EXEMPTION:
+ perm = permission.PoliciesDeleteMaskingExemptionPolicy
+ case storepb.Policy_MASKING_RULE:
+ perm = permission.PoliciesDeleteMaskingRulePolicy
+ default:
+ perm = permission.PoliciesDelete
+ }
+ if err := s.checkPolicyPermission(ctx, req, perm, policy); err != nil {
+ return nil, err
+ }
+
if err := s.store.DeletePolicy(ctx, policy); err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
@@ -259,37 +313,30 @@ func extractPolicyTypeFromName(policyName string) (storepb.Policy_Type, error) {
// getDefaultRolloutPolicy returns the default rollout policy when no custom policy exists.
// Uses the shared store.GetDefaultRolloutPolicy to ensure consistency across API and store layers.
-func (*OrgPolicyService) getDefaultRolloutPolicy(parent string, policyName string) (*v1pb.Policy, error) {
- resourceType, _, err := common.GetPolicyResourceTypeAndResource(parent)
+func (*OrgPolicyService) getDefaultRolloutPolicy(parent string) (*store.PolicyMessage, error) {
+ resourceType, resource, err := common.GetPolicyResourceTypeAndResource(parent)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
- v1ResourceType := v1pb.PolicyResourceType_RESOURCE_TYPE_UNSPECIFIED
- switch resourceType {
- case storepb.Policy_WORKSPACE:
- v1ResourceType = v1pb.PolicyResourceType_WORKSPACE
- case storepb.Policy_ENVIRONMENT:
- v1ResourceType = v1pb.PolicyResourceType_ENVIRONMENT
- case storepb.Policy_PROJECT:
- v1ResourceType = v1pb.PolicyResourceType_PROJECT
- default:
- // Keep the default RESOURCE_TYPE_UNSPECIFIED
- }
-
// Get the default rollout policy from the shared store function
- defaultStorePBPolicy := store.GetDefaultRolloutPolicy()
+ defaultRolloutPolicy := store.GetDefaultRolloutPolicy()
+ payloadBytes, err := protojson.Marshal(defaultRolloutPolicy)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to marshal rollout policy")
+ }
- return &v1pb.Policy{
- Name: policyName,
- ResourceType: v1ResourceType,
- Type: v1pb.PolicyType_ROLLOUT_POLICY,
+ policy := &store.PolicyMessage{
+ ResourceType: resourceType,
+ Type: storepb.Policy_ROLLOUT,
InheritFromParent: false,
Enforce: true,
- Policy: &v1pb.Policy_RolloutPolicy{
- RolloutPolicy: convertToV1PBRolloutPolicy(defaultStorePBPolicy),
- },
- }, nil
+ Payload: string(payloadBytes),
+ }
+ if v := resource; v != nil {
+ policy.Resource = *v
+ }
+ return policy, nil
}
// findPolicyMessage finds the policy and the parent name by the policy name.
@@ -337,7 +384,10 @@ func (s *OrgPolicyService) findPolicyMessage(ctx context.Context, policyName str
return policy, policyParent, nil
}
-func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent string, policy *v1pb.Policy) (*v1pb.Policy, error) {
+func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, req *connect.Request[v1pb.CreatePolicyRequest]) (*v1pb.Policy, error) {
+ parent := req.Msg.Parent
+ policy := req.Msg.Policy
+
resourceType, _, err := common.GetPolicyResourceTypeAndResource(parent)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
@@ -371,6 +421,19 @@ func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent strin
Enforce: true,
}
+ var perm permission.Permission
+ switch create.Type {
+ case storepb.Policy_MASKING_EXEMPTION:
+ perm = permission.PoliciesCreateMaskingExemptionPolicy
+ case storepb.Policy_MASKING_RULE:
+ perm = permission.PoliciesCreateMaskingRulePolicy
+ default:
+ perm = permission.PoliciesCreate
+ }
+ if err := s.checkPolicyPermission(ctx, req, perm, create); err != nil {
+ return nil, err
+ }
+
p, err := s.store.CreatePolicy(ctx, create)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
@@ -384,6 +447,38 @@ func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent strin
return response, nil
}
+func (s *OrgPolicyService) checkPolicyPermission(ctx context.Context, req connect.AnyRequest, perm permission.Permission, policy *store.PolicyMessage) error {
+ user, ok := GetUserFromContext(ctx)
+ if !ok {
+ return connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
+ }
+
+ projectIDs := []string{}
+ if policy.ResourceType == storepb.Policy_PROJECT {
+ projectID, err := common.GetProjectID(policy.Resource)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Errorf("failed to get project id from %v", policy.Resource))
+ }
+ projectIDs = append(projectIDs, projectID)
+ }
+
+ ok, err := s.iamManager.CheckPermission(ctx, perm, user, projectIDs...)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))
+ }
+ if !ok {
+ err := connect.NewError(connect.CodePermissionDenied, errors.Errorf("user does not have permission %q", perm))
+ if detail, detailErr := connect.NewErrorDetail(&v1pb.PermissionDeniedDetail{
+ Method: req.Spec().Procedure,
+ RequiredPermissions: []string{string(perm)},
+ }); detailErr == nil {
+ err.AddDetail(detail)
+ }
+ return err
+ }
+ return nil
+}
+
func validatePolicyType(policyType storepb.Policy_Type, policyResourceType storepb.Policy_Resource) error {
allowedTypes, ok := allowedResourceTypes[policyType]
if !ok {
diff --git a/backend/api/v1/org_policy_service_converter.go b/backend/api/v1/org_policy_service_converter.go
index ad4a05a7a9..305ab37e0e 100644
--- a/backend/api/v1/org_policy_service_converter.go
+++ b/backend/api/v1/org_policy_service_converter.go
@@ -161,13 +161,6 @@ func convertToStorePBRolloutPolicy(policy *v1pb.RolloutPolicy) *storepb.RolloutP
}
}
-func convertToV1PBRolloutPolicy(policy *storepb.RolloutPolicy) *v1pb.RolloutPolicy {
- return &v1pb.RolloutPolicy{
- Automatic: policy.Automatic,
- Roles: policy.Roles,
- }
-}
-
func convertToV1PBQueryDataPolicy(payloadStr string) (*v1pb.Policy_QueryDataPolicy, error) {
payload := &storepb.QueryDataPolicy{}
if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(payloadStr), payload); err != nil {
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index ba3e427788..63c26086b7 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -68,14 +68,6 @@ func (s *SettingService) ListSettings(ctx context.Context, _ *connect.Request[v1
if isSettingDisallowed(setting.Name) {
continue
}
- // environment setting is controlled by bb.settings.getEnvironment permission, not expose in the ListSettings API.
- if setting.Name == storepb.SettingName_ENVIRONMENT {
- continue
- }
- // workspace profile setting is controlled by bb.settings.getWorkspaceProfile permission, not expose in the ListSettings API.
- if setting.Name == storepb.SettingName_WORKSPACE_PROFILE {
- continue
- }
settingMessage, err := convertToSettingMessage(setting, s.profile)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
@@ -112,7 +104,7 @@ func (s *SettingService) GetSetting(ctx context.Context, request *connect.Reques
default:
perm = permission.SettingsGet
}
- if err := s.CheckSettingPermission(ctx, perm); err != nil {
+ if err := s.checkSettingPermission(ctx, request, perm); err != nil {
return nil, err
}
@@ -165,7 +157,7 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
default:
perm = permission.SettingsSet
}
- if err := s.CheckSettingPermission(ctx, perm); err != nil {
+ if err := s.checkSettingPermission(ctx, request, perm); err != nil {
return nil, err
}
@@ -630,7 +622,7 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
return connect.NewResponse(settingMessage), nil
}
-func (s *SettingService) CheckSettingPermission(ctx context.Context, perm permission.Permission) error {
+func (s *SettingService) checkSettingPermission(ctx context.Context, req connect.AnyRequest, perm permission.Permission) error {
user, ok := GetUserFromContext(ctx)
if !ok {
return connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
@@ -641,7 +633,14 @@ func (s *SettingService) CheckSettingPermission(ctx context.Context, perm permis
return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission with error: %v", err.Error()))
}
if !ok {
- return connect.NewError(connect.CodePermissionDenied, errors.Errorf("user does not have permission %q", perm))
+ err := connect.NewError(connect.CodePermissionDenied, errors.Errorf("user does not have permission %q", perm))
+ if detail, detailErr := connect.NewErrorDetail(&v1pb.PermissionDeniedDetail{
+ Method: req.Spec().Procedure,
+ RequiredPermissions: []string{string(perm)},
+ }); detailErr == nil {
+ err.AddDetail(detail)
+ }
+ return err
}
return nil
}
diff --git a/backend/common/permission/permission.go b/backend/common/permission/permission.go
index 6ad091e17b..94ed66c0d9 100644
--- a/backend/common/permission/permission.go
+++ b/backend/common/permission/permission.go
@@ -12,120 +12,128 @@ var permissionYAML []byte
type Permission = string
const (
- AuditLogsExport Permission = "bb.auditLogs.export"
- AuditLogsSearch Permission = "bb.auditLogs.search"
- ChangelogsGet Permission = "bb.changelogs.get"
- ChangelogsList Permission = "bb.changelogs.list"
- DatabaseCatalogsGet Permission = "bb.databaseCatalogs.get"
- DatabaseCatalogsUpdate Permission = "bb.databaseCatalogs.update"
- DatabaseGroupsCreate Permission = "bb.databaseGroups.create"
- DatabaseGroupsDelete Permission = "bb.databaseGroups.delete"
- DatabaseGroupsGet Permission = "bb.databaseGroups.get"
- DatabaseGroupsList Permission = "bb.databaseGroups.list"
- DatabaseGroupsUpdate Permission = "bb.databaseGroups.update"
- DatabasesCheck Permission = "bb.databases.check"
- DatabasesGet Permission = "bb.databases.get"
- DatabasesGetSchema Permission = "bb.databases.getSchema"
- DatabasesList Permission = "bb.databases.list"
- DatabasesSync Permission = "bb.databases.sync"
- DatabasesUpdate Permission = "bb.databases.update"
- IdentityProvidersCreate Permission = "bb.identityProviders.create"
- IdentityProvidersDelete Permission = "bb.identityProviders.delete"
- IdentityProvidersGet Permission = "bb.identityProviders.get"
- IdentityProvidersUpdate Permission = "bb.identityProviders.update"
- InstancesCreate Permission = "bb.instances.create"
- InstancesDelete Permission = "bb.instances.delete"
- InstancesGet Permission = "bb.instances.get"
- InstancesList Permission = "bb.instances.list"
- InstancesSync Permission = "bb.instances.sync"
- InstancesUndelete Permission = "bb.instances.undelete"
- InstancesUpdate Permission = "bb.instances.update"
- InstanceRolesGet Permission = "bb.instanceRoles.get"
- InstanceRolesList Permission = "bb.instanceRoles.list"
- IssueCommentsCreate Permission = "bb.issueComments.create"
- IssueCommentsList Permission = "bb.issueComments.list"
- IssueCommentsUpdate Permission = "bb.issueComments.update"
- IssuesCreate Permission = "bb.issues.create"
- IssuesGet Permission = "bb.issues.get"
- IssuesList Permission = "bb.issues.list"
- IssuesUpdate Permission = "bb.issues.update"
- PlanCheckRunsGet Permission = "bb.planCheckRuns.get"
- PlanCheckRunsRun Permission = "bb.planCheckRuns.run"
- PlansCreate Permission = "bb.plans.create"
- PlansGet Permission = "bb.plans.get"
- PlansList Permission = "bb.plans.list"
- PlansUpdate Permission = "bb.plans.update"
- PoliciesCreate Permission = "bb.policies.create"
- PoliciesDelete Permission = "bb.policies.delete"
- PoliciesGet Permission = "bb.policies.get"
- PoliciesList Permission = "bb.policies.list"
- PoliciesUpdate Permission = "bb.policies.update"
- ProjectsCreate Permission = "bb.projects.create"
- ProjectsDelete Permission = "bb.projects.delete"
- ProjectsGet Permission = "bb.projects.get"
- ProjectsGetIAMPolicy Permission = "bb.projects.getIamPolicy"
- ProjectsList Permission = "bb.projects.list"
- ProjectsSetIAMPolicy Permission = "bb.projects.setIamPolicy"
- ProjectsUndelete Permission = "bb.projects.undelete"
- ProjectsUpdate Permission = "bb.projects.update"
- ReleasesCheck Permission = "bb.releases.check"
- ReleasesCreate Permission = "bb.releases.create"
- ReleasesDelete Permission = "bb.releases.delete"
- ReleasesGet Permission = "bb.releases.get"
- ReleasesList Permission = "bb.releases.list"
- ReleasesUndelete Permission = "bb.releases.undelete"
- ReleasesUpdate Permission = "bb.releases.update"
- ReviewConfigsCreate Permission = "bb.reviewConfigs.create"
- ReviewConfigsDelete Permission = "bb.reviewConfigs.delete"
- ReviewConfigsGet Permission = "bb.reviewConfigs.get"
- ReviewConfigsList Permission = "bb.reviewConfigs.list"
- ReviewConfigsUpdate Permission = "bb.reviewConfigs.update"
- RevisionsCreate Permission = "bb.revisions.create"
- RevisionsDelete Permission = "bb.revisions.delete"
- RevisionsGet Permission = "bb.revisions.get"
- RevisionsList Permission = "bb.revisions.list"
- RolesCreate Permission = "bb.roles.create"
- RolesDelete Permission = "bb.roles.delete"
- RolesList Permission = "bb.roles.list"
- RolesGet Permission = "bb.roles.get"
- RolesUpdate Permission = "bb.roles.update"
- RolloutsCreate Permission = "bb.rollouts.create"
- RolloutsGet Permission = "bb.rollouts.get"
- RolloutsList Permission = "bb.rollouts.list"
- SettingsGet Permission = "bb.settings.get"
- SettingsList Permission = "bb.settings.list"
- SettingsSet Permission = "bb.settings.set"
- EnvironmentSettingsGet Permission = "bb.settings.getEnvironment"
- EnvironmentSettingsSet Permission = "bb.settings.setEnvironment"
- WorkspaceProfileSettingsGet Permission = "bb.settings.getWorkspaceProfile"
- WorkspaceProfileSettingsSet Permission = "bb.settings.setWorkspaceProfile"
- SheetsCreate Permission = "bb.sheets.create"
- SheetsGet Permission = "bb.sheets.get"
- SheetsUpdate Permission = "bb.sheets.update"
- SQLSelect Permission = "bb.sql.select"
- SQLDdl Permission = "bb.sql.ddl"
- SQLDml Permission = "bb.sql.dml"
- SQLExplain Permission = "bb.sql.explain"
- SQLInfo Permission = "bb.sql.info"
- SQLAdmin Permission = "bb.sql.admin"
- TaskRunsCreate Permission = "bb.taskRuns.create"
- TaskRunsList Permission = "bb.taskRuns.list"
- GroupsCreate Permission = "bb.groups.create"
- GroupsDelete Permission = "bb.groups.delete"
- GroupsGet Permission = "bb.groups.get"
- GroupsList Permission = "bb.groups.list"
- GroupsUpdate Permission = "bb.groups.update"
- UsersCreate Permission = "bb.users.create"
- UsersDelete Permission = "bb.users.delete"
- UsersGet Permission = "bb.users.get"
- UsersList Permission = "bb.users.list"
- UsersUndelete Permission = "bb.users.undelete"
- UsersUpdate Permission = "bb.users.update"
- UsersUpdateEmail Permission = "bb.users.updateEmail"
- WorksheetsGet Permission = "bb.worksheets.get"
- WorksheetsManage Permission = "bb.worksheets.manage"
- WorkspacesGetIamPolicy Permission = "bb.workspaces.getIamPolicy"
- WorkspacesSetIamPolicy Permission = "bb.workspaces.setIamPolicy"
+ AuditLogsExport Permission = "bb.auditLogs.export"
+ AuditLogsSearch Permission = "bb.auditLogs.search"
+ ChangelogsGet Permission = "bb.changelogs.get"
+ ChangelogsList Permission = "bb.changelogs.list"
+ DatabaseCatalogsGet Permission = "bb.databaseCatalogs.get"
+ DatabaseCatalogsUpdate Permission = "bb.databaseCatalogs.update"
+ DatabaseGroupsCreate Permission = "bb.databaseGroups.create"
+ DatabaseGroupsDelete Permission = "bb.databaseGroups.delete"
+ DatabaseGroupsGet Permission = "bb.databaseGroups.get"
+ DatabaseGroupsList Permission = "bb.databaseGroups.list"
+ DatabaseGroupsUpdate Permission = "bb.databaseGroups.update"
+ DatabasesCheck Permission = "bb.databases.check"
+ DatabasesGet Permission = "bb.databases.get"
+ DatabasesGetSchema Permission = "bb.databases.getSchema"
+ DatabasesList Permission = "bb.databases.list"
+ DatabasesSync Permission = "bb.databases.sync"
+ DatabasesUpdate Permission = "bb.databases.update"
+ IdentityProvidersCreate Permission = "bb.identityProviders.create"
+ IdentityProvidersDelete Permission = "bb.identityProviders.delete"
+ IdentityProvidersGet Permission = "bb.identityProviders.get"
+ IdentityProvidersUpdate Permission = "bb.identityProviders.update"
+ InstancesCreate Permission = "bb.instances.create"
+ InstancesDelete Permission = "bb.instances.delete"
+ InstancesGet Permission = "bb.instances.get"
+ InstancesList Permission = "bb.instances.list"
+ InstancesSync Permission = "bb.instances.sync"
+ InstancesUndelete Permission = "bb.instances.undelete"
+ InstancesUpdate Permission = "bb.instances.update"
+ InstanceRolesGet Permission = "bb.instanceRoles.get"
+ InstanceRolesList Permission = "bb.instanceRoles.list"
+ IssueCommentsCreate Permission = "bb.issueComments.create"
+ IssueCommentsList Permission = "bb.issueComments.list"
+ IssueCommentsUpdate Permission = "bb.issueComments.update"
+ IssuesCreate Permission = "bb.issues.create"
+ IssuesGet Permission = "bb.issues.get"
+ IssuesList Permission = "bb.issues.list"
+ IssuesUpdate Permission = "bb.issues.update"
+ PlanCheckRunsGet Permission = "bb.planCheckRuns.get"
+ PlanCheckRunsRun Permission = "bb.planCheckRuns.run"
+ PlansCreate Permission = "bb.plans.create"
+ PlansGet Permission = "bb.plans.get"
+ PlansList Permission = "bb.plans.list"
+ PlansUpdate Permission = "bb.plans.update"
+ PoliciesCreate Permission = "bb.policies.create"
+ PoliciesDelete Permission = "bb.policies.delete"
+ PoliciesGet Permission = "bb.policies.get"
+ PoliciesList Permission = "bb.policies.list"
+ PoliciesUpdate Permission = "bb.policies.update"
+ PoliciesGetMaskingRulePolicy Permission = "bb.policies.getMaskingRulePolicy"
+ PoliciesUpdateMaskingRulePolicy Permission = "bb.policies.updateMaskingRulePolicy"
+ PoliciesCreateMaskingRulePolicy Permission = "bb.policies.createMaskingRulePolicy"
+ PoliciesDeleteMaskingRulePolicy Permission = "bb.policies.deleteMaskingRulePolicy"
+ PoliciesGetMaskingExemptionPolicy Permission = "bb.policies.getMaskingExemptionPolicy"
+ PoliciesUpdateMaskingExemptionPolicy Permission = "bb.policies.updateMaskingExemptionPolicy"
+ PoliciesCreateMaskingExemptionPolicy Permission = "bb.policies.createMaskingExemptionPolicy"
+ PoliciesDeleteMaskingExemptionPolicy Permission = "bb.policies.deleteMaskingExemptionPolicy"
+ ProjectsCreate Permission = "bb.projects.create"
+ ProjectsDelete Permission = "bb.projects.delete"
+ ProjectsGet Permission = "bb.projects.get"
+ ProjectsGetIAMPolicy Permission = "bb.projects.getIamPolicy"
+ ProjectsList Permission = "bb.projects.list"
+ ProjectsSetIAMPolicy Permission = "bb.projects.setIamPolicy"
+ ProjectsUndelete Permission = "bb.projects.undelete"
+ ProjectsUpdate Permission = "bb.projects.update"
+ ReleasesCheck Permission = "bb.releases.check"
+ ReleasesCreate Permission = "bb.releases.create"
+ ReleasesDelete Permission = "bb.releases.delete"
+ ReleasesGet Permission = "bb.releases.get"
+ ReleasesList Permission = "bb.releases.list"
+ ReleasesUndelete Permission = "bb.releases.undelete"
+ ReleasesUpdate Permission = "bb.releases.update"
+ ReviewConfigsCreate Permission = "bb.reviewConfigs.create"
+ ReviewConfigsDelete Permission = "bb.reviewConfigs.delete"
+ ReviewConfigsGet Permission = "bb.reviewConfigs.get"
+ ReviewConfigsList Permission = "bb.reviewConfigs.list"
+ ReviewConfigsUpdate Permission = "bb.reviewConfigs.update"
+ RevisionsCreate Permission = "bb.revisions.create"
+ RevisionsDelete Permission = "bb.revisions.delete"
+ RevisionsGet Permission = "bb.revisions.get"
+ RevisionsList Permission = "bb.revisions.list"
+ RolesCreate Permission = "bb.roles.create"
+ RolesDelete Permission = "bb.roles.delete"
+ RolesList Permission = "bb.roles.list"
+ RolesGet Permission = "bb.roles.get"
+ RolesUpdate Permission = "bb.roles.update"
+ RolloutsCreate Permission = "bb.rollouts.create"
+ RolloutsGet Permission = "bb.rollouts.get"
+ RolloutsList Permission = "bb.rollouts.list"
+ SettingsGet Permission = "bb.settings.get"
+ SettingsList Permission = "bb.settings.list"
+ SettingsSet Permission = "bb.settings.set"
+ EnvironmentSettingsGet Permission = "bb.settings.getEnvironment"
+ EnvironmentSettingsSet Permission = "bb.settings.setEnvironment"
+ WorkspaceProfileSettingsGet Permission = "bb.settings.getWorkspaceProfile"
+ WorkspaceProfileSettingsSet Permission = "bb.settings.setWorkspaceProfile"
+ SheetsCreate Permission = "bb.sheets.create"
+ SheetsGet Permission = "bb.sheets.get"
+ SheetsUpdate Permission = "bb.sheets.update"
+ SQLSelect Permission = "bb.sql.select"
+ SQLDdl Permission = "bb.sql.ddl"
+ SQLDml Permission = "bb.sql.dml"
+ SQLExplain Permission = "bb.sql.explain"
+ SQLInfo Permission = "bb.sql.info"
+ SQLAdmin Permission = "bb.sql.admin"
+ TaskRunsCreate Permission = "bb.taskRuns.create"
+ TaskRunsList Permission = "bb.taskRuns.list"
+ GroupsCreate Permission = "bb.groups.create"
+ GroupsDelete Permission = "bb.groups.delete"
+ GroupsGet Permission = "bb.groups.get"
+ GroupsList Permission = "bb.groups.list"
+ GroupsUpdate Permission = "bb.groups.update"
+ UsersCreate Permission = "bb.users.create"
+ UsersDelete Permission = "bb.users.delete"
+ UsersGet Permission = "bb.users.get"
+ UsersList Permission = "bb.users.list"
+ UsersUndelete Permission = "bb.users.undelete"
+ UsersUpdate Permission = "bb.users.update"
+ UsersUpdateEmail Permission = "bb.users.updateEmail"
+ WorksheetsGet Permission = "bb.worksheets.get"
+ WorksheetsManage Permission = "bb.worksheets.manage"
+ WorkspacesGetIamPolicy Permission = "bb.workspaces.getIamPolicy"
+ WorkspacesSetIamPolicy Permission = "bb.workspaces.setIamPolicy"
)
var allPermissions = func() []Permission {
diff --git a/backend/common/permission/permission.yaml b/backend/common/permission/permission.yaml
index 8a1b7d9f2f..fbbaf866ad 100644
--- a/backend/common/permission/permission.yaml
+++ b/backend/common/permission/permission.yaml
@@ -52,6 +52,14 @@ permissions:
- bb.policies.get
- bb.policies.list
- bb.policies.update
+ - bb.policies.getMaskingRulePolicy
+ - bb.policies.updateMaskingRulePolicy
+ - bb.policies.createMaskingRulePolicy
+ - bb.policies.deleteMaskingRulePolicy
+ - bb.policies.getMaskingExemptionPolicy
+ - bb.policies.updateMaskingExemptionPolicy
+ - bb.policies.createMaskingExemptionPolicy
+ - bb.policies.deleteMaskingExemptionPolicy
- bb.projects.create
- bb.projects.delete
- bb.projects.get
diff --git a/backend/generated-go/v1/org_policy_service.pb.go b/backend/generated-go/v1/org_policy_service.pb.go
index f966b49ae5..5d4e477fb5 100644
--- a/backend/generated-go/v1/org_policy_service.pb.go
+++ b/backend/generated-go/v1/org_policy_service.pb.go
@@ -1339,11 +1339,11 @@ const file_v1_org_policy_service_proto_rawDesc = "" +
"\vENVIRONMENT\x10\x02\x12\v\n" +
"\aPROJECT\x10\x032\xf4\f\n" +
"\x10OrgPolicyService\x12\xa0\x02\n" +
- "\tGetPolicy\x12\x1d.bytebase.v1.GetPolicyRequest\x1a\x13.bytebase.v1.Policy\"\xde\x01\xdaA\x04name\x8a\xea0\x0fbb.policies.get\x90\xea0\x01\x82\xd3\xe4\x93\x02\xb9\x01Z\"\x12 /v1/{name=projects/*/policies/*}Z&\x12$/v1/{name=environments/*/policies/*}Z#\x12!/v1/{name=instances/*/policies/*}Z/\x12-/v1/{name=instances/*/databases/*/policies/*}\x12\x15/v1/{name=policies/*}\x12\xa8\x02\n" +
+ "\tGetPolicy\x12\x1d.bytebase.v1.GetPolicyRequest\x1a\x13.bytebase.v1.Policy\"\xde\x01\xdaA\x04name\x8a\xea0\x0fbb.policies.get\x90\xea0\x02\x82\xd3\xe4\x93\x02\xb9\x01Z\"\x12 /v1/{name=projects/*/policies/*}Z&\x12$/v1/{name=environments/*/policies/*}Z#\x12!/v1/{name=instances/*/policies/*}Z/\x12-/v1/{name=instances/*/databases/*/policies/*}\x12\x15/v1/{name=policies/*}\x12\xa8\x02\n" +
"\fListPolicies\x12 .bytebase.v1.ListPoliciesRequest\x1a!.bytebase.v1.ListPoliciesResponse\"\xd2\x01\xdaA\x00\x8a\xea0\x10bb.policies.list\x90\xea0\x01\x82\xd3\xe4\x93\x02\xb0\x01Z\"\x12 /v1/{parent=projects/*}/policiesZ&\x12$/v1/{parent=environments/*}/policiesZ#\x12!/v1/{parent=instances/*}/policiesZ/\x12-/v1/{parent=instances/*/databases/*}/policies\x12\f/v1/policies\x12\xd5\x02\n" +
- "\fCreatePolicy\x12 .bytebase.v1.CreatePolicyRequest\x1a\x13.bytebase.v1.Policy\"\x8d\x02\xdaA\rparent,policy\x8a\xea0\x12bb.policies.create\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\xd8\x01:\x06policyZ*:\x06policy\" /v1/{parent=projects/*}/policiesZ.:\x06policy\"$/v1/{parent=environments/*}/policiesZ+:\x06policy\"!/v1/{parent=instances/*}/policiesZ7:\x06policy\"-/v1/{parent=instances/*/databases/*}/policies\"\f/v1/policies\x12\x86\x03\n" +
- "\fUpdatePolicy\x12 .bytebase.v1.UpdatePolicyRequest\x1a\x13.bytebase.v1.Policy\"\xbe\x02\xdaA\x12policy,update_mask\x8a\xea0\x12bb.policies.update\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x84\x02:\x06policyZ1:\x06policy2'/v1/{policy.name=projects/*/policies/*}Z5:\x06policy2+/v1/{policy.name=environments/*/policies/*}Z2:\x06policy2(/v1/{policy.name=instances/*/policies/*}Z>:\x06policy24/v1/{policy.name=instances/*/databases/*/policies/*}2\x1c/v1/{policy.name=policies/*}\x12\xb0\x02\n" +
- "\fDeletePolicy\x12 .bytebase.v1.DeletePolicyRequest\x1a\x16.google.protobuf.Empty\"\xe5\x01\xdaA\x04name\x8a\xea0\x12bb.policies.delete\x90\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\xb9\x01Z\"* /v1/{name=projects/*/policies/*}Z&*$/v1/{name=environments/*/policies/*}Z#*!/v1/{name=instances/*/policies/*}Z/*-/v1/{name=instances/*/databases/*/policies/*}*\x15/v1/{name=policies/*}B\xab\x01\n" +
+ "\fCreatePolicy\x12 .bytebase.v1.CreatePolicyRequest\x1a\x13.bytebase.v1.Policy\"\x8d\x02\xdaA\rparent,policy\x8a\xea0\x12bb.policies.create\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x02\xd8\x01:\x06policyZ*:\x06policy\" /v1/{parent=projects/*}/policiesZ.:\x06policy\"$/v1/{parent=environments/*}/policiesZ+:\x06policy\"!/v1/{parent=instances/*}/policiesZ7:\x06policy\"-/v1/{parent=instances/*/databases/*}/policies\"\f/v1/policies\x12\x86\x03\n" +
+ "\fUpdatePolicy\x12 .bytebase.v1.UpdatePolicyRequest\x1a\x13.bytebase.v1.Policy\"\xbe\x02\xdaA\x12policy,update_mask\x8a\xea0\x12bb.policies.update\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x02\x84\x02:\x06policyZ1:\x06policy2'/v1/{policy.name=projects/*/policies/*}Z5:\x06policy2+/v1/{policy.name=environments/*/policies/*}Z2:\x06policy2(/v1/{policy.name=instances/*/policies/*}Z>:\x06policy24/v1/{policy.name=instances/*/databases/*/policies/*}2\x1c/v1/{policy.name=policies/*}\x12\xb0\x02\n" +
+ "\fDeletePolicy\x12 .bytebase.v1.DeletePolicyRequest\x1a\x16.google.protobuf.Empty\"\xe5\x01\xdaA\x04name\x8a\xea0\x12bb.policies.delete\x90\xea0\x02\x98\xea0\x01\x82\xd3\xe4\x93\x02\xb9\x01Z\"* /v1/{name=projects/*/policies/*}Z&*$/v1/{name=environments/*/policies/*}Z#*!/v1/{name=instances/*/policies/*}Z/*-/v1/{name=instances/*/databases/*/policies/*}*\x15/v1/{name=policies/*}B\xab\x01\n" +
"\x0fcom.bytebase.v1B\x15OrgPolicyServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"
var (
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 96ce08b85d..9763467e2e 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -99,7 +99,7 @@ func configureGrpcRouters(
instanceRoleService := apiv1.NewInstanceRoleService(stores)
instanceService := apiv1.NewInstanceService(stores, profile, licenseService, dbFactory, schemaSyncer, sampleInstanceManager)
issueService := apiv1.NewIssueService(stores, webhookManager, bus, licenseService, iamManager)
- orgPolicyService := apiv1.NewOrgPolicyService(stores, licenseService)
+ orgPolicyService := apiv1.NewOrgPolicyService(stores, licenseService, iamManager)
planService := apiv1.NewPlanService(stores, bus, iamManager, webhookManager, licenseService)
projectService := apiv1.NewProjectService(stores, profile, iamManager)
releaseService := apiv1.NewReleaseService(stores, sheetManager, dbFactory)
diff --git a/backend/store/predefined_roles.go b/backend/store/predefined_roles.go
index 6183d7b603..a721c2f92a 100644
--- a/backend/store/predefined_roles.go
+++ b/backend/store/predefined_roles.go
@@ -78,6 +78,14 @@ var PredefinedRoles = []*RoleMessage{
permission.PoliciesGet,
permission.PoliciesList,
permission.PoliciesUpdate,
+ permission.PoliciesCreateMaskingExemptionPolicy,
+ permission.PoliciesUpdateMaskingExemptionPolicy,
+ permission.PoliciesDeleteMaskingExemptionPolicy,
+ permission.PoliciesGetMaskingExemptionPolicy,
+ permission.PoliciesCreateMaskingRulePolicy,
+ permission.PoliciesUpdateMaskingRulePolicy,
+ permission.PoliciesDeleteMaskingRulePolicy,
+ permission.PoliciesGetMaskingRulePolicy,
permission.ProjectsCreate,
permission.ProjectsDelete,
permission.ProjectsGet,
@@ -195,6 +203,14 @@ var PredefinedRoles = []*RoleMessage{
permission.PoliciesGet,
permission.PoliciesList,
permission.PoliciesUpdate,
+ permission.PoliciesCreateMaskingExemptionPolicy,
+ permission.PoliciesUpdateMaskingExemptionPolicy,
+ permission.PoliciesDeleteMaskingExemptionPolicy,
+ permission.PoliciesGetMaskingExemptionPolicy,
+ permission.PoliciesCreateMaskingRulePolicy,
+ permission.PoliciesUpdateMaskingRulePolicy,
+ permission.PoliciesDeleteMaskingRulePolicy,
+ permission.PoliciesGetMaskingRulePolicy,
permission.ProjectsCreate,
permission.ProjectsDelete,
permission.ProjectsGet,
@@ -262,7 +278,6 @@ var PredefinedRoles = []*RoleMessage{
permission.InstanceRolesGet,
permission.InstanceRolesList,
permission.PoliciesGet,
- permission.PoliciesList,
permission.ReviewConfigsGet,
permission.ReviewConfigsList,
permission.RolesList,
@@ -317,6 +332,14 @@ var PredefinedRoles = []*RoleMessage{
permission.PoliciesGet,
permission.PoliciesList,
permission.PoliciesUpdate,
+ permission.PoliciesCreateMaskingExemptionPolicy,
+ permission.PoliciesUpdateMaskingExemptionPolicy,
+ permission.PoliciesDeleteMaskingExemptionPolicy,
+ permission.PoliciesGetMaskingExemptionPolicy,
+ permission.PoliciesCreateMaskingRulePolicy,
+ permission.PoliciesUpdateMaskingRulePolicy,
+ permission.PoliciesDeleteMaskingRulePolicy,
+ permission.PoliciesGetMaskingRulePolicy,
permission.ProjectsGet,
permission.ProjectsGetIAMPolicy,
permission.ProjectsSetIAMPolicy,
diff --git a/frontend/src/components/Changelog/ChangelogDetail.vue b/frontend/src/components/Changelog/ChangelogDetail.vue
index 086b46e88f..59ba4d3e6d 100644
--- a/frontend/src/components/Changelog/ChangelogDetail.vue
+++ b/frontend/src/components/Changelog/ChangelogDetail.vue
@@ -167,7 +167,7 @@ const state = reactive<LocalState>({
});
const { database, ready } = useDatabaseV1ByName(props.database);
-const { allowAlterSchema } = useDatabaseDetailContext();
+const { allowAlterSchema, isDefaultProject } = useDatabaseDetailContext();
const changelogName = computed(() => {
return `${props.database}/changelogs/${props.changelogId}`;
@@ -233,6 +233,9 @@ const previousSchema = computed((): string => {
// Allow rollback for completed MIGRATE changelogs when user has alter schema permission
const allowRollback = computed((): boolean => {
+ if (isDefaultProject.value) {
+ return false;
+ }
if (!changelog.value || !allowAlterSchema.value) {
return false;
}
diff --git a/frontend/src/components/Database/DatabaseChangelogPanel.vue b/frontend/src/components/Database/DatabaseChangelogPanel.vue
index 69b93477cd..f89549cba1 100644
--- a/frontend/src/components/Database/DatabaseChangelogPanel.vue
+++ b/frontend/src/components/Database/DatabaseChangelogPanel.vue
@@ -6,26 +6,34 @@
:size="20"
:title="$t('changelog.refreshing')"
/>
- <TooltipButton
- v-if="allowEstablishBaseline"
- tooltip-mode="DISABLED-ONLY"
- :disabled="false"
- type="primary"
- @click="state.showBaselineModal = true"
+ <PermissionGuardWrapper
+ v-if="allowAlterSchema"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="[
+ ...PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE
+ ]"
>
- <template #default>
- {{ $t("changelog.establish-baseline") }}
- </template>
- <template v-if="database.project === DEFAULT_PROJECT_NAME" #tooltip>
- <div class="whitespace-pre-line">
- {{
- $t("issue.not-allowed-to-operate-unassigned-database", {
- operation: $t("changelog.establish-baseline").toLowerCase(),
- })
- }}
- </div>
- </template>
- </TooltipButton>
+ <TooltipButton
+ tooltip-mode="DISABLED-ONLY"
+ :disabled="slotProps.disabled"
+ type="primary"
+ @click="state.showBaselineModal = true"
+ >
+ <template #default>
+ {{ $t("changelog.establish-baseline") }}
+ </template>
+ <template v-if="database.project === DEFAULT_PROJECT_NAME && !slotProps.disabled" #tooltip>
+ <div class="whitespace-pre-line">
+ {{
+ $t("issue.not-allowed-to-operate-unassigned-database", {
+ operation: $t("changelog.establish-baseline").toLowerCase(),
+ })
+ }}
+ </div>
+ </template>
+ </TooltipButton>
+ </PermissionGuardWrapper>
</div>
@@ -65,12 +73,13 @@
<script lang="ts" setup>
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { computed, reactive, ref } from "vue";
+import { reactive, ref } from "vue";
import type { ComponentExposed } from "vue-component-type-helpers";
import { useI18n } from "vue-i18n";
import { BBAlert, BBSpin } from "@/bbkit";
import { ChangelogDataTable } from "@/components/Changelog";
import { useDatabaseDetailContext } from "@/components/Database/context";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { TooltipButton } from "@/components/v2";
import PagedTable from "@/components/v2/Model/PagedTable.vue";
import {
@@ -85,6 +94,7 @@ import {
DatabaseSchema$,
UpdateDatabaseRequestSchema,
} from "@/types/proto-es/v1/database_service_pb";
+import { PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE } from "@/utils";
interface LocalState {
showBaselineModal: boolean;
@@ -128,10 +138,6 @@ const fetchChangelogList = async ({
const { allowAlterSchema } = useDatabaseDetailContext();
-const allowEstablishBaseline = computed(() => {
- return allowAlterSchema.value;
-});
-
const updateDatabaseDrift = async () => {
const updatedDatabase = create(DatabaseSchema$, {
...props.database,
diff --git a/frontend/src/components/Database/DatabaseOverviewPanel.vue b/frontend/src/components/Database/DatabaseOverviewPanel.vue
index 4a4012825c..b349c655f9 100644
--- a/frontend/src/components/Database/DatabaseOverviewPanel.vue
+++ b/frontend/src/components/Database/DatabaseOverviewPanel.vue
@@ -3,154 +3,159 @@
<!-- Description list -->
<DatabaseOverviewInfo :database="database" class="pb-6" />
- <div v-if="allowGetSchema" class="border-t border-block-border pt-6">
- <div
- v-if="hasSchemaPropertyV1"
- class="flex flex-row justify-start items-center mb-4"
- >
- <span class="text-lg leading-6 font-medium text-main mr-2">Schema</span>
- <NSelect
- v-model:value="state.selectedSchemaName"
- :options="schemaNameOptions"
- :disabled="state.loading"
- :placeholder="$t('database.schema.select')"
- class="w-auto! min-w-48"
- />
- </div>
-
- <template v-if="databaseEngine !== Engine.REDIS">
- <div class="mb-4 w-full flex flex-row justify-between items-center">
- <div class="text-lg leading-6 font-medium text-main">
- <span v-if="databaseEngine === Engine.MONGODB">
- {{ $t("db.collections") }}
- </span>
- <span v-else>{{ $t("db.tables") }}</span>
- </div>
- <SearchBox
- v-model:value="state.tableNameSearchKeyword"
- :placeholder="$t('common.filter-by-name')"
+ <ComponentPermissionGuard
+ :project="database.projectEntity"
+ :permissions="['bb.databases.getSchema']"
+ >
+ <div class="border-t border-block-border pt-6">
+ <div
+ v-if="hasSchemaPropertyV1"
+ class="flex flex-row justify-start items-center mb-4"
+ >
+ <span class="text-lg leading-6 font-medium text-main mr-2">Schema</span>
+ <NSelect
+ v-model:value="state.selectedSchemaName"
+ :options="schemaNameOptions"
:disabled="state.loading"
+ :placeholder="$t('database.schema.select')"
+ class="w-auto! min-w-48"
/>
</div>
- <TableDataTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :table-list="tableList"
- :search="state.tableNameSearchKeyword.trim().toLowerCase()"
- :loading="state.loading"
- />
-
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.views") }}
- </div>
- <ViewDataTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :view-list="viewList"
- :loading="state.loading"
- />
-
- <template
- v-if="
- databaseEngine === Engine.POSTGRES || databaseEngine === Engine.HIVE
- "
- >
- <div
- class="mt-6 w-full flex flex-row justify-between items-center mb-4"
- >
+ <template v-if="databaseEngine !== Engine.REDIS">
+ <div class="mb-4 w-full flex flex-row justify-between items-center">
<div class="text-lg leading-6 font-medium text-main">
- {{ $t("db.external-tables") }}
+ <span v-if="databaseEngine === Engine.MONGODB">
+ {{ $t("db.collections") }}
+ </span>
+ <span v-else>{{ $t("db.tables") }}</span>
</div>
<SearchBox
- v-model:value="state.externalTableNameSearchKeyword"
+ v-model:value="state.tableNameSearchKeyword"
:placeholder="$t('common.filter-by-name')"
:disabled="state.loading"
/>
</div>
- <ExternalTableDataTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :external-table-list="externalTableList"
- :search="state.externalTableNameSearchKeyword.trim().toLowerCase()"
- :loading="state.loading"
- />
- </template>
-
- <template v-if="databaseEngine === Engine.POSTGRES">
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.extensions") }}
- </div>
- <DBExtensionDataTable
- :db-extension-list="dbExtensionList"
- :loading="state.loading"
- />
- </template>
- <template
- v-if="
- databaseEngine === Engine.POSTGRES ||
- databaseEngine === Engine.MSSQL
- "
- >
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.functions") }}
- </div>
- <FunctionDataTable
+ <TableDataTable
:database="database"
:schema-name="state.selectedSchemaName"
- :function-list="functionList"
+ :table-list="tableList"
+ :search="state.tableNameSearchKeyword.trim().toLowerCase()"
:loading="state.loading"
/>
- </template>
- <template v-if="instanceV1SupportsSequence(databaseEngine)">
<div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.sequences") }}
+ {{ $t("db.views") }}
</div>
- <SequenceDataTable
+ <ViewDataTable
:database="database"
:schema-name="state.selectedSchemaName"
- :sequence-list="sequenceList"
+ :view-list="viewList"
:loading="state.loading"
/>
- </template>
- <template v-if="databaseEngine === Engine.SNOWFLAKE">
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.streams") }}
- </div>
- <StreamTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :stream-list="streamList"
- :loading="state.loading"
- />
+ <template
+ v-if="
+ databaseEngine === Engine.POSTGRES || databaseEngine === Engine.HIVE
+ "
+ >
+ <div
+ class="mt-6 w-full flex flex-row justify-between items-center mb-4"
+ >
+ <div class="text-lg leading-6 font-medium text-main">
+ {{ $t("db.external-tables") }}
+ </div>
+ <SearchBox
+ v-model:value="state.externalTableNameSearchKeyword"
+ :placeholder="$t('common.filter-by-name')"
+ :disabled="state.loading"
+ />
+ </div>
+ <ExternalTableDataTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :external-table-list="externalTableList"
+ :search="state.externalTableNameSearchKeyword.trim().toLowerCase()"
+ :loading="state.loading"
+ />
+ </template>
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.tasks") }}
- </div>
- <TaskTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :task-list="taskList"
- :loading="state.loading"
- />
- </template>
+ <template v-if="databaseEngine === Engine.POSTGRES">
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.extensions") }}
+ </div>
+ <DBExtensionDataTable
+ :db-extension-list="dbExtensionList"
+ :loading="state.loading"
+ />
+ </template>
- <template v-if="instanceV1SupportsPackage(databaseEngine)">
- <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.packages") }}
- </div>
- <PackageDataTable
- :database="database"
- :schema-name="state.selectedSchemaName"
- :package-list="packageList"
- :loading="state.loading"
- />
+ <template
+ v-if="
+ databaseEngine === Engine.POSTGRES ||
+ databaseEngine === Engine.MSSQL
+ "
+ >
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.functions") }}
+ </div>
+ <FunctionDataTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :function-list="functionList"
+ :loading="state.loading"
+ />
+ </template>
+
+ <template v-if="instanceV1SupportsSequence(databaseEngine)">
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.sequences") }}
+ </div>
+ <SequenceDataTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :sequence-list="sequenceList"
+ :loading="state.loading"
+ />
+ </template>
+
+ <template v-if="databaseEngine === Engine.SNOWFLAKE">
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.streams") }}
+ </div>
+ <StreamTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :stream-list="streamList"
+ :loading="state.loading"
+ />
+
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.tasks") }}
+ </div>
+ <TaskTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :task-list="taskList"
+ :loading="state.loading"
+ />
+ </template>
+
+ <template v-if="instanceV1SupportsPackage(databaseEngine)">
+ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">
+ {{ $t("db.packages") }}
+ </div>
+ <PackageDataTable
+ :database="database"
+ :schema-name="state.selectedSchemaName"
+ :package-list="packageList"
+ :loading="state.loading"
+ />
+ </template>
</template>
- </template>
- </div>
+ </div>
+ </ComponentPermissionGuard>
</div>
</template>
@@ -160,10 +165,10 @@ import { NSelect } from "naive-ui";
import { computed, reactive, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
-import { useDatabaseDetailContext } from "@/components/Database/context";
import DBExtensionDataTable from "@/components/DBExtensionDataTable.vue";
import ExternalTableDataTable from "@/components/ExternalTableDataTable.vue";
import FunctionDataTable from "@/components/FunctionDataTable.vue";
+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";
import StreamTable from "@/components/StreamTable.vue";
import TableDataTable from "@/components/TableDataTable.vue";
import TaskTable from "@/components/TaskTable.vue";
@@ -202,8 +207,6 @@ const state = reactive<LocalState>({
externalTableNameSearchKeyword: "",
});
-const { allowGetSchema } = useDatabaseDetailContext();
-
const dbSchemaStore = useDBSchemaV1Store();
const databaseEngine = computed(() => {
@@ -214,14 +217,14 @@ const hasSchemaPropertyV1 = computed(() => {
return hasSchemaProperty(databaseEngine.value);
});
+const schemaList = computed(() => {
+ return dbSchemaStore.getSchemaList(props.database.name);
+});
+
watch(
() => props.database.name,
- async (database) => {
+ async () => {
state.loading = true;
- await dbSchemaStore.getOrFetchDatabaseMetadata({
- database,
- skipCache: false,
- });
if (schemaList.value.length > 0) {
const schemaInQuery = route.query.schema as string;
if (
@@ -247,10 +250,6 @@ watch(
{ immediate: true }
);
-const schemaList = computed(() => {
- return dbSchemaStore.getSchemaList(props.database.name);
-});
-
const schemaNameOptions = computed(() => {
return schemaList.value.map((schema) => ({
value: schema.name,
diff --git a/frontend/src/components/Database/DatabaseSensitiveDataPanel.vue b/frontend/src/components/Database/DatabaseSensitiveDataPanel.vue
index 510d416d73..58aed6980b 100644
--- a/frontend/src/components/Database/DatabaseSensitiveDataPanel.vue
+++ b/frontend/src/components/Database/DatabaseSensitiveDataPanel.vue
@@ -8,26 +8,36 @@
class="flex flex-col gap-x-2 lg:flex-row gap-y-4 justify-between items-end lg:items-center"
>
<SearchBox v-model:value="state.searchText" style="max-width: 100%" />
- <NButton
+ <PermissionGuardWrapper
v-if="!isMaskingForNoSQL"
- type="primary"
- :disabled="
- state.pendingGrantAccessColumn.length === 0 ||
- !hasPolicyPermission ||
- !hasGetCatalogPermission
- "
- @click="onGrantAccessButtonClick"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="[
+ 'bb.policies.createMaskingExemptionPolicy',
+ 'bb.policies.updateMaskingExemptionPolicy',
+ 'bb.databaseCatalogs.get'
+ ]"
>
- <template #icon>
- <ShieldCheckIcon v-if="hasSensitiveDataFeature" class="w-4" />
- <FeatureBadge
- :feature="PlanFeature.FEATURE_DATA_MASKING"
- class="text-white"
- :instance="database.instanceResource"
- />
- </template>
- {{ $t("settings.sensitive-data.grant-access") }}
- </NButton>
+ <NButton
+ type="primary"
+ :disabled="
+ slotProps.disabled ||
+ state.pendingGrantAccessColumn.length === 0
+ "
+ @click="onGrantAccessButtonClick"
+ >
+ <template #icon>
+ <ShieldCheckIcon v-if="hasSensitiveDataFeature" class="w-4" />
+ <FeatureBadge
+ v-else
+ :feature="PlanFeature.FEATURE_DATA_MASKING"
+ class="text-white"
+ :instance="database.instanceResource"
+ />
+ </template>
+ {{ $t("settings.sensitive-data.grant-access") }}
+ </NButton>
+ </PermissionGuardWrapper>
</div>
<SensitiveColumnTable
@@ -78,6 +88,7 @@ import {
FeatureBadge,
FeatureModal,
} from "@/components/FeatureGuard";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import SensitiveColumnTable from "@/components/SensitiveData/components/SensitiveColumnTable.vue";
import GrantAccessDrawer from "@/components/SensitiveData/GrantAccessDrawer.vue";
import type { MaskData } from "@/components/SensitiveData/types";
@@ -129,20 +140,6 @@ const hasUpdateCatalogPermission = computed(() => {
);
});
-const hasGetCatalogPermission = computed(() => {
- return hasProjectPermissionV2(
- props.database.projectEntity,
- "bb.databaseCatalogs.get"
- );
-});
-
-const hasPolicyPermission = computed(() => {
- return hasProjectPermissionV2(
- props.database.projectEntity,
- "bb.policies.update"
- );
-});
-
const policyStore = usePolicyV1Store();
const hasSensitiveDataFeature = featureToRef(PlanFeature.FEATURE_DATA_MASKING);
diff --git a/frontend/src/components/Database/context.ts b/frontend/src/components/Database/context.ts
index 0de173c7b5..feb39495fc 100644
--- a/frontend/src/components/Database/context.ts
+++ b/frontend/src/components/Database/context.ts
@@ -5,25 +5,15 @@ import {
databaseNamePrefix,
instanceNamePrefix,
} from "@/store/modules/v1/common";
-import type { ComposedDatabase, Permission } from "@/types";
+import type { ComposedDatabase } from "@/types";
import { DEFAULT_PROJECT_NAME } from "@/types";
-import {
- hasPermissionToCreateChangeDatabaseIssue,
- hasProjectPermissionV2,
- instanceV1HasAlterSchema,
-} from "@/utils";
+import { instanceV1HasAlterSchema } from "@/utils";
export type DatabaseDetailContext = {
database: Ref<ComposedDatabase>;
pagedRevisionTableSessionKey: Ref<string>;
- allowGetDatabase: Ref<boolean>;
- allowUpdateDatabase: Ref<boolean>;
- allowSyncDatabase: Ref<boolean>;
- allowTransferDatabase: Ref<boolean>;
- allowGetSchema: Ref<boolean>;
- allowChangeData: Ref<boolean>;
allowAlterSchema: Ref<boolean>;
- allowListChangelogs: Ref<boolean>;
+ isDefaultProject: Ref<boolean>;
};
export const KEY = Symbol(
@@ -49,57 +39,19 @@ export const provideDatabaseDetailContext = (
`bb.paged-revision-table.${Date.now()}`
);
- const checkPermission = (permission: Permission): boolean => {
- return hasProjectPermissionV2(database.value.projectEntity, permission);
- };
-
- const allowGetDatabase = computed(() => checkPermission("bb.databases.get"));
- const allowUpdateDatabase = computed(() =>
- checkPermission("bb.databases.update")
- );
- const allowSyncDatabase = computed(() => {
- return checkPermission("bb.databases.sync");
- });
- const allowTransferDatabase = computed(() => {
- if (database.value.project === DEFAULT_PROJECT_NAME) {
- return true;
- }
- return allowUpdateDatabase.value;
- });
-
- const allowGetSchema = computed(() =>
- checkPermission("bb.databases.getSchema")
+ const isDefaultProject = computed(
+ () => database.value.project === DEFAULT_PROJECT_NAME
);
- const allowChangeData = computed(() => {
- return (
- database.value.project !== DEFAULT_PROJECT_NAME &&
- hasPermissionToCreateChangeDatabaseIssue(database.value)
- );
- });
const allowAlterSchema = computed(() => {
- return (
- database.value.project !== DEFAULT_PROJECT_NAME &&
- hasPermissionToCreateChangeDatabaseIssue(database.value) &&
- instanceV1HasAlterSchema(database.value.instanceResource)
- );
+ return instanceV1HasAlterSchema(database.value.instanceResource);
});
- const allowListChangelogs = computed(() =>
- checkPermission("bb.changelogs.list")
- );
-
const context: DatabaseDetailContext = {
database,
pagedRevisionTableSessionKey,
- allowGetDatabase,
- allowUpdateDatabase,
- allowSyncDatabase,
- allowTransferDatabase,
- allowGetSchema,
- allowChangeData,
allowAlterSchema,
- allowListChangelogs,
+ isDefaultProject,
};
provide(KEY, context);
diff --git a/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue b/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue
index f9f24e68a4..7626a053cc 100644
--- a/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue
+++ b/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue
@@ -1,7 +1,13 @@
<template>
- <div v-if="available">
+ <PermissionGuardWrapper
+ v-if="available"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="['bb.databases.getSchema']"
+ >
<NDropdown
:options="exportOptions"
+ :disabled="slotProps.disabled"
@select="handleExportFormat"
trigger="click"
>
@@ -9,7 +15,7 @@
{{ $t("database.export-schema") }}
</NButton>
</NDropdown>
- </div>
+ </PermissionGuardWrapper>
</template>
<script setup lang="ts">
@@ -18,6 +24,7 @@ import { ConnectError } from "@connectrpc/connect";
import { NButton, NDropdown } from "naive-ui";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { databaseServiceClientConnect } from "@/connect";
import { pushNotification } from "@/store";
import type { ComposedDatabase } from "@/types";
@@ -26,7 +33,6 @@ import {
GetDatabaseSDLSchemaRequest_SDLFormat,
GetDatabaseSDLSchemaRequestSchema,
} from "@/types/proto-es/v1/database_service_pb";
-import { hasProjectPermissionV2 } from "@/utils";
const props = defineProps<{
database: ComposedDatabase;
@@ -36,14 +42,7 @@ const exporting = ref(false);
const { t } = useI18n();
const available = computed(() => {
- if (!isValidDatabaseName(props.database.name)) {
- return false;
- }
-
- return hasProjectPermissionV2(
- props.database.projectEntity,
- "bb.databases.getSchema"
- );
+ return isValidDatabaseName(props.database.name);
});
const exportOptions = computed(() => [
diff --git a/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue b/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue
index 5ebe8f1b46..4d3533834d 100644
--- a/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue
+++ b/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue
@@ -34,7 +34,6 @@ import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { cloneDeep } from "lodash-es";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
-import { useDatabaseDetailContext } from "@/components/Database/context";
import { EnvironmentSelect } from "@/components/v2";
import {
environmentNamePrefix,
@@ -45,6 +44,7 @@ import {
import { type ComposedDatabase } from "@/types";
import { UpdateDatabaseRequestSchema } from "@/types/proto-es/v1/database_service_pb";
import type { Environment } from "@/types/v1/environment";
+import { hasProjectPermissionV2 } from "@/utils";
import Labels from "./components/Labels.vue";
const props = defineProps<{
@@ -61,7 +61,9 @@ const environment = computed(() => {
);
});
-const { allowUpdateDatabase } = useDatabaseDetailContext();
+const allowUpdateDatabase = computed(() =>
+ hasProjectPermissionV2(props.database.projectEntity, "bb.databases.update")
+);
const handleSelectEnvironment = async (name: string | undefined) => {
if (name === props.database.effectiveEnvironment) {
diff --git a/frontend/src/components/DatabaseDetail/SyncDatabaseButton.vue b/frontend/src/components/DatabaseDetail/SyncDatabaseButton.vue
index 6dcbf3a314..22997303cd 100644
--- a/frontend/src/components/DatabaseDetail/SyncDatabaseButton.vue
+++ b/frontend/src/components/DatabaseDetail/SyncDatabaseButton.vue
@@ -1,14 +1,20 @@
<template>
- <div v-if="available">
+ <PermissionGuardWrapper
+ v-if="available"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="['bb.databases.sync']"
+ >
<NButton
:text="text"
:type="type"
+ :disabled="slotProps.disabled"
:loading="syncingSchema"
@click="syncDatabaseSchema"
>
{{ $t("database.sync-database") }}
</NButton>
- </div>
+ </PermissionGuardWrapper>
</template>
<script setup lang="ts">
@@ -16,6 +22,7 @@ import { ConnectError } from "@connectrpc/connect";
import { NButton } from "naive-ui";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import {
pushNotification,
useDatabaseV1Store,
@@ -23,7 +30,6 @@ import {
} from "@/store";
import type { ComposedDatabase } from "@/types";
import { isValidDatabaseName } from "@/types";
-import { hasProjectPermissionV2 } from "@/utils";
const props = defineProps<{
text: boolean;
@@ -41,14 +47,7 @@ const databaseV1Store = useDatabaseV1Store();
const dbSchemaStore = useDBSchemaV1Store();
const available = computed(() => {
- if (!isValidDatabaseName(props.database.name)) {
- return false;
- }
-
- return hasProjectPermissionV2(
- props.database.projectEntity,
- "bb.databases.sync"
- );
+ return isValidDatabaseName(props.database.name);
});
const syncDatabaseSchema = async () => {
diff --git a/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue b/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue
index 6ca31c9226..967d6bad87 100644
--- a/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue
+++ b/frontend/src/components/EnvironmentForm/AccessControlConfigure.vue
@@ -1,5 +1,5 @@
<template>
- <div class="flex flex-col gap-y-2">
+ <div v-if="hasGetPermission" class="flex flex-col gap-y-2">
<div class="font-medium flex items-center gap-x-2">
<label>
{{ t("environment.access-control.title") }}
@@ -15,63 +15,87 @@
</div>
<div>
<div class="w-full inline-flex items-center gap-x-2">
- <Switch
- v-model:value="state.queryDataPolicy.disableCopyData"
- :text="true"
- :disabled="!allowUpdatePolicy || !hasRestrictCopyingDataFeature"
- />
- <span class="textlabel">{{
- t("environment.access-control.disable-copy-data-from-sql-editor")
- }}</span>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <Switch
+ v-model:value="state.queryDataPolicy.disableCopyData"
+ :text="true"
+ :disabled="slotProps.disabled || !hasRestrictCopyingDataFeature"
+ />
+ </PermissionGuardWrapper>
+ <span class="textlabel">
+ {{ t("environment.access-control.disable-copy-data-from-sql-editor") }}
+ </span>
<FeatureBadge :feature="PlanFeature.FEATURE_RESTRICT_COPYING_DATA" />
</div>
<div class="">
<div class="w-full inline-flex items-center gap-x-2">
- <Switch
- :value="adminDataSourceQueryRestrictionEnabled"
- :text="true"
- :disabled="!allowUpdatePolicy || !hasRestrictQueryDataSourceFeature"
- @update:value="switchDataSourceQueryPolicyEnabled"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <Switch
+ :value="adminDataSourceQueryRestrictionEnabled"
+ :text="true"
+ :disabled="slotProps.disabled || !hasRestrictQueryDataSourceFeature"
+ @update:value="switchDataSourceQueryPolicyEnabled"
+ />
+ </PermissionGuardWrapper>
<span class="textlabel">{{
t("environment.access-control.restrict-admin-connection.self")
}}</span>
<FeatureBadge :feature="PlanFeature.FEATURE_QUERY_POLICY" />
</div>
<div v-if="adminDataSourceQueryRestrictionEnabled" class="ml-12">
- <NRadioGroup
- v-model:value="
- state.dataSourceQueryPolicy.adminDataSourceRestriction
- "
- :disabled="!allowUpdatePolicy || !hasRestrictQueryDataSourceFeature"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
>
- <NRadio
- class="w-full"
- :value="DataSourceQueryPolicy_Restriction.DISALLOW"
- >
- {{
- t(
- "environment.access-control.restrict-admin-connection.disallow"
- )
- }}
- </NRadio>
- <NRadio
- class="w-full"
- :value="DataSourceQueryPolicy_Restriction.FALLBACK"
+ <NRadioGroup
+ v-model:value="
+ state.dataSourceQueryPolicy.adminDataSourceRestriction
+ "
+ :disabled="slotProps.disabled || !hasRestrictQueryDataSourceFeature"
>
- {{
- t(
- "environment.access-control.restrict-admin-connection.fallback"
- )
- }}
- </NRadio>
- </NRadioGroup>
+ <NRadio
+ class="w-full"
+ :value="DataSourceQueryPolicy_Restriction.DISALLOW"
+ >
+ {{
+ t(
+ "environment.access-control.restrict-admin-connection.disallow"
+ )
+ }}
+ </NRadio>
+ <NRadio
+ class="w-full"
+ :value="DataSourceQueryPolicy_Restriction.FALLBACK"
+ >
+ {{
+ t(
+ "environment.access-control.restrict-admin-connection.fallback"
+ )
+ }}
+ </NRadio>
+ </NRadioGroup>
+ </PermissionGuardWrapper>
</div>
</div>
</div>
</div>
<div
- v-if="resource.startsWith(environmentNamePrefix)"
+ v-if="resource.startsWith(environmentNamePrefix) && hasGetPermission"
class="flex flex-col gap-y-2"
>
<div class="font-medium flex items-center gap-x-2">
@@ -82,21 +106,37 @@
</div>
<div>
<div class="w-full inline-flex items-center gap-x-2">
- <Switch
- v-model:value="state.dataSourceQueryPolicy.disallowDdl"
- :text="true"
- :disabled="!allowUpdatePolicy || !hasRestrictQueryDataSourceFeature"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <Switch
+ v-model:value="state.dataSourceQueryPolicy.disallowDdl"
+ :text="true"
+ :disabled="slotProps.disabled || !hasRestrictQueryDataSourceFeature"
+ />
+ </PermissionGuardWrapper>
<span class="textlabel">
{{ t("environment.statement-execution.disallow-ddl") }}
</span>
</div>
<div class="w-full inline-flex items-center gap-x-2">
- <Switch
- v-model:value="state.dataSourceQueryPolicy.disallowDml"
- :text="true"
- :disabled="!allowUpdatePolicy || !hasRestrictQueryDataSourceFeature"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <Switch
+ v-model:value="state.dataSourceQueryPolicy.disallowDml"
+ :text="true"
+ :disabled="slotProps.disabled || !hasRestrictQueryDataSourceFeature"
+ />
+ </PermissionGuardWrapper>
<span class="textlabel">
{{ t("environment.statement-execution.disallow-dml") }}
</span>
@@ -106,29 +146,28 @@
</template>
<script setup lang="ts">
-import { create as createProto } from "@bufbuild/protobuf";
import { cloneDeep, isEqual } from "lodash-es";
import { CircleQuestionMarkIcon } from "lucide-vue-next";
import { NRadio, NRadioGroup, NTooltip } from "naive-ui";
import { computed, reactive, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
-import { hasFeature, usePolicyV1Store } from "@/store";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
+import { hasFeature, usePolicyV1Store, useProjectV1Store } from "@/store";
import {
environmentNamePrefix,
projectNamePrefix,
} from "@/store/modules/v1/common";
+import { isValidProjectName } from "@/types";
import type {
DataSourceQueryPolicy,
QueryDataPolicy,
} from "@/types/proto-es/v1/org_policy_service_pb";
import {
DataSourceQueryPolicy_Restriction,
- DataSourceQueryPolicySchema,
PolicyType,
- QueryDataPolicySchema,
} from "@/types/proto-es/v1/org_policy_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { hasWorkspacePermissionV2 } from "@/utils";
+import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
import { FeatureBadge } from "../FeatureGuard";
import { Switch } from "../v2";
@@ -141,25 +180,38 @@ interface LocalState {
const props = defineProps<{
resource: string;
- allowEdit: boolean;
}>();
-const scope = computed(() => {
+const projectStore = useProjectV1Store();
+
+const project = computed(() => {
if (props.resource.startsWith(projectNamePrefix)) {
- return t("settings.general.workspace.query-data-policy.environment-scope");
+ const proj = projectStore.getProjectByName(props.resource);
+ if (!isValidProjectName(proj.name)) {
+ return undefined;
+ }
+ return proj;
}
- if (props.resource.startsWith(environmentNamePrefix)) {
- return t("settings.general.workspace.query-data-policy.project-scope");
+ return undefined;
+});
+
+const hasGetPermission = computed(() => {
+ if (project.value) {
+ return hasProjectPermissionV2(project.value, "bb.policies.get");
}
- return "";
+ return hasWorkspacePermissionV2("bb.policies.get");
});
const tooltip = computed(() => {
- if (!scope.value) {
- return "";
+ if (project.value) {
+ return t("settings.general.workspace.query-data-policy.tooltip", {
+ scope: t(
+ "settings.general.workspace.query-data-policy.environment-scope"
+ ),
+ });
}
return t("settings.general.workspace.query-data-policy.tooltip", {
- scope: scope.value,
+ scope: t("settings.general.workspace.query-data-policy.project-scope"),
});
});
@@ -168,24 +220,14 @@ const policyStore = usePolicyV1Store();
const getInitialState = (): LocalState => {
return {
queryDataPolicy: (() => {
- const policy = policyStore.getPolicyByParentAndType({
- parentPath: props.resource,
- policyType: PolicyType.DATA_QUERY,
- });
- if (policy?.policy.case === "queryDataPolicy") {
- return cloneDeep(policy.policy.value);
- }
- return createProto(QueryDataPolicySchema, {});
+ const policy = policyStore.getQueryDataPolicyByParent(props.resource);
+ return cloneDeep(policy);
})(),
dataSourceQueryPolicy: (() => {
- const policy = policyStore.getPolicyByParentAndType({
- parentPath: props.resource,
- policyType: PolicyType.DATA_SOURCE_QUERY,
- });
- if (policy?.policy.case === "dataSourceQueryPolicy") {
- return cloneDeep(policy.policy.value);
- }
- return createProto(DataSourceQueryPolicySchema, {});
+ const policy = policyStore.getDataSourceQueryPolicyByParent(
+ props.resource
+ );
+ return cloneDeep(policy);
})(),
};
};
@@ -193,6 +235,9 @@ const getInitialState = (): LocalState => {
const state = reactive<LocalState>(getInitialState());
watchEffect(async () => {
+ if (!hasGetPermission.value) {
+ return;
+ }
await Promise.all([
policyStore.getOrFetchPolicyByParentAndType({
parentPath: props.resource,
@@ -225,10 +270,6 @@ const hasRestrictCopyingDataFeature = computed(() =>
hasFeature(PlanFeature.FEATURE_RESTRICT_COPYING_DATA)
);
-const allowUpdatePolicy = computed(() => {
- return props.allowEdit && hasWorkspacePermissionV2("bb.policies.update");
-});
-
const updateQueryDataPolicy = async () => {
await policyStore.upsertPolicy({
parentPath: props.resource,
@@ -257,9 +298,9 @@ const updateAdminDataSourceQueryRestrctionPolicy = async () => {
type: PolicyType.DATA_SOURCE_QUERY,
policy: {
case: "dataSourceQueryPolicy",
- value: createProto(DataSourceQueryPolicySchema, {
+ value: {
...state.dataSourceQueryPolicy,
- }),
+ },
},
},
});
diff --git a/frontend/src/components/EnvironmentForm/Form.vue b/frontend/src/components/EnvironmentForm/Form.vue
index e2f4a064c1..02bce10efb 100644
--- a/frontend/src/components/EnvironmentForm/Form.vue
+++ b/frontend/src/components/EnvironmentForm/Form.vue
@@ -11,11 +11,18 @@
<RequiredStar />
</span>
</div>
- <NInput
- v-model:value="state.environment.title"
- :disabled="!allowEdit"
- required
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setEnvironment'
+ ]"
+ >
+ <NInput
+ v-model:value="state.environment.title"
+ :disabled="slotProps.disabled"
+ required
+ />
+ </PermissionGuardWrapper>
<ResourceIdField
ref="resourceIdField"
@@ -45,23 +52,31 @@
/>
</p>
</div>
- <NCheckbox
- :checked="state.environment.tags.protected === 'protected'"
- :disabled="!allowEdit"
- @update:checked="
- (on: boolean) => {
- state.environment.tags.protected = on
- ? 'protected'
- : 'unprotected';
- }
- "
+
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setEnvironment'
+ ]"
>
- {{ t("policy.environment-tier.mark-env-as-production") }}
- </NCheckbox>
+ <NCheckbox
+ :checked="state.environment.tags.protected === 'protected'"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (on: boolean) => {
+ state.environment.tags.protected = on
+ ? 'protected'
+ : 'unprotected';
+ }
+ "
+ >
+ {{ t("policy.environment-tier.mark-env-as-production") }}
+ </NCheckbox>
+ </PermissionGuardWrapper>
</div>
<div
- v-if="features.includes('ROLLOUT_POLICY')"
+ v-if="features.includes('ROLLOUT_POLICY') && hasGetPolicyPermission"
class="flex flex-col gap-y-2"
>
<div class="gap-y-1">
@@ -86,7 +101,6 @@
</div>
<RolloutPolicyConfig
v-model:policy="state.rolloutPolicy"
- :disabled="!allowEdit"
/>
</div>
@@ -94,14 +108,12 @@
v-if="features.includes('SQL_REVIEW') && !create"
ref="sqlReviewForResourceRef"
:resource="`${environmentNamePrefix}${environment.id}`"
- :allow-edit="allowEdit"
/>
<AccessControlConfigure
v-if="features.includes('ACCESS_CONTROL') && !create"
ref="accessControlConfigureRef"
:resource="`${environmentNamePrefix}${environment.id}`"
- :allow-edit="allowEdit"
/>
</div>
@@ -149,6 +161,7 @@ import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { BBButtonConfirm } from "@/bbkit";
import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import RequiredStar from "@/components/RequiredStar.vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import {
@@ -161,6 +174,7 @@ import {
import { environmentNamePrefix } from "@/store/modules/v1/common";
import { isValidEnvironmentName } from "@/types";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
import { FeatureBadge } from "../FeatureGuard";
import SQLReviewForResource from "../SQLReview/components/SQLReviewForResource.vue";
import { ResourceIdField } from "../v2";
@@ -201,6 +215,10 @@ const environmentStore = useEnvironmentV1Store();
const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
+const hasGetPolicyPermission = computed(() => {
+ return hasWorkspacePermissionV2("bb.policies.get");
+});
+
const accessControlConfigureRef =
ref<InstanceType<typeof AccessControlConfigure>>();
const sqlReviewForResourceRef =
@@ -291,6 +309,7 @@ const renderColorPicker = () => {
class="w-full! h-full!"
modes={["hex"]}
showAlpha={false}
+ disabled={!allowEdit.value}
value={state.value.environment.color || "#4f46e5"}
renderLabel={() => (
<div
diff --git a/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue b/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue
index 5deb498ec8..14ddd96b37 100644
--- a/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue
+++ b/frontend/src/components/EnvironmentForm/RolloutPolicyConfig.vue
@@ -1,21 +1,35 @@
<template>
<div class="flex flex-col items-start gap-y-2">
<div class="flex flex-col gap-y-2">
- <div class="flex flex-col gap-y-2">
- <RoleSelect
- v-model:value="rolloutPolicy.roles"
- :disabled="disabled"
- multiple
- @update:value="updateRoles(rolloutPolicy.roles)"
- />
- </div>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <div class="flex flex-col gap-y-2">
+ <RoleSelect
+ v-model:value="rolloutPolicy.roles"
+ :disabled="slotProps.disabled"
+ multiple
+ @update:value="updateRoles(rolloutPolicy.roles)"
+ />
+ </div>
+ </PermissionGuardWrapper>
<div class="w-full inline-flex items-start gap-x-2">
- <Switch
- :value="isAutomaticRolloutChecked"
- :text="true"
- :disabled="disabled"
- @update:value="toggleAutomaticRollout($event)"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <Switch
+ :value="isAutomaticRolloutChecked"
+ :text="true"
+ :disabled="slotProps.disabled"
+ @update:value="toggleAutomaticRollout($event)"
+ />
+ </PermissionGuardWrapper>
<div class="flex flex-col">
<span class="textlabel">
{{ t("policy.rollout.auto") }}
@@ -34,6 +48,7 @@ import { create } from "@bufbuild/protobuf";
import { cloneDeep } from "lodash-es";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import type {
Policy,
RolloutPolicy,
@@ -45,7 +60,6 @@ const { t } = useI18n();
const props = defineProps<{
policy: Policy;
- disabled?: boolean;
}>();
const emit = defineEmits<{
@@ -73,6 +87,7 @@ const update = (rp: RolloutPolicy) => {
},
});
};
+
const toggleAutomaticRollout = (selected: boolean) => {
update(
create(RolloutPolicySchema, {
@@ -81,6 +96,7 @@ const toggleAutomaticRollout = (selected: boolean) => {
})
);
};
+
const updateRoles = (roles: string[]) => {
update(
create(RolloutPolicySchema, {
diff --git a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue
index a7a46a5271..c9cf1bd91b 100644
--- a/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue
+++ b/frontend/src/components/GeneralSetting/AIAugmentationSetting.vue
@@ -6,167 +6,184 @@
{{ title }}
</h1>
</div>
- <span v-if="!allowEdit" class="text-sm text-gray-400">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
</div>
<div class="flex-1 lg:px-4">
- <div v-if="actuatorStore.isSaaSMode">
- <BBAttention
- :type="'info'"
- :description="
- t('settings.general.workspace.ai-assistant.enabled-in-saas')
- "
- />
- </div>
- <div v-else class="mt-4 lg:mt-0 flex flex-col gap-y-4">
- <div>
- <div class="flex items-center gap-x-2">
- <Switch
- v-model:value="state.enabled"
- :text="true"
- :disabled="!allowEdit"
- @update:value="toggleAIEnabled"
- />
- <span class="font-medium">
- {{
- $t(
- "settings.general.workspace.ai-assistant.enable-ai-assistant"
- )
- }}
- </span>
- </div>
- <div class="mt-1 mb-3 text-sm text-gray-400">
- {{ $t("settings.general.workspace.ai-assistant.description") }}
- <LearnMoreLink
- url="https://docs.bytebase.com/ai-assistant?source=console"
- class="ml-1 text-sm"
- />
- </div>
+ <ComponentPermissionGuard
+ :permissions="['bb.settings.get']"
+ >
+ <div v-if="actuatorStore.isSaaSMode">
+ <BBAttention
+ :type="'info'"
+ :description="
+ t('settings.general.workspace.ai-assistant.enabled-in-saas')
+ "
+ />
</div>
- <NCollapseTransition :show="state.enabled" class="flex flex-col gap-y-4">
+ <div v-else class="mt-4 lg:mt-0 flex flex-col gap-y-4">
<div>
- <label class="flex items-center gap-x-2 mb-2">
- <span class="font-medium">{{
- $t("settings.general.workspace.ai-assistant.provider.self")
- }}</span>
- </label>
- <NSelect
- style="width: 12rem"
- v-model:value="state.provider"
- :options="providerOptions"
- :disabled="!allowEdit"
- :consistent-menu-width="true"
- />
+ <div class="flex items-center gap-x-2">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.set'
+ ]"
+ >
+ <Switch
+ v-model:value="state.enabled"
+ :text="true"
+ :disabled="slotProps.disabled"
+ @update:value="toggleAIEnabled"
+ />
+ </PermissionGuardWrapper>
+ <span class="font-medium">
+ {{
+ $t(
+ "settings.general.workspace.ai-assistant.enable-ai-assistant"
+ )
+ }}
+ </span>
+ </div>
+ <div class="mt-1 mb-3 text-sm text-gray-400">
+ {{ $t("settings.general.workspace.ai-assistant.description") }}
+ <LearnMoreLink
+ url="https://docs.bytebase.com/ai-assistant?source=console"
+ class="ml-1 text-sm"
+ />
+ </div>
</div>
- <div>
- <label class="flex items-center gap-x-2">
- <span class="font-medium">{{
- $t("settings.general.workspace.ai-assistant.api-key.self")
- }}</span>
- </label>
- <div class="mb-3 text-sm text-gray-400">
- <i18n-t
- keypath="settings.general.workspace.ai-assistant.api-key.description"
+ <NCollapseTransition :show="state.enabled" class="flex flex-col gap-y-4">
+ <div>
+ <label class="flex items-center gap-x-2 mb-2">
+ <span class="font-medium">{{
+ $t("settings.general.workspace.ai-assistant.provider.self")
+ }}</span>
+ </label>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.set'
+ ]"
>
- <template #viewDoc>
- <a
- :href="providerDefault.apiKeyDoc"
- class="normal-link"
- target="_blank"
- >{{
- $t(
- "settings.general.workspace.ai-assistant.api-key.find-my-key"
- )
- }}
- </a>
- </template>
- </i18n-t>
+ <NSelect
+ style="width: 12rem"
+ v-model:value="state.provider"
+ :options="providerOptions"
+ :disabled="slotProps.disabled"
+ :consistent-menu-width="true"
+ />
+ </PermissionGuardWrapper>
</div>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
+ <div>
+ <label class="flex items-center gap-x-2">
+ <span class="font-medium">{{
+ $t("settings.general.workspace.ai-assistant.api-key.self")
+ }}</span>
+ </label>
+ <div class="mb-3 text-sm text-gray-400">
+ <i18n-t
+ keypath="settings.general.workspace.ai-assistant.api-key.description"
+ >
+ <template #viewDoc>
+ <a
+ :href="providerDefault.apiKeyDoc"
+ class="normal-link"
+ target="_blank"
+ >{{
+ $t(
+ "settings.general.workspace.ai-assistant.api-key.find-my-key"
+ )
+ }}
+ </a>
+ </template>
+ </i18n-t>
+ </div>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.set'
+ ]"
+ >
<BBTextField
v-model:value="state.apiKey"
- :disabled="!allowEdit"
+ :disabled="slotProps.disabled"
:placeholder="
$t(
'settings.general.workspace.ai-assistant.api-key.placeholder'
)
"
/>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
- </div>
-
- <div>
- <label class="flex items-center gap-x-2">
- <span class="font-medium">{{
- $t("settings.general.workspace.ai-assistant.endpoint.self")
- }}</span>
- </label>
- <div class="mb-3 text-sm text-gray-400">
- {{
- $t(
- "settings.general.workspace.ai-assistant.endpoint.description"
- )
- }}
+ </PermissionGuardWrapper>
</div>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
+
+ <div>
+ <label class="flex items-center gap-x-2">
+ <span class="font-medium">{{
+ $t("settings.general.workspace.ai-assistant.endpoint.self")
+ }}</span>
+ </label>
+ <div class="mb-3 text-sm text-gray-400">
+ {{
+ $t(
+ "settings.general.workspace.ai-assistant.endpoint.description"
+ )
+ }}
+ </div>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.set'
+ ]"
+ >
<BBTextField
v-model:value="state.endpoint"
:required="true"
- :disabled="!allowEdit"
+ :disabled="slotProps.disabled"
:placeholder="providerDefault.endpoint"
/>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
- </div>
-
- <div>
- <label class="flex items-center gap-x-2">
- <span class="font-medium">{{
- $t("settings.general.workspace.ai-assistant.model.self")
- }}</span>
- </label>
- <div class="mb-3 text-sm text-gray-400">
- {{
- $t("settings.general.workspace.ai-assistant.model.description")
- }}
+ </PermissionGuardWrapper>
</div>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
+
+ <div>
+ <label class="flex items-center gap-x-2">
+ <span class="font-medium">{{
+ $t("settings.general.workspace.ai-assistant.model.self")
+ }}</span>
+ </label>
+ <div class="mb-3 text-sm text-gray-400">
+ {{
+ $t("settings.general.workspace.ai-assistant.model.description")
+ }}
+ </div>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.set'
+ ]"
+ >
<BBTextField
v-model:value="state.model"
:required="true"
- :disabled="!allowEdit"
+ :disabled="slotProps.disabled"
/>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
- </div>
- </NCollapseTransition>
- </div>
+ </PermissionGuardWrapper>
+ </div>
+ </NCollapseTransition>
+ </div>
+ </ComponentPermissionGuard>
</div>
</div>
</template>
<script lang="ts" setup>
import { create } from "@bufbuild/protobuf";
-import { NCollapseTransition, NSelect, NTooltip } from "naive-ui";
+import { NCollapseTransition, NSelect } from "naive-ui";
import scrollIntoView from "scroll-into-view-if-needed";
import { computed, onMounted, reactive, ref, watch, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
import { BBAttention, BBTextField } from "@/bbkit";
import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { Switch } from "@/components/v2";
import { useActuatorV1Store, useSettingV1Store } from "@/store/modules";
import {
@@ -186,7 +203,6 @@ interface LocalState {
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const settingV1Store = useSettingV1Store();
@@ -252,7 +268,10 @@ const providerOptions = computed(() =>
);
watchEffect(async () => {
- await settingV1Store.getOrFetchSettingByName(Setting_SettingName.AI);
+ await settingV1Store.getOrFetchSettingByName(
+ Setting_SettingName.AI,
+ /* silent */ true
+ );
Object.assign(state, getInitialState());
});
diff --git a/frontend/src/components/GeneralSetting/AccountSetting.vue b/frontend/src/components/GeneralSetting/AccountSetting.vue
index cecc44b3d0..898de7bdfd 100644
--- a/frontend/src/components/GeneralSetting/AccountSetting.vue
+++ b/frontend/src/components/GeneralSetting/AccountSetting.vue
@@ -6,19 +6,23 @@
{{ title }}
</h1>
</div>
- <span v-if="!allowEdit" class="text-sm text-gray-400">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
</div>
<div class="flex-1 lg:px-4">
<div v-if="!isSaaSMode" class="mb-7 mt-4 lg:mt-0">
<div class="flex items-center gap-x-2">
- <Switch
- v-model:value="state.disallowSignup"
- :text="true"
- :disabled="!allowEdit || !hasDisallowSignupFeature"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <Switch
+ v-model:value="state.disallowSignup"
+ :text="true"
+ :disabled="slotProps.disabled || !hasDisallowSignupFeature"
+ />
+ </PermissionGuardWrapper>
<div class="font-medium flex items-center gap-x-2">
{{ $t("settings.general.workspace.disallow-signup.enable") }}
<FeatureBadge
@@ -35,18 +39,24 @@
<PasswordRestrictionSetting
ref="passwordRestrictionSettingRef"
- :allow-edit="allowEdit"
/>
<NDivider />
<div>
<div class="mb-7 mt-4 lg:mt-0">
<div class="flex items-center gap-x-2">
- <Switch
- v-model:value="state.require2fa"
- :text="true"
- :disabled="!allowEdit || !has2FAFeature"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <Switch
+ v-model:value="state.require2fa"
+ :text="true"
+ :disabled="slotProps.disabled || !has2FAFeature"
+ />
+ </PermissionGuardWrapper>
<div class="font-medium flex items-center gap-x-2">
{{ $t("settings.general.workspace.require-2fa.enable") }}
<FeatureBadge :feature="PlanFeature.FEATURE_TWO_FA" />
@@ -58,22 +68,28 @@
</div>
<div class="mb-7 mt-4 lg:mt-0">
<div class="flex items-center gap-x-2">
- <Switch
- v-model:value="state.disallowPasswordSignin"
- :text="true"
- :disabled="
- !allowEdit ||
- !hasDisallowPasswordSigninFeature ||
- (!state.disallowPasswordSignin && !existActiveIdentityProvider)
- "
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <Switch
+ v-model:value="state.disallowPasswordSignin"
+ :text="true"
+ :disabled="
+ slotProps.disabled ||
+ !hasDisallowPasswordSigninFeature ||
+ (!state.disallowPasswordSignin && !existActiveIdentityProvider)
+ "
+ />
+ </PermissionGuardWrapper>
<div class="font-medium flex items-center gap-x-2">
{{
$t("settings.general.workspace.disallow-password-signin.enable")
}}
<NTooltip
v-if="
- allowEdit &&
hasDisallowPasswordSigninFeature &&
!state.disallowPasswordSignin &&
!existActiveIdentityProvider
@@ -106,7 +122,6 @@
<TokenDurationSetting
ref="tokenDurationSettingRef"
- :allow-edit="allowEdit"
/>
</div>
</div>
@@ -126,6 +141,7 @@ import { TriangleAlertIcon } from "lucide-vue-next";
import { NDivider, NTooltip } from "naive-ui";
import { storeToRefs } from "pinia";
import { computed, reactive, ref, watchEffect } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { Switch } from "@/components/v2";
import {
featureToRef,
@@ -148,7 +164,6 @@ interface LocalState {
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const settingV1Store = useSettingV1Store();
diff --git a/frontend/src/components/GeneralSetting/AnnouncementSetting.vue b/frontend/src/components/GeneralSetting/AnnouncementSetting.vue
index fb78a22b40..0d07088bfb 100644
--- a/frontend/src/components/GeneralSetting/AnnouncementSetting.vue
+++ b/frontend/src/components/GeneralSetting/AnnouncementSetting.vue
@@ -7,12 +7,6 @@
</h1>
<FeatureBadge :feature="PlanFeature.FEATURE_DASHBOARD_ANNOUNCEMENT" />
</div>
-
- <span v-if="!allowEdit" class="text-sm text-gray-400">
- {{
- $t("settings.general.workspace.announcement.admin-or-dba-can-edit")
- }}
- </span>
</div>
<div class="flex-1 lg:px-5">
<div class="mt-5 lg:mt-0">
@@ -23,76 +17,64 @@
)
}}</span>
</label>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
- <div class="flex flex-wrap py-2 radio-set-row gap-4">
- <AnnouncementLevelSelect
- v-model:level="state.level"
- :allow-edit="allowEdit && hasAnnouncementFeature"
- />
- </div>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{
- $t(
- "settings.general.workspace.announcement.admin-or-dba-can-edit"
- )
- }}
- </span>
- </NTooltip>
+ <div class="flex flex-wrap py-2 radio-set-row gap-4">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <AnnouncementLevelSelect
+ v-model:level="state.level"
+ :allow-edit="!slotProps.disabled && hasAnnouncementFeature"
+ />
+ </PermissionGuardWrapper>
+ </div>
<label class="flex items-center mt-2 gap-x-2">
- <span class="font-medium"
- >{{ $t("settings.general.workspace.announcement-text.self") }}
+ <span class="font-medium">
+ {{ $t("settings.general.workspace.announcement-text.self") }}
</span>
</label>
<div class="mb-3 text-sm text-gray-400">
{{ $t("settings.general.workspace.announcement-text.description") }}
</div>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
- <NInput
- v-model:value="state.text"
- class="mb-3 w-full"
- :placeholder="
- $t('settings.general.workspace.announcement-text.placeholder')
- "
- :disabled="!allowEdit || !hasAnnouncementFeature"
- />
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{
- $t(
- "settings.general.workspace.announcement.admin-or-dba-can-edit"
- )
- }}
- </span>
- </NTooltip>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <NInput
+ v-model:value="state.text"
+ class="mb-3 w-full"
+ :placeholder="
+ $t('settings.general.workspace.announcement-text.placeholder')
+ "
+ :disabled="slotProps.disabled || !hasAnnouncementFeature"
+ />
+ </PermissionGuardWrapper>
<label class="flex items-center py-2 gap-x-2">
- <span class="font-medium">{{
- $t("settings.general.workspace.extra-link.self")
- }}</span>
- </label>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
- <NInput
- v-model:value="state.link"
- class="mb-5 w-full"
- :placeholder="
- $t('settings.general.workspace.extra-link.placeholder')
- "
- :disabled="!allowEdit || !hasAnnouncementFeature"
- />
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{
- $t(
- "settings.general.workspace.announcement.admin-or-dba-can-edit"
- )
- }}
+ <span class="font-medium">
+ {{ $t("settings.general.workspace.extra-link.self") }}
</span>
- </NTooltip>
+ </label>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <NInput
+ v-model:value="state.link"
+ class="mb-5 w-full"
+ :placeholder="
+ $t('settings.general.workspace.extra-link.placeholder')
+ "
+ :disabled="slotProps.disabled || !hasAnnouncementFeature"
+ />
+ </PermissionGuardWrapper>
</div>
</div>
</div>
@@ -102,8 +84,9 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { cloneDeep, isEqual } from "lodash-es";
-import { NInput, NTooltip } from "naive-ui";
+import { NInput } from "naive-ui";
import { computed, reactive } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { AnnouncementLevelSelect } from "@/components/v2";
import { featureToRef } from "@/store";
import { useSettingV1Store } from "@/store/modules/v1/setting";
@@ -117,7 +100,6 @@ import { FeatureBadge } from "../FeatureGuard";
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const settingV1Store = useSettingV1Store();
diff --git a/frontend/src/components/GeneralSetting/BrandingSetting.vue b/frontend/src/components/GeneralSetting/BrandingSetting.vue
index cbb90d5212..c46b4e0959 100644
--- a/frontend/src/components/GeneralSetting/BrandingSetting.vue
+++ b/frontend/src/components/GeneralSetting/BrandingSetting.vue
@@ -7,9 +7,6 @@
</h1>
<FeatureBadge :feature="PlanFeature.FEATURE_CUSTOM_LOGO" />
</div>
- <span v-if="!allowEdit" class="text-sm text-gray-400">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
</div>
<div class="flex-1 lg:px-4">
<div class="mb-4 mt-4 lg:mt-0">
@@ -19,40 +16,48 @@
<p class="mb-3 text-sm text-gray-400">
{{ $t("settings.general.workspace.logo-aspect") }}
</p>
- <NTooltip placement="top-start" :disabled="allowEdit">
- <template #trigger>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <div
+ class="flex justify-center border-2 border-gray-300 border-dashed rounded-md relative h-48"
+ >
<div
- class="flex justify-center border-2 border-gray-300 border-dashed rounded-md relative h-48"
- >
- <div
- class="w-full bg-no-repeat bg-contain bg-center rounded-md pointer-events-none m-4"
- :style="`background-image: url(${state.logoUrl});`"
- ></div>
- <SingleFileSelector
- class="flex flex-col gap-y-1 text-center justify-center items-center absolute top-0 bottom-0 left-0 right-0"
- :class="[state.logoUrl ? 'opacity-0 hover:opacity-90' : '']"
- :max-file-size-in-mi-b="maxFileSizeInMiB"
- :support-file-extensions="supportImageExtensions"
- :disabled="!allowEdit || !hasBrandingFeature"
- :show-no-data-placeholder="!state.logoUrl"
- @on-select="onLogoSelect"
- />
- </div>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
+ class="w-full bg-no-repeat bg-contain bg-center rounded-md pointer-events-none m-4"
+ :style="`background-image: url(${state.logoUrl});`"
+ ></div>
+ <SingleFileSelector
+ class="flex flex-col gap-y-1 text-center justify-center items-center absolute top-0 bottom-0 left-0 right-0"
+ :class="[state.logoUrl ? 'opacity-0 hover:opacity-90' : '']"
+ :max-file-size-in-mi-b="maxFileSizeInMiB"
+ :support-file-extensions="supportImageExtensions"
+ :disabled="slotProps.disabled || !hasBrandingFeature"
+ :show-no-data-placeholder="!state.logoUrl"
+ @on-select="onLogoSelect"
+ />
+ </div>
+ </PermissionGuardWrapper>
</div>
<div class="flex justify-end gap-x-3">
- <NButton
- v-if="allowEdit && !!state.logoUrl"
- secondary
- type="error"
- @click="() => (state.logoUrl = '')"
+ <PermissionGuardWrapper
+ v-if="!!state.logoUrl"
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
>
- {{ $t("common.delete") }}
- </NButton>
+ <NButton
+ secondary
+ :disabled="slotProps.disabled"
+ type="error"
+ @click="() => (state.logoUrl = '')"
+ >
+ {{ $t("common.delete") }}
+ </NButton>
+ </PermissionGuardWrapper>
</div>
</div>
</div>
@@ -67,8 +72,9 @@
<script lang="ts" setup>
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { NButton, NTooltip } from "naive-ui";
+import { NButton } from "naive-ui";
import { computed, reactive } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { featureToRef } from "@/store";
import { useActuatorV1Store } from "@/store/modules/v1/actuator";
import { useSettingV1Store } from "@/store/modules/v1/setting";
@@ -84,7 +90,6 @@ interface LocalState {
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const maxFileSizeInMiB = 2;
diff --git a/frontend/src/components/GeneralSetting/DomainRestrictionSetting.vue b/frontend/src/components/GeneralSetting/DomainRestrictionSetting.vue
index 5e443ecd4b..1a52b7e86a 100644
--- a/frontend/src/components/GeneralSetting/DomainRestrictionSetting.vue
+++ b/frontend/src/components/GeneralSetting/DomainRestrictionSetting.vue
@@ -12,43 +12,57 @@
{{ $t("settings.general.workspace.domain-restriction.description") }}
</p>
<div class="w-full flex flex-col gap-2 mt-2">
- <NDynamicTags
- :size="'large'"
- :disabled="!allowEdit"
- :value="state.domains"
- :input-props="{
- placeholder: $t(
- 'settings.general.workspace.domain-restriction.domain-input-placeholder'
- ),
- clearable: true,
- }"
- :input-style="'min-width: 20rem;'"
- @update:value="onDomainsUpdate"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <NDynamicTags
+ :size="'large'"
+ :disabled="slotProps.disabled"
+ :value="state.domains"
+ :input-props="{
+ placeholder: $t(
+ 'settings.general.workspace.domain-restriction.domain-input-placeholder'
+ ),
+ clearable: true,
+ }"
+ :input-style="'min-width: 20rem;'"
+ @update:value="onDomainsUpdate"
+ />
+ </PermissionGuardWrapper>
<div class="w-full flex flex-row justify-between items-center">
- <NCheckbox
- v-model:checked="state.enableRestriction"
- :disabled="validDomains.length === 0 || !hasFeature || !allowEdit"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
>
- <div class="font-medium flex items-center gap-x-2">
- {{
- $t(
- "settings.general.workspace.domain-restriction.members-restriction.self"
- )
- }}
- <FeatureBadge
- :feature="PlanFeature.FEATURE_USER_EMAIL_DOMAIN_RESTRICTION"
- />
- </div>
- <p class="text-sm text-gray-400 leading-tight">
- {{
- $t(
- "settings.general.workspace.domain-restriction.members-restriction.description"
- )
- }}
- </p>
- </NCheckbox>
+ <NCheckbox
+ v-model:checked="state.enableRestriction"
+ :disabled="validDomains.length === 0 || !hasFeature || slotProps.disabled"
+ >
+ <div class="font-medium flex items-center gap-x-2">
+ {{
+ $t(
+ "settings.general.workspace.domain-restriction.members-restriction.self"
+ )
+ }}
+ <FeatureBadge
+ :feature="PlanFeature.FEATURE_USER_EMAIL_DOMAIN_RESTRICTION"
+ />
+ </div>
+ <p class="text-sm text-gray-400 leading-tight">
+ {{
+ $t(
+ "settings.general.workspace.domain-restriction.members-restriction.description"
+ )
+ }}
+ </p>
+ </NCheckbox>
+ </PermissionGuardWrapper>
</div>
</div>
</div>
@@ -60,6 +74,7 @@ import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { cloneDeep, isEqual } from "lodash-es";
import { NCheckbox, NDynamicTags } from "naive-ui";
import { computed, reactive } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { featureToRef } from "@/store";
import { useSettingV1Store } from "@/store/modules/v1/setting";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
@@ -83,10 +98,6 @@ interface LocalState {
enableRestriction: boolean;
}
-defineProps<{
- allowEdit: boolean;
-}>();
-
const settingV1Store = useSettingV1Store();
const state = reactive<LocalState>(cloneDeep(initialState.value));
diff --git a/frontend/src/components/GeneralSetting/GeneralSetting.vue b/frontend/src/components/GeneralSetting/GeneralSetting.vue
index aa5d4a30c6..2ebd9312b2 100644
--- a/frontend/src/components/GeneralSetting/GeneralSetting.vue
+++ b/frontend/src/components/GeneralSetting/GeneralSetting.vue
@@ -10,7 +10,6 @@
<div class="flex-1 mt-4 lg:px-4 lg:mt-0 flex flex-col gap-y-6">
<WorkspaceMode
v-model:mode="state.databaseChangeMode"
- :disabled="!allowEdit"
/>
<div v-if="!isSaaSMode">
@@ -28,25 +27,32 @@
<div v-if="externalUrlFromFlag" class="mb-2 text-sm text-accent">
{{ $t("settings.general.workspace.external-url.managed-by-flag") }}
</div>
- <NTooltip
- placement="top-start"
- :disabled="allowEdit && !externalUrlFromFlag"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
>
- <template #trigger>
- <NInput
- v-model:value="state.externalUrl"
- class="mb-4 w-full"
- :disabled="!allowEdit || isSaaSMode || externalUrlFromFlag"
- />
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{
- externalUrlFromFlag
- ? $t("settings.general.workspace.external-url.cannot-edit-flag")
- : $t("settings.general.workspace.only-admin-can-edit")
- }}
- </span>
- </NTooltip>
+ <NTooltip
+ placement="top-start"
+ :disabled="slotProps.disabled || !externalUrlFromFlag"
+ >
+ <template #trigger>
+ <NInput
+ v-model:value="state.externalUrl"
+ class="mb-4 w-full"
+ :disabled="slotProps.disabled || isSaaSMode || externalUrlFromFlag"
+ />
+ </template>
+ <span class="text-sm text-gray-400 -translate-y-2">
+ {{
+ externalUrlFromFlag
+ ? $t("settings.general.workspace.external-url.cannot-edit-flag")
+ : ''
+ }}
+ </span>
+ </NTooltip>
+ </PermissionGuardWrapper>
</div>
</div>
@@ -87,6 +93,7 @@ import { storeToRefs } from "pinia";
import { computed, reactive, ref } from "vue";
import { BBModal } from "@/bbkit";
import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { router } from "@/router";
import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
import { useActuatorV1Store, useSettingV1Store } from "@/store";
@@ -116,7 +123,6 @@ const getInitialState = (): LocalState => {
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const settingV1Store = useSettingV1Store();
diff --git a/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue b/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue
index 8a6e307fb5..c20c91682b 100644
--- a/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue
+++ b/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue
@@ -8,27 +8,36 @@
<p class="text-sm text-gray-400 mt-1">
{{ $t("settings.general.workspace.maximum-role-expiration.description") }}
</p>
- <div class="mt-3 w-full flex flex-row justify-start items-center gap-4">
- <NInputNumber
- v-model:value="state.inputValue"
- class="w-60"
- :disabled="!allowEdit || state.neverExpire"
- :min="1"
- :precision="0"
+ <div class="mt-3 w-full flex flex-row">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
>
- <template #suffix>
- {{ $t("settings.general.workspace.maximum-role-expiration.days") }}
- </template>
- </NInputNumber>
- <NCheckbox
- :disabled="!allowEdit"
- v-model:checked="state.neverExpire"
- style="margin-right: 12px"
- >
- {{
- $t("settings.general.workspace.maximum-role-expiration.never-expires")
- }}
- </NCheckbox>
+ <div class="flex items-center gap-4">
+ <NInputNumber
+ v-model:value="state.inputValue"
+ class="w-60"
+ :disabled="slotProps.disabled || state.neverExpire"
+ :min="1"
+ :precision="0"
+ >
+ <template #suffix>
+ {{ $t("settings.general.workspace.maximum-role-expiration.days") }}
+ </template>
+ </NInputNumber>
+ <NCheckbox
+ :disabled="slotProps.disabled"
+ v-model:checked="state.neverExpire"
+ style="margin-right: 12px"
+ >
+ {{
+ $t("settings.general.workspace.maximum-role-expiration.never-expires")
+ }}
+ </NCheckbox>
+ </div>
+ </PermissionGuardWrapper>
</div>
</div>
</template>
@@ -39,6 +48,7 @@ import { DurationSchema, FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { isEqual } from "lodash-es";
import { NCheckbox, NInputNumber } from "naive-ui";
import { computed, reactive } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { useSettingV1Store } from "@/store/modules/v1/setting";
const DEFAULT_EXPIRATION_DAYS = 90;
@@ -64,10 +74,6 @@ const getInitialState = (): LocalState => {
return defaultState;
};
-defineProps<{
- allowEdit: boolean;
-}>();
-
const settingV1Store = useSettingV1Store();
const state = reactive<LocalState>(getInitialState());
diff --git a/frontend/src/components/GeneralSetting/MaximumSQLResultSizeSetting.vue b/frontend/src/components/GeneralSetting/MaximumSQLResultSizeSetting.vue
index 42bd0449ce..a69a7823cb 100644
--- a/frontend/src/components/GeneralSetting/MaximumSQLResultSizeSetting.vue
+++ b/frontend/src/components/GeneralSetting/MaximumSQLResultSizeSetting.vue
@@ -28,21 +28,29 @@
</span>
</p>
<div class="mt-3 w-full flex flex-row justify-start items-center gap-4">
- <NInputNumber
- :value="queryRestriction.maximumResultSize"
- :disabled="!allowEdit"
- class="w-60"
- :min="1"
- :precision="0"
- @update:value="
- handleInput(
- $event,
- (val: number) => (queryRestriction.maximumResultSize = val)
- )
- "
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
>
- <template #suffix> MB </template>
- </NInputNumber>
+ <NInputNumber
+ :value="queryRestriction.maximumResultSize"
+ :disabled="!hasQueryPolicyFeature || slotProps.disabled"
+ class="w-60"
+ :min="1"
+ :precision="0"
+ @update:value="
+ handleInput(
+ $event,
+ (val: number) => (queryRestriction.maximumResultSize = val)
+ )
+ "
+ >
+ <template #suffix> MB </template>
+ </NInputNumber>
+ </PermissionGuardWrapper>
</div>
</div>
<div>
@@ -69,23 +77,31 @@
</span>
</p>
<div class="mt-3 w-full flex flex-row justify-start items-center gap-4">
- <NInputNumber
- :value="queryRestriction.maximumResultRows"
- :disabled="!allowEdit"
- class="w-60"
- :min="-1"
- :precision="0"
- @update:value="
- handleInput(
- $event,
- (val: number) => (queryRestriction.maximumResultRows = val)
- )
- "
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
>
- <template #suffix>{{
- $t("settings.general.workspace.maximum-sql-result.rows.rows")
- }}</template>
- </NInputNumber>
+ <NInputNumber
+ :value="queryRestriction.maximumResultRows"
+ :disabled="!hasQueryPolicyFeature || slotProps.disabled"
+ class="w-60"
+ :min="-1"
+ :precision="0"
+ @update:value="
+ handleInput(
+ $event,
+ (val: number) => (queryRestriction.maximumResultRows = val)
+ )
+ "
+ >
+ <template #suffix>{{
+ $t("settings.general.workspace.maximum-sql-result.rows.rows")
+ }}</template>
+ </NInputNumber>
+ </PermissionGuardWrapper>
</div>
</div>
</div>
@@ -97,19 +113,25 @@ import { isEqual } from "lodash-es";
import { CircleQuestionMarkIcon } from "lucide-vue-next";
import { NInputNumber, NTooltip } from "naive-ui";
import { computed, ref } from "vue";
-import { DEFAULT_MAX_RESULT_SIZE_IN_MB, usePolicyV1Store } from "@/store";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
+import {
+ DEFAULT_MAX_RESULT_SIZE_IN_MB,
+ featureToRef,
+ usePolicyV1Store,
+} from "@/store";
import {
PolicyResourceType,
PolicyType,
type QueryDataPolicy,
QueryDataPolicySchema,
} from "@/types/proto-es/v1/org_policy_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { FeatureBadge } from "../FeatureGuard";
const props = defineProps<{
- allowEdit: boolean;
resource: string;
+ project?: Project;
policy: QueryDataPolicy;
tooltip?: string;
}>();
@@ -130,6 +152,8 @@ const queryRestriction = ref<{
maximumResultRows: number;
}>(initialState());
+const hasQueryPolicyFeature = featureToRef(PlanFeature.FEATURE_QUERY_POLICY);
+
const allowUpdate = computed(() => {
return !isEqual(initialState(), queryRestriction.value);
});
diff --git a/frontend/src/components/GeneralSetting/PasswordRestrictionSetting.vue b/frontend/src/components/GeneralSetting/PasswordRestrictionSetting.vue
index 6417208c56..0be1b0d12e 100644
--- a/frontend/src/components/GeneralSetting/PasswordRestrictionSetting.vue
+++ b/frontend/src/components/GeneralSetting/PasswordRestrictionSetting.vue
@@ -6,153 +6,160 @@
{{ $t("settings.general.workspace.password-restriction.self") }}
<FeatureBadge :feature="PlanFeature.FEATURE_PASSWORD_RESTRICTIONS" />
</p>
- <div class="w-full flex flex-col gap-y-3">
- <div class="flex items-center">
- <NInputNumber
- :value="state.minLength"
- :disabled="!allowEdit"
- class="w-24 mr-2"
- :min="1"
- :placeholder="'Minimum length'"
- :precision="0"
- size="small"
- @update:value="
- (val) =>
- onUpdate({
- minLength: Math.max(
- val || DEFAULT_MIN_LENGTH,
- DEFAULT_MIN_LENGTH
- ),
- })
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <div class="flex flex-col gap-y-3">
+ <div class="flex items-center">
+ <NInputNumber
+ :value="state.minLength"
+ :disabled="slotProps.disabled"
+ class="w-24 mr-2"
+ :min="1"
+ :placeholder="'Minimum length'"
+ :precision="0"
+ size="small"
+ @update:value="
+ (val) =>
+ onUpdate({
+ minLength: Math.max(
+ val || DEFAULT_MIN_LENGTH,
+ DEFAULT_MIN_LENGTH
+ ),
+ })
+ "
+ />
+ {{
+ $t("settings.general.workspace.password-restriction.min-length", {
+ min: state.minLength || DEFAULT_MIN_LENGTH,
+ })
+ }}
+ </div>
+ <NCheckbox
+ :checked="state.requireNumber"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (val) => {
+ onUpdate({ requireNumber: val });
+ }
"
- />
- {{
- $t("settings.general.workspace.password-restriction.min-length", {
- min: state.minLength || DEFAULT_MIN_LENGTH,
- })
- }}
- </div>
- <NCheckbox
- :checked="state.requireNumber"
- :disabled="!allowEdit"
- @update:checked="
- (val) => {
- onUpdate({ requireNumber: val });
- }
- "
- >
- {{
- $t("settings.general.workspace.password-restriction.require-number")
- }}
- </NCheckbox>
- <NCheckbox
- :checked="state.requireLetter"
- :disabled="!allowEdit"
- @update:checked="
- (val) => {
- onUpdate({ requireLetter: val });
- }
- "
- >
- {{
- $t("settings.general.workspace.password-restriction.require-letter")
- }}
- </NCheckbox>
- <NCheckbox
- :checked="state.requireUppercaseLetter"
- :disabled="!allowEdit"
- @update:checked="
- (val) => {
- onUpdate({ requireUppercaseLetter: val });
- }
- "
- >
- {{
- $t(
- "settings.general.workspace.password-restriction.require-uppercase-letter"
- )
- }}
- </NCheckbox>
- <NCheckbox
- :checked="state.requireSpecialCharacter"
- :disabled="!allowEdit"
- @update:checked="
- (val) => {
- onUpdate({ requireSpecialCharacter: val });
- }
- "
- >
- {{
- $t(
- "settings.general.workspace.password-restriction.require-special-character"
- )
- }}
- </NCheckbox>
- <NCheckbox
- :checked="state.requireResetPasswordForFirstLogin"
- :disabled="!allowEdit"
- @update:checked="
- (val) => {
- onUpdate({ requireResetPasswordForFirstLogin: val });
- }
- "
- >
- {{
- $t(
- "settings.general.workspace.password-restriction.require-reset-password-for-first-login"
- )
- }}
- </NCheckbox>
- <NCheckbox
- :checked="!!state.passwordRotation"
- :disabled="!allowEdit"
- class="flex! items-center!"
- @update:checked="
- (checked) => {
- if (checked) {
- onUpdate({
- passwordRotation: create(DurationSchema, {
- seconds: BigInt(7 * 24 * 60 * 60) /* default 7 days */,
- nanos: 0,
- }),
- });
- } else {
- delete state.passwordRotation;
+ >
+ {{
+ $t("settings.general.workspace.password-restriction.require-number")
+ }}
+ </NCheckbox>
+ <NCheckbox
+ :checked="state.requireLetter"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (val) => {
+ onUpdate({ requireLetter: val });
}
- }
- "
- >
- <i18n-t
- tag="div"
- keypath="settings.general.workspace.password-restriction.password-rotation"
- class="flex items-center gap-x-2"
+ "
>
- <template #day>
- <NInputNumber
- v-if="state.passwordRotation"
- :value="Number(state.passwordRotation.seconds) / (24 * 60 * 60)"
- :disabled="!allowEdit"
- :min="1"
- class="w-24 mx-2"
- :size="'small'"
- :placeholder="'Minimum length'"
- :precision="0"
- @click="(e: MouseEvent) => e.stopPropagation()"
- @update:value="
- (val) =>
- onUpdate({
- passwordRotation: create(DurationSchema, {
- seconds: BigInt((val || 1) * 24 * 60 * 60),
- nanos: 0,
- }),
- })
- "
- />
- <span v-else class="mx-1">N</span>
- </template>
- </i18n-t>
- </NCheckbox>
- </div>
+ {{
+ $t("settings.general.workspace.password-restriction.require-letter")
+ }}
+ </NCheckbox>
+ <NCheckbox
+ :checked="state.requireUppercaseLetter"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (val) => {
+ onUpdate({ requireUppercaseLetter: val });
+ }
+ "
+ >
+ {{
+ $t(
+ "settings.general.workspace.password-restriction.require-uppercase-letter"
+ )
+ }}
+ </NCheckbox>
+ <NCheckbox
+ :checked="state.requireSpecialCharacter"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (val) => {
+ onUpdate({ requireSpecialCharacter: val });
+ }
+ "
+ >
+ {{
+ $t(
+ "settings.general.workspace.password-restriction.require-special-character"
+ )
+ }}
+ </NCheckbox>
+ <NCheckbox
+ :checked="state.requireResetPasswordForFirstLogin"
+ :disabled="slotProps.disabled"
+ @update:checked="
+ (val) => {
+ onUpdate({ requireResetPasswordForFirstLogin: val });
+ }
+ "
+ >
+ {{
+ $t(
+ "settings.general.workspace.password-restriction.require-reset-password-for-first-login"
+ )
+ }}
+ </NCheckbox>
+ <NCheckbox
+ :checked="!!state.passwordRotation"
+ :disabled="slotProps.disabled"
+ class="flex! items-center!"
+ @update:checked="
+ (checked) => {
+ if (checked) {
+ onUpdate({
+ passwordRotation: create(DurationSchema, {
+ seconds: BigInt(7 * 24 * 60 * 60) /* default 7 days */,
+ nanos: 0,
+ }),
+ });
+ } else {
+ delete state.passwordRotation;
+ }
+ }
+ "
+ >
+ <i18n-t
+ tag="div"
+ keypath="settings.general.workspace.password-restriction.password-rotation"
+ class="flex items-center gap-x-2"
+ >
+ <template #day>
+ <NInputNumber
+ v-if="state.passwordRotation"
+ :value="Number(state.passwordRotation.seconds) / (24 * 60 * 60)"
+ :disabled="slotProps.disabled"
+ :min="1"
+ class="w-24 mx-2"
+ :size="'small'"
+ :placeholder="'Minimum length'"
+ :precision="0"
+ @click="(e: MouseEvent) => e.stopPropagation()"
+ @update:value="
+ (val) =>
+ onUpdate({
+ passwordRotation: create(DurationSchema, {
+ seconds: BigInt((val || 1) * 24 * 60 * 60),
+ nanos: 0,
+ }),
+ })
+ "
+ />
+ <span v-else class="mx-1">N</span>
+ </template>
+ </i18n-t>
+ </NCheckbox>
+ </div>
+ </PermissionGuardWrapper>
</div>
<FeatureModal
@@ -168,6 +175,7 @@ import { DurationSchema, FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { cloneDeep, isEqual } from "lodash-es";
import { NCheckbox, NInputNumber } from "naive-ui";
import { computed, reactive, ref } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { featureToRef } from "@/store";
import { useSettingV1Store } from "@/store/modules/v1/setting";
import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";
@@ -177,10 +185,6 @@ import { FeatureBadge, FeatureModal } from "../FeatureGuard";
const DEFAULT_MIN_LENGTH = 8;
-defineProps<{
- allowEdit: boolean;
-}>();
-
const settingV1Store = useSettingV1Store();
const showFeatureModal = ref<boolean>(false);
const hasPasswordFeature = featureToRef(
diff --git a/frontend/src/components/GeneralSetting/QueryDataPolicySetting.vue b/frontend/src/components/GeneralSetting/QueryDataPolicySetting.vue
index 838543b43f..ec1d891dec 100644
--- a/frontend/src/components/GeneralSetting/QueryDataPolicySetting.vue
+++ b/frontend/src/components/GeneralSetting/QueryDataPolicySetting.vue
@@ -1,75 +1,91 @@
<template>
- <div class="flex-1 flex flex-col gap-y-6">
+ <div v-if="hasGetPermission" class="flex-1 flex flex-col gap-y-6">
<div>
- <div class="flex items-center gap-x-2">
+ <div class="flex items-center gap-x-2">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
<Switch
:value="!disableExport"
:text="true"
- :disabled="disabled"
+ :disabled="slotProps.disabled || !hasQueryPolicyFeature"
@update:value="(val: boolean) => disableExport = !val"
/>
- <span class="font-medium">
- {{ $t("settings.general.workspace.data-export.enable") }}
+ </PermissionGuardWrapper>
+ <span class="font-medium">
+ {{ $t("settings.general.workspace.data-export.enable") }}
+ </span>
+ <NTooltip v-if="tooltip">
+ <template #trigger>
+ <CircleQuestionMarkIcon class="w-4 textinfolabel" />
+ </template>
+ <span>
+ {{ tooltip }}
</span>
- <NTooltip v-if="scope">
- <template #trigger>
- <CircleQuestionMarkIcon class="w-4 textinfolabel" />
- </template>
- <span>
- {{ $t("settings.general.workspace.query-data-policy.tooltip", { scope }) }}
- </span>
- </NTooltip>
- </div>
- <div class="mt-1 text-sm text-gray-400">
- {{ $t("settings.general.workspace.data-export.description") }}
- </div>
+ </NTooltip>
+ </div>
+ <div class="mt-1 text-sm text-gray-400">
+ {{ $t("settings.general.workspace.data-export.description") }}
</div>
- <MaximumSQLResultSizeSetting
- ref="maximumSQLResultSizeSettingRef"
- :allow-edit="!disabled"
- :resource="resource"
- :policy="policyPayload"
- :tooltip="scope ? $t('settings.general.workspace.query-data-policy.tooltip', { scope }) : ''"
- />
- <div>
- <p class="font-medium flex flex-row justify-start items-center">
- <span class="mr-2">
- {{ $t("settings.general.workspace.query-data-policy.timeout.self") }}
- </span>
- <FeatureBadge :feature="PlanFeature.FEATURE_QUERY_POLICY" />
- <NTooltip v-if="scope">
- <template #trigger>
- <CircleQuestionMarkIcon class="w-4 textinfolabel" />
- </template>
- <span>
- {{ $t("settings.general.workspace.query-data-policy.tooltip", { scope }) }}
+ </div>
+ <MaximumSQLResultSizeSetting
+ ref="maximumSQLResultSizeSettingRef"
+ :resource="resource"
+ :policy="policyPayload"
+ :tooltip="tooltip"
+ :project="project"
+ />
+ <div>
+ <p class="font-medium flex flex-row justify-start items-center">
+ <span class="mr-2">
+ {{ $t("settings.general.workspace.query-data-policy.timeout.self") }}
</span>
- </NTooltip>
- </p>
- <p class="text-sm text-gray-400 mt-1">
- {{
- $t("settings.general.workspace.query-data-policy.timeout.description")
- }}
- <span class="font-semibold! textinfolabel">
- {{ $t("settings.general.workspace.no-limit") }}
- </span>
- </p>
- <div class="mt-3 w-full flex flex-row justify-start items-center gap-4">
- <NInputNumber
- :value="maxQueryTimeInseconds"
- :disabled="disabled"
- class="w-60"
- :min="0"
- :precision="0"
- @update:value="handleInput"
- >
- <template #suffix>{{
- $t("settings.general.workspace.query-data-policy.seconds")
- }}</template>
- </NInputNumber>
+ <FeatureBadge :feature="PlanFeature.FEATURE_QUERY_POLICY" />
+ <NTooltip v-if="tooltip">
+ <template #trigger>
+ <CircleQuestionMarkIcon class="w-4 textinfolabel" />
+ </template>
+ <span>
+ {{ tooltip }}
+ </span>
+ </NTooltip>
+ </p>
+ <p class="text-sm text-gray-400 mt-1">
+ {{
+ $t("settings.general.workspace.query-data-policy.timeout.description")
+ }}
+ <span class="font-semibold! textinfolabel">
+ {{ $t("settings.general.workspace.no-limit") }}
+ </span>
+ </p>
+ <div class="mt-3 w-full flex flex-row justify-start items-center gap-4">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
+ >
+ <NInputNumber
+ :value="maxQueryTimeInseconds"
+ :disabled="!hasQueryPolicyFeature || slotProps.disabled"
+ class="w-60"
+ :min="0"
+ :precision="0"
+ @update:value="handleInput"
+ >
+ <template #suffix>{{
+ $t("settings.general.workspace.query-data-policy.seconds")
+ }}</template>
+ </NInputNumber>
+ </PermissionGuardWrapper>
+ </div>
</div>
</div>
- </div>
</template>
<script lang="ts" setup>
@@ -78,39 +94,63 @@ import { DurationSchema } from "@bufbuild/protobuf/wkt";
import { CircleQuestionMarkIcon } from "lucide-vue-next";
import { NInputNumber, NTooltip } from "naive-ui";
import { computed, ref, watch } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { Switch } from "@/components/v2";
import { t } from "@/plugins/i18n";
import {
featureToRef,
usePolicyByParentAndType,
usePolicyV1Store,
+ useProjectV1Store,
} from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
+import { isValidProjectName } from "@/types";
import {
PolicyResourceType,
PolicyType,
QueryDataPolicySchema,
} from "@/types/proto-es/v1/org_policy_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
import { FeatureBadge } from "../FeatureGuard";
import MaximumSQLResultSizeSetting from "./MaximumSQLResultSizeSetting.vue";
const props = defineProps<{
resource: string;
- allowEdit: boolean;
}>();
const policyV1Store = usePolicyV1Store();
+const projectStore = useProjectV1Store();
+
const hasQueryPolicyFeature = featureToRef(PlanFeature.FEATURE_QUERY_POLICY);
-const scope = computed(() => {
+const project = computed(() => {
if (props.resource.startsWith(projectNamePrefix)) {
- return t("settings.general.workspace.query-data-policy.workspace-scope");
+ const proj = projectStore.getProjectByName(props.resource);
+ if (!isValidProjectName(proj.name)) {
+ return undefined;
+ }
+ return proj;
}
- if (props.resource === "") {
- return t("settings.general.workspace.query-data-policy.project-scope");
+ return undefined;
+});
+
+const hasGetPermission = computed(() => {
+ if (project.value) {
+ return hasProjectPermissionV2(project.value, "bb.policies.get");
}
- return "";
+ return hasWorkspacePermissionV2("bb.policies.get");
+});
+
+const tooltip = computed(() => {
+ if (project.value) {
+ return t("settings.general.workspace.query-data-policy.tooltip", {
+ scope: t("settings.general.workspace.query-data-policy.workspace-scope"),
+ });
+ }
+ return t("settings.general.workspace.query-data-policy.tooltip", {
+ scope: t("settings.general.workspace.query-data-policy.project-scope"),
+ });
});
const { ready } = usePolicyByParentAndType(
@@ -150,10 +190,6 @@ watch(
}
);
-const disabled = computed(
- () => !props.allowEdit || !hasQueryPolicyFeature.value
-);
-
const isDirty = computed(() => {
return (
maxQueryTimeInseconds.value !== initialMaxQueryTimeInseconds.value ||
diff --git a/frontend/src/components/GeneralSetting/SecuritySetting.vue b/frontend/src/components/GeneralSetting/SecuritySetting.vue
index 2c7643647c..c4aee1f012 100644
--- a/frontend/src/components/GeneralSetting/SecuritySetting.vue
+++ b/frontend/src/components/GeneralSetting/SecuritySetting.vue
@@ -6,19 +6,23 @@
{{ title }}
</h1>
</div>
- <span v-if="!allowEdit" class="text-sm text-gray-400">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
</div>
<div class="flex-1 lg:px-4 flex flex-col gap-y-6">
<div>
<div class="flex items-center gap-x-2">
- <Switch
- v-model:value="enableWatermark"
- :text="true"
- :disabled="!allowEdit || !hasWatermarkFeature"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <Switch
+ v-model:value="enableWatermark"
+ :text="true"
+ :disabled="slotProps.disabled || !hasWatermarkFeature"
+ />
+ </PermissionGuardWrapper>
<span class="font-medium">
{{ $t("settings.general.workspace.watermark.enable") }}
</span>
@@ -31,15 +35,12 @@
<QueryDataPolicySetting
ref="queryDataPolicySettingRef"
resource=""
- :allow-edit="hasPermission"
/>
<MaximumRoleExpirationSetting
ref="maximumRoleExpirationSettingRef"
- :allow-edit="allowEdit"
/>
<DomainRestrictionSetting
ref="domainRestrictionSettingRef"
- :allow-edit="allowEdit"
/>
</div>
</div>
@@ -49,10 +50,10 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { computed, ref } from "vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { Switch } from "@/components/v2";
import { featureToRef, useSettingV1Store } from "@/store";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { hasWorkspacePermissionV2 } from "@/utils";
import { FeatureBadge } from "../FeatureGuard";
import DomainRestrictionSetting from "./DomainRestrictionSetting.vue";
import MaximumRoleExpirationSetting from "./MaximumRoleExpirationSetting.vue";
@@ -60,14 +61,10 @@ import QueryDataPolicySetting from "./QueryDataPolicySetting.vue";
const props = defineProps<{
title: string;
- allowEdit: boolean;
}>();
const settingV1Store = useSettingV1Store();
const hasWatermarkFeature = featureToRef(PlanFeature.FEATURE_WATERMARK);
-const hasPermission = computed(() =>
- hasWorkspacePermissionV2("bb.policies.update")
-);
const domainRestrictionSettingRef =
ref<InstanceType<typeof DomainRestrictionSetting>>();
diff --git a/frontend/src/components/GeneralSetting/TokenDurationSetting.vue b/frontend/src/components/GeneralSetting/TokenDurationSetting.vue
index b1615822a1..2fe6695124 100644
--- a/frontend/src/components/GeneralSetting/TokenDurationSetting.vue
+++ b/frontend/src/components/GeneralSetting/TokenDurationSetting.vue
@@ -10,36 +10,36 @@
<p class="text-sm text-gray-400 mt-1">
{{ $t("settings.general.workspace.access-token-duration.description") }}
</p>
- <NTooltip placement="top-start" :disabled="allowChangeSetting">
- <template #trigger>
- <div class="mt-3 w-full flex flex-row justify-start items-center">
- <NInputNumber
- v-model:value="state.accessTokenDuration"
- class="w-24 mr-4"
- :disabled="!allowChangeSetting"
- :min="1"
- :max="state.accessTokenTimeFormat === 'MINUTES' ? 59 : 23"
- :precision="0"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <div class="mt-3 flex flex-row justify-start items-center">
+ <NInputNumber
+ v-model:value="state.accessTokenDuration"
+ class="w-24 mr-4"
+ :disabled="!hasSecureTokenFeature || slotProps.disabled"
+ :min="1"
+ :max="state.accessTokenTimeFormat === 'MINUTES' ? 59 : 23"
+ :precision="0"
+ />
+ <NRadioGroup
+ v-model:value="state.accessTokenTimeFormat"
+ :disabled="!hasSecureTokenFeature || slotProps.disabled"
+ >
+ <NRadio
+ :value="'MINUTES'"
+ :label="$t('settings.general.workspace.access-token-duration.minutes')"
/>
- <NRadioGroup
- v-model:value="state.accessTokenTimeFormat"
- :disabled="!allowChangeSetting"
- >
- <NRadio
- :value="'MINUTES'"
- :label="$t('settings.general.workspace.access-token-duration.minutes')"
- />
- <NRadio
- :value="'HOURS'"
- :label="$t('settings.general.workspace.access-token-duration.hours')"
- />
- </NRadioGroup>
- </div>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
+ <NRadio
+ :value="'HOURS'"
+ :label="$t('settings.general.workspace.access-token-duration.hours')"
+ />
+ </NRadioGroup>
+ </div>
+ </PermissionGuardWrapper>
</div>
<!-- Refresh Token Duration -->
@@ -53,36 +53,36 @@
<p class="text-sm text-gray-400 mt-1">
{{ $t("settings.general.workspace.refresh-token-duration.description") }}
</p>
- <NTooltip placement="top-start" :disabled="allowChangeSetting">
- <template #trigger>
- <div class="mt-3 w-full flex flex-row justify-start items-center">
- <NInputNumber
- v-model:value="state.refreshTokenDuration"
- class="w-24 mr-4"
- :disabled="!allowChangeSetting"
- :min="1"
- :max="state.refreshTokenTimeFormat === 'HOURS' ? 23 : undefined"
- :precision="0"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <div class="mt-3 w-full flex flex-row justify-start items-center">
+ <NInputNumber
+ v-model:value="state.refreshTokenDuration"
+ class="w-24 mr-4"
+ :disabled="!hasSecureTokenFeature || slotProps.disabled"
+ :min="1"
+ :max="state.refreshTokenTimeFormat === 'HOURS' ? 23 : undefined"
+ :precision="0"
+ />
+ <NRadioGroup
+ v-model:value="state.refreshTokenTimeFormat"
+ :disabled="!hasSecureTokenFeature || slotProps.disabled"
+ >
+ <NRadio
+ :value="'HOURS'"
+ :label="$t('settings.general.workspace.refresh-token-duration.hours')"
/>
- <NRadioGroup
- v-model:value="state.refreshTokenTimeFormat"
- :disabled="!allowChangeSetting"
- >
- <NRadio
- :value="'HOURS'"
- :label="$t('settings.general.workspace.refresh-token-duration.hours')"
- />
- <NRadio
- :value="'DAYS'"
- :label="$t('settings.general.workspace.refresh-token-duration.days')"
- />
- </NRadioGroup>
- </div>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
- </span>
- </NTooltip>
+ <NRadio
+ :value="'DAYS'"
+ :label="$t('settings.general.workspace.refresh-token-duration.days')"
+ />
+ </NRadioGroup>
+ </div>
+ </PermissionGuardWrapper>
</div>
<div class="mb-7 mt-4 lg:mt-0" @click="handleValueFieldClick">
@@ -100,26 +100,26 @@
{{ $t("settings.general.workspace.no-limit") }}
</span>
</p>
- <NTooltip placement="top-start" :disabled="allowChangeSetting">
- <template #trigger>
- <div class="mt-3 w-full flex flex-row justify-start items-center">
- <NInputNumber
- v-model:value="state.inactiveTimeout"
- class="w-24 mr-4"
- :min="-1"
- :disabled="!allowChangeSetting"
- />
- <span class="textinfo text-sm">
- {{
- $t("settings.general.workspace.inactive-session-timeout.hours")
- }}
- </span>
- </div>
- </template>
- <span class="text-sm text-gray-400 -translate-y-2">
- {{ $t("settings.general.workspace.only-admin-can-edit") }}
+ <div class="mt-3 w-full flex flex-row justify-start items-center">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <NInputNumber
+ v-model:value="state.inactiveTimeout"
+ class="w-24 mr-4"
+ :min="-1"
+ :disabled="!hasSecureTokenFeature || slotProps.disabled"
+ />
+ </PermissionGuardWrapper>
+ <span class="textinfo text-sm">
+ {{
+ $t("settings.general.workspace.inactive-session-timeout.hours")
+ }}
</span>
- </NTooltip>
+ </div>
</div>
<FeatureModal
@@ -133,9 +133,10 @@
import { create } from "@bufbuild/protobuf";
import { DurationSchema, FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { isEqual } from "lodash-es";
-import { NInputNumber, NRadio, NRadioGroup, NTooltip } from "naive-ui";
+import { NInputNumber, NRadio, NRadioGroup } from "naive-ui";
import { computed, reactive, watch } from "vue";
import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { featureToRef } from "@/store";
import { useSettingV1Store } from "@/store/modules/v1/setting";
import {
@@ -209,10 +210,6 @@ const getInitialState = (): LocalState => {
return defaultState;
};
-const props = defineProps<{
- allowEdit: boolean;
-}>();
-
const settingV1Store = useSettingV1Store();
const state = reactive<LocalState>(getInitialState());
@@ -220,10 +217,6 @@ const hasSecureTokenFeature = featureToRef(
PlanFeature.FEATURE_TOKEN_DURATION_CONTROL
);
-const allowChangeSetting = computed(() => {
- return hasSecureTokenFeature.value && props.allowEdit;
-});
-
const handleValueFieldClick = () => {
if (!hasSecureTokenFeature.value) {
state.showFeatureModal = true;
diff --git a/frontend/src/components/Permission/ComponentPermissionGuard.vue b/frontend/src/components/Permission/ComponentPermissionGuard.vue
new file mode 100644
index 0000000000..663f30d116
--- /dev/null
+++ b/frontend/src/components/Permission/ComponentPermissionGuard.vue
@@ -0,0 +1,73 @@
+<template>
+ <slot v-if="missedPermissions.length === 0" />
+ <NoPermissionPlaceholder
+ v-else
+ v-bind="$attrs"
+ :path="requestPath"
+ :resources="project ? [project.name] : []"
+ :permissions="missedPermissions"
+ >
+ <template #action>
+ <div v-if="allowRequestRole" class="mt-2">
+ <NButton
+ type="primary"
+ @click="showRequestRolePanel = true"
+ >
+ <template #icon>
+ <heroicons-outline:user-add class="w-4 h-4" />
+ </template>
+ {{ $t("issue.title.request-role") }}
+ </NButton>
+ </div>
+ </template>
+ </NoPermissionPlaceholder>
+
+ <GrantRequestPanel
+ v-if="showRequestRolePanel && project"
+ :project-name="project.name"
+ @close="showRequestRolePanel = false"
+ />
+</template>
+
+
+<script lang="tsx" setup>
+import { NButton } from "naive-ui";
+import { computed, ref } from "vue";
+import { useRouter } from "vue-router";
+import GrantRequestPanel from "@/components/GrantRequestPanel";
+import NoPermissionPlaceholder from "@/components/Permission/NoPermissionPlaceholder.vue";
+import { hasFeature } from "@/store";
+import { type Permission } from "@/types";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
+
+const props = defineProps<{
+ project?: Project;
+ permissions: Permission[];
+}>();
+
+const showRequestRolePanel = ref(false);
+const router = useRouter();
+const allowRequestRole = computed(() => {
+ return (
+ props.project?.allowRequestRole &&
+ hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW) &&
+ hasProjectPermissionV2(props.project, "bb.issues.create") &&
+ hasWorkspacePermissionV2("bb.roles.list")
+ );
+});
+
+const requestPath = computed(() => {
+ return router.currentRoute.value.fullPath;
+});
+
+const missedPermissions = computed(() => {
+ if (props.project) {
+ return props.permissions.filter(
+ (p) => !hasProjectPermissionV2(props.project!, p)
+ );
+ }
+ return props.permissions.filter((p) => !hasWorkspacePermissionV2(p));
+});
+</script>
\ No newline at end of file
diff --git a/frontend/src/components/Permission/RoutePermissionGuard.vue b/frontend/src/components/Permission/RoutePermissionGuard.vue
index 2d3f74e883..a0e190e632 100644
--- a/frontend/src/components/Permission/RoutePermissionGuard.vue
+++ b/frontend/src/components/Permission/RoutePermissionGuard.vue
@@ -1,84 +1,32 @@
<template>
- <slot v-if="missedPermissions.length === 0" />
- <NoPermissionPlaceholder
- v-else
- v-bind="$attrs"
- :path="requestPath"
- :resources="project ? [project.name] : []"
- :permissions="missedPermissions"
- >
- <template #action>
- <div v-if="allowRequestRole" class="mt-2">
- <NButton
- type="primary"
- @click="showRequestRolePanel = true"
- >
- <template #icon>
- <heroicons-outline:user-add class="w-4 h-4" />
- </template>
- {{ $t("issue.title.request-role") }}
- </NButton>
- </div>
- </template>
- </NoPermissionPlaceholder>
-
- <GrantRequestPanel
- v-if="showRequestRolePanel && project"
- :project-name="project.name"
- @close="showRequestRolePanel = false"
- />
+ <ComponentPermissionGuard :project="project" :permissions="requiredPermissions">
+ <slot />
+ </ComponentPermissionGuard>
</template>
<script lang="tsx" setup>
-import { NButton } from "naive-ui";
-import { computed, ref } from "vue";
+import { computed } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { useRouter } from "vue-router";
-import GrantRequestPanel from "@/components/GrantRequestPanel";
-import NoPermissionPlaceholder from "@/components/Permission/NoPermissionPlaceholder.vue";
import { getFlattenRoutes } from "@/components/v2/Sidebar/utils.ts";
-import { hasFeature } from "@/store";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
+import ComponentPermissionGuard from "./ComponentPermissionGuard.vue";
const props = defineProps<{
project?: Project;
routes: RouteRecordRaw[];
}>();
-const showRequestRolePanel = ref(false);
const router = useRouter();
-const allowRequestRole = computed(() => {
- return (
- props.project?.allowRequestRole &&
- hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW) &&
- hasProjectPermissionV2(props.project, "bb.issues.create") &&
- hasWorkspacePermissionV2("bb.roles.list")
- );
-});
const flattenRoutes = computed(() => {
return getFlattenRoutes(props.routes);
});
-const requestPath = computed(() => {
- return router.currentRoute.value.fullPath;
-});
-
const requiredPermissions = computed(() => {
const routeConfig = flattenRoutes.value.find(
(workspaceRoute) => workspaceRoute.name === router.currentRoute.value.name
);
return routeConfig?.permissions ?? [];
});
-
-const missedPermissions = computed(() => {
- if (props.project) {
- return requiredPermissions.value.filter(
- (p) => !hasProjectPermissionV2(props.project!, p)
- );
- }
- return requiredPermissions.value.filter((p) => !hasWorkspacePermissionV2(p));
-});
</script>
\ No newline at end of file
diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue
index c5702b3209..419a528bfe 100644
--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue
+++ b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue
@@ -7,7 +7,7 @@
{{ $t("settings.general.workspace.maximum-sql-result.size.self") }}
</span>
<span class=" font-medium">
- {{ Number(effectiveQueryDataPolicy.maximumResultSize) / 1024 / 1024 }} MB
+ {{ Number(policy.maximumResultSize) / 1024 / 1024 }} MB
</span>
</div>
<div class="flex items-center gap-x-2">
@@ -24,17 +24,18 @@
<script lang="tsx" setup>
import { computed } from "vue";
import { t } from "@/plugins/i18n";
-import { useCurrentProjectV1, usePolicyV1Store } from "@/store";
+import {
+ useCurrentProjectV1,
+ useEffectiveQueryDataPolicyForProject,
+} from "@/store";
-const policyStore = usePolicyV1Store();
const { project } = useCurrentProjectV1();
-
-const effectiveQueryDataPolicy = computed(() => {
- return policyStore.getEffectiveQueryDataPolicyForProject(project.value.name);
-});
+const { policy } = useEffectiveQueryDataPolicyForProject(
+ computed(() => project.value.name)
+);
const maximumResultRows = computed(() => {
- const { maximumResultRows } = effectiveQueryDataPolicy.value;
+ const { maximumResultRows } = policy.value;
if (maximumResultRows === Number.MAX_VALUE) {
return t("common.unlimited");
}
diff --git a/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue b/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
index b43a84381d..b3f1c3c3a4 100644
--- a/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
+++ b/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
@@ -5,13 +5,21 @@
{{ $t("common.name") }}
<RequiredStar />
</div>
- <NInput
- id="projectName"
- class="mt-1"
- v-model:value="state.title"
- :disabled="!allowEdit"
- required
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.projects.update'
+ ]"
+ >
+ <NInput
+ id="projectName"
+ class="mt-1"
+ v-model:value="state.title"
+ :disabled="slotProps.disabled"
+ required
+ />
+ </PermissionGuardWrapper>
<div class="mt-1">
<ResourceIdField
resource-type="project"
@@ -30,12 +38,20 @@
{{ $t("project.settings.project-labels.description") }}
</div>
- <LabelListEditor
- ref="labelListEditorRef"
- v-model:kv-list="labelKVList"
- :readonly="!allowEdit"
- :show-errors="true"
- />
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.projects.update'
+ ]"
+ >
+ <LabelListEditor
+ ref="labelListEditorRef"
+ v-model:kv-list="labelKVList"
+ :readonly="slotProps.disabled"
+ :show-errors="true"
+ />
+ </PermissionGuardWrapper>
</div>
</form>
</template>
@@ -45,6 +61,7 @@ import { cloneDeep, isEmpty, isEqual } from "lodash-es";
import { NInput } from "naive-ui";
import { computed, reactive, ref, watch } from "vue";
import { LabelListEditor } from "@/components/Label";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import RequiredStar from "@/components/RequiredStar.vue";
import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";
import { useProjectV1Store } from "@/store";
@@ -62,7 +79,6 @@ interface LocalState {
const props = defineProps<{
project: Project;
- allowEdit: boolean;
}>();
const projectV1Store = useProjectV1Store();
diff --git a/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue b/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue
index 390e6880ee..a18df2eb22 100644
--- a/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue
+++ b/frontend/src/components/Project/Settings/ProjectIssueRelatedSettingPanel.vue
@@ -20,6 +20,32 @@
@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
@@ -312,6 +338,7 @@ import {
interface LocalState {
issueLabels: Label[];
+ allowRequestRole: boolean;
enforceSqlReview: boolean;
forceIssueLabels: boolean;
enforceIssueTitle: boolean;
@@ -330,6 +357,7 @@ const getInitialLocalState = (): LocalState => {
if (!props.project) {
return {
issueLabels: [],
+ allowRequestRole: false,
forceIssueLabels: false,
enforceIssueTitle: false,
enforceSqlReview: false,
@@ -348,6 +376,7 @@ 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,
@@ -487,6 +516,9 @@ const updateMask = computed(() => {
if (!isEqual(state.skipBackupErrors, props.project.skipBackupErrors)) {
mask.push("skip_backup_errors");
}
+ 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.vue
index 7c74324180..aeab3cb736 100644
--- a/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vue
+++ b/frontend/src/components/Project/Settings/ProjectSecuritySettingPanel.vue
@@ -1,19 +1,16 @@
<template>
- <div v-if="allowGet" class="w-full flex flex-col justify-start items-start gap-y-6">
+ <div class="w-full flex flex-col justify-start items-start gap-y-6">
<SQLReviewForResource
ref="sqlReviewForResourceRef"
:resource="project.name"
- :allow-edit="allowEdit"
/>
<AccessControlConfigure
ref="accessControlConfigureRef"
:resource="project.name"
- :allow-edit="allowEdit"
/>
<QueryDataPolicySetting
ref="queryDataPolicySettingRef"
:resource="project.name"
- :allow-edit="allowEdit"
/>
</div>
</template>
@@ -24,9 +21,8 @@ import AccessControlConfigure from "@/components/EnvironmentForm/AccessControlCo
import QueryDataPolicySetting from "@/components/GeneralSetting/QueryDataPolicySetting.vue";
import { SQLReviewForResource } from "@/components/SQLReview";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { hasProjectPermissionV2 } from "@/utils";
-const props = defineProps<{
+defineProps<{
project: Project;
}>();
@@ -44,13 +40,6 @@ const isDirty = computed(
queryDataPolicySettingRef.value?.isDirty
);
-const allowGet = computed(() =>
- hasProjectPermissionV2(props.project, "bb.policies.get")
-);
-const allowEdit = computed(() =>
- hasProjectPermissionV2(props.project, "bb.policies.update")
-);
-
const onUpdate = async () => {
if (sqlReviewForResourceRef.value?.isDirty) {
await sqlReviewForResourceRef.value.update();
diff --git a/frontend/src/components/ProjectSettingPanel.vue b/frontend/src/components/ProjectSettingPanel.vue
index 634014ffcd..6d0c7584f5 100644
--- a/frontend/src/components/ProjectSettingPanel.vue
+++ b/frontend/src/components/ProjectSettingPanel.vue
@@ -12,7 +12,6 @@
<ProjectGeneralSettingPanel
ref="projectGeneralSettingPanelRef"
:project="project"
- :allow-edit="allowEdit"
/>
</div>
</div>
@@ -25,10 +24,15 @@
</h1>
</div>
<div class="flex-1 mt-4 lg:px-4 lg:mt-0">
- <ProjectSecuritySettingPanel
- ref="projectSecuritySettingPanelRef"
+ <ComponentPermissionGuard
:project="project"
- />
+ :permissions="['bb.policies.get']"
+ >
+ <ProjectSecuritySettingPanel
+ ref="projectSecuritySettingPanelRef"
+ :project="project"
+ />
+ </ComponentPermissionGuard>
</div>
</div>
@@ -39,11 +43,19 @@
</h1>
</div>
<div class="flex-1 mt-4 lg:px-4 lg:mt-0">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.projects.update'
+ ]"
+ >
<ProjectIssueRelatedSettingPanel
ref="projectIssueRelatedSettingPanelRef"
:project="project"
- :allow-edit="allowEdit"
+ :allow-edit="!slotProps.disabled"
/>
+ </PermissionGuardWrapper>
</div>
</div>
@@ -72,6 +84,8 @@
import { NButton } from "naive-ui";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";
import { pushNotification } from "@/store";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
diff --git a/frontend/src/components/ProvideDashboardContext.vue b/frontend/src/components/ProvideDashboardContext.vue
index 82f1bf02fe..5b35ace0ca 100644
--- a/frontend/src/components/ProvideDashboardContext.vue
+++ b/frontend/src/components/ProvideDashboardContext.vue
@@ -8,27 +8,18 @@ import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import {
useEnvironmentV1Store,
- usePolicyV1Store,
useSettingV1Store,
useUIStateStore,
} from "@/store";
-import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import MaskSpinner from "./misc/MaskSpinner.vue";
const router = useRouter();
const isInitializing = ref<boolean>(true);
-const policyStore = usePolicyV1Store();
-
onMounted(async () => {
await router.isReady();
- // Prepare workspace policies first.
- await policyStore.fetchPolicies({
- resourceType: PolicyResourceType.WORKSPACE,
- });
-
await Promise.all([
useEnvironmentV1Store().fetchEnvironments(),
useSettingV1Store().getOrFetchSettingByName(
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index d7b78f10d6..a9dcb68aff 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -37,7 +37,6 @@ import {
import {
pushNotification,
useDatabaseV1Store,
- usePolicyV1Store,
useProjectV1Store,
useSQLEditorStore,
useSQLEditorTabStore,
@@ -51,7 +50,6 @@ import {
isValidInstanceName,
isValidProjectName,
} from "@/types";
-import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
import {
emptySQLEditorConnection,
extractInstanceResourceName,
@@ -77,7 +75,6 @@ const databaseStore = useDatabaseV1Store();
const editorStore = useSQLEditorStore();
const worksheetStore = useWorkSheetStore();
const tabStore = useSQLEditorTabStore();
-const policyStore = usePolicyV1Store();
const {
asidePanelTab,
events: editorEvents,
@@ -376,12 +373,7 @@ const restoreLastVisitedSidebarTab = () => {
onMounted(async () => {
editorStore.projectContextReady = false;
- const [_, project] = await Promise.all([
- policyStore.fetchPolicies({
- resourceType: PolicyResourceType.WORKSPACE,
- }),
- initializeProject(),
- ]);
+ const project = await initializeProject();
await migrateLegacyCache();
await tabStore.initProject(project);
diff --git a/frontend/src/components/Quickstart.vue b/frontend/src/components/Quickstart.vue
index 57c8e44601..67966e672e 100644
--- a/frontend/src/components/Quickstart.vue
+++ b/frontend/src/components/Quickstart.vue
@@ -86,7 +86,7 @@ import { CheckCircleIcon, XIcon } from "lucide-vue-next";
import type { Ref } from "vue";
import { computed, unref } from "vue";
import { useI18n } from "vue-i18n";
-import type { RouteLocationRaw } from "vue-router";
+import { type RouteLocationRaw, useRouter } from "vue-router";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
DATABASE_ROUTE_DASHBOARD,
@@ -121,7 +121,7 @@ const SAMPLE_SHEET_ID = "101";
type IntroItem = {
name: string | Ref<string>;
- link?: RouteLocationRaw;
+ link: RouteLocationRaw;
done: Ref<boolean>;
click?: () => void;
hide?: boolean;
@@ -135,6 +135,7 @@ const actuatorStore = useActuatorV1Store();
const issueStore = useIssueV1Store();
const worksheetStore = useWorkSheetStore();
const projectIamPolicyStore = useProjectIamPolicyStore();
+const router = useRouter();
const sampleProject = computedAsync(async () => {
if (!actuatorStore.quickStartEnabled) {
@@ -155,9 +156,6 @@ const sampleIssue = computedAsync(async () => {
if (!sampleProject.value) {
return;
}
- if (!hasProjectPermissionV2(sampleProject.value, "bb.issues.get")) {
- return;
- }
const issue = await issueStore.fetchIssueByName(
`${sampleProject.value.name}/issues/${SAMPLE_ISSUE_ID}`,
{
@@ -174,12 +172,6 @@ const sampleWorksheet = computedAsync(async () => {
if (!sampleProject.value) {
return;
}
- if (!hasProjectPermissionV2(sampleProject.value, "bb.worksheets.get")) {
- return;
- }
- if (!hasProjectPermissionV2(sampleProject.value, "bb.sql.select")) {
- return;
- }
const sheet = await worksheetStore.getOrFetchWorksheetByName(
`${sampleProject.value.name}/sheets/${SAMPLE_SHEET_ID}`,
true /* silent */
@@ -202,6 +194,7 @@ const introList = computed(() => {
},
done: computed(() => uiStateStore.getIntroStateByKey("issue.visit")),
hide: !sampleIssue.value,
+ requiredPermissions: ["bb.issues.get", "bb.projects.get"],
},
{
name: computed(() => t("quick-start.query-data")),
@@ -214,6 +207,11 @@ const introList = computed(() => {
},
done: computed(() => uiStateStore.getIntroStateByKey("data.query")),
hide: !sampleWorksheet.value,
+ requiredPermissions: [
+ "bb.sql.select",
+ "bb.projects.get",
+ "bb.worksheets.get",
+ ],
},
{
name: computed(() => t("quick-start.visit-project")),
@@ -231,7 +229,7 @@ const introList = computed(() => {
done: computed(() =>
uiStateStore.getIntroStateByKey("environment.visit")
),
- requiredPermissions: ["bb.settings.get"],
+ requiredPermissions: ["bb.settings.getEnvironment"],
},
{
name: computed(() => t("quick-start.visit-instance")),
@@ -255,16 +253,26 @@ const introList = computed(() => {
name: WORKSPACE_ROUTE_USERS,
},
done: computed(() => uiStateStore.getIntroStateByKey("member.visit")),
+ requiredPermissions: ["bb.workspaces.getIamPolicy", "bb.users.list"],
},
];
- return introList.filter(
- (item) =>
- !item.hide &&
- (item.requiredPermissions ?? []).every((permission) =>
- hasWorkspacePermissionV2(permission)
- )
- );
+ return introList.filter((item) => {
+ if (item.hide) {
+ return false;
+ }
+ const route = router.resolve(item.link);
+ const permissions = item.requiredPermissions ?? [];
+ if (!!route.params["project"] || !!route.params["projectId"]) {
+ if (!sampleProject.value) {
+ return false;
+ }
+ return permissions.every((permission) =>
+ hasProjectPermissionV2(sampleProject.value!, permission)
+ );
+ }
+ return permissions.every(hasWorkspacePermissionV2);
+ });
});
const showQuickstart = computed(() => {
diff --git a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue b/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue
index f1faa41211..9cd59f1daf 100644
--- a/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue
+++ b/frontend/src/components/Role/Setting/components/RoleDataTable/cells/RoleOperationsCell.vue
@@ -7,7 +7,7 @@
>
<Trash2Icon />
</MiniActionButton>
- <MiniActionButton :disabled="!allowUpdate" @click="$emit('edit', role)">
+ <MiniActionButton @click="$emit('edit', role)">
<PencilIcon />
</MiniActionButton>
</div>
@@ -49,7 +49,6 @@ const { t } = useI18n();
const resourceOccupiedModalRef =
ref<InstanceType<typeof ResourceOccupiedModal>>();
-const allowUpdate = computed(() => hasWorkspacePermissionV2("bb.roles.update"));
const allowDelete = computed(() => hasWorkspacePermissionV2("bb.roles.delete"));
const usersWithRole = computed(() => {
diff --git a/frontend/src/components/Role/Setting/components/RolePanel.vue b/frontend/src/components/Role/Setting/components/RolePanel.vue
index 7ce1723828..9e067525f3 100644
--- a/frontend/src/components/Role/Setting/components/RolePanel.vue
+++ b/frontend/src/components/Role/Setting/components/RolePanel.vue
@@ -21,6 +21,7 @@
:placeholder="$t('role.setting.title-placeholder')"
:status="state.role.title?.length === 0 ? 'error' : undefined"
:maxlength="200"
+ :disabled="!allowUpdate"
/>
</div>
<div class="-mt-2">
@@ -47,6 +48,7 @@
:autosize="{ minRows: 2, maxRows: 4 }"
:placeholder="$t('role.setting.description-placeholder')"
:maxlength="1000"
+ :disabled="!allowUpdate"
/>
</div>
</div>
@@ -59,6 +61,7 @@
</div>
<NButton
size="small"
+ :disabled="!allowUpdate"
@click="state.showImportPermissionFromRoleModal = true"
>
<PlusIcon class="w-4 h-auto mr-1" />
@@ -71,6 +74,7 @@
source-filterable
source-filter-placeholder="Search"
:options="permissionOptions"
+ :disabled="!allowUpdate"
/>
</div>
</div>
@@ -121,7 +125,7 @@ import { PERMISSIONS } from "@/types";
import type { Role } from "@/types/proto-es/v1/role_service_pb";
import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { extractRoleResourceName } from "@/utils";
+import { extractRoleResourceName, hasWorkspacePermissionV2 } from "@/utils";
import { useCustomRoleSettingContext } from "../context";
import ImportPermissionFromRoleModal from "./ImportPermissionFromRoleModal.vue";
@@ -153,6 +157,8 @@ const state = reactive<LocalState>({
showImportPermissionFromRoleModal: false,
});
+const allowUpdate = computed(() => hasWorkspacePermissionV2("bb.roles.update"));
+
const resourceId = computed({
get() {
return extractRoleResourceName(state.role.name);
diff --git a/frontend/src/components/RolloutV1/components/taskPermissions.ts b/frontend/src/components/RolloutV1/components/taskPermissions.ts
index ad8d06659f..f46fcd1183 100644
--- a/frontend/src/components/RolloutV1/components/taskPermissions.ts
+++ b/frontend/src/components/RolloutV1/components/taskPermissions.ts
@@ -65,6 +65,7 @@ export const canRolloutTasks = (tasks: Task[], issue?: Issue): boolean => {
}
// Get rollout policy for the environment
+ // Note: Policies are prefetched by IssueLayout.vue and RolloutLayout.vue
const rolloutPolicy = policyStore.getPolicyByParentAndType({
parentPath: database.effectiveEnvironment,
policyType: PolicyType.ROLLOUT_POLICY,
diff --git a/frontend/src/components/SQLReview/components/SQLReviewForResource.vue b/frontend/src/components/SQLReview/components/SQLReviewForResource.vue
index d911a12f29..50bfc7de71 100644
--- a/frontend/src/components/SQLReview/components/SQLReviewForResource.vue
+++ b/frontend/src/components/SQLReview/components/SQLReviewForResource.vue
@@ -18,18 +18,26 @@
v-if="pendingSelectReviewPolicy"
class="inline-flex items-center gap-x-2"
>
- <Switch
- v-if="allowEditSQLReviewPolicy"
- v-model:value="enforceSQLReviewPolicy"
- :text="true"
- />
- <span
- class="textlabel normal-link text-accent!"
- @click="onSQLReviewPolicyClick"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.reviewConfigs.update',
+ ]"
>
- {{ pendingSelectReviewPolicy.name }}
+ <Switch
+ v-model:value="enforceSQLReviewPolicy"
+ :text="true"
+ :disabled="slotProps.disabled"
+ />
+ </PermissionGuardWrapper>
+ <div
+ class="flex items-center space-x-1"
+ >
+ <span class="textlabel normal-link text-accent!" @click="onSQLReviewPolicyClick">
+ {{ pendingSelectReviewPolicy.name }}
+ </span>
<NButton
- v-if="allowEditSQLReviewTag"
+ v-if="hasUpdatePolicyPermission"
quaternary
size="tiny"
@click.stop="onReviewPolicyRemove"
@@ -38,17 +46,24 @@
<XIcon class="w-4 h-auto" />
</template>
</NButton>
- </span>
+ </div>
</div>
- <NButton
- v-else-if="allowEditSQLReviewTag"
- @click.prevent="showReviewSelectPanel = true"
+ <PermissionGuardWrapper
+ v-else
+ v-slot="slotProps"
+ :project="project"
+ :permissions="[
+ 'bb.policies.update',
+ 'bb.reviewConfigs.list'
+ ]"
>
- {{ $t("sql-review.configure-policy") }}
- </NButton>
- <span v-else class="textinfolabel">
- {{ $t("sql-review.no-policy-set") }}
- </span>
+ <NButton
+ :disabled="slotProps.disabled"
+ @click.prevent="showReviewSelectPanel = true"
+ >
+ {{ $t("sql-review.configure-policy") }}
+ </NButton>
+ </PermissionGuardWrapper>
</div>
</div>
@@ -66,43 +81,71 @@ import { CircleQuestionMarkIcon, XIcon } from "lucide-vue-next";
import { NButton, NTooltip } from "naive-ui";
import { computed, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { Switch } from "@/components/v2";
import { t } from "@/plugins/i18n";
import { WORKSPACE_ROUTE_SQL_REVIEW_DETAIL } from "@/router/dashboard/workspaceRoutes";
-import { useReviewPolicyByResource, useSQLReviewStore } from "@/store";
import {
- environmentNamePrefix,
- projectNamePrefix,
-} from "@/store/modules/v1/common";
+ useProjectV1Store,
+ useReviewPolicyByResource,
+ useSQLReviewStore,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
import type { SQLReviewPolicy } from "@/types";
-import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
+import { isValidProjectName } from "@/types";
+import {
+ hasProjectPermissionV2,
+ hasWorkspacePermissionV2,
+ sqlReviewPolicySlug,
+} from "@/utils";
import SQLReviewPolicySelectPanel from "./SQLReviewPolicySelectPanel.vue";
const props = defineProps<{
resource: string;
- allowEdit: boolean;
}>();
const router = useRouter();
const reviewStore = useSQLReviewStore();
const showReviewSelectPanel = ref<boolean>(false);
const pendingSelectReviewPolicy = ref<SQLReviewPolicy | undefined>(undefined);
+const projectStore = useProjectV1Store();
-const scope = computed(() => {
+const project = computed(() => {
if (props.resource.startsWith(projectNamePrefix)) {
- return t("settings.general.workspace.query-data-policy.environment-scope");
+ const proj = projectStore.getProjectByName(props.resource);
+ if (!isValidProjectName(proj.name)) {
+ return undefined;
+ }
+ return proj;
}
- if (props.resource.startsWith(environmentNamePrefix)) {
- return t("settings.general.workspace.query-data-policy.project-scope");
+ return undefined;
+});
+
+const hasGetPolicyPermission = computed(() => {
+ if (project.value) {
+ return hasProjectPermissionV2(project.value, "bb.policies.get");
}
- return "";
+ return hasWorkspacePermissionV2("bb.policies.get");
+});
+
+const hasUpdatePolicyPermission = computed(() => {
+ if (project.value) {
+ return hasProjectPermissionV2(project.value, "bb.policies.update");
+ }
+ return hasWorkspacePermissionV2("bb.policies.update");
});
const tooltip = computed(() => {
- if (!scope.value) {
- return "";
+ if (project.value) {
+ return t("sql-review.tooltip-for-resource", {
+ scope: t(
+ "settings.general.workspace.query-data-policy.environment-scope"
+ ),
+ });
}
- return t("sql-review.tooltip-for-resource", { scope: scope.value });
+ return t("sql-review.tooltip-for-resource", {
+ scope: t("settings.general.workspace.query-data-policy.project-scope"),
+ });
});
const sqlReviewPolicy = useReviewPolicyByResource(
@@ -118,15 +161,10 @@ const resetState = () => {
watchEffect(resetState);
const allowGetSQLReviewPolicy = computed(() => {
- return props.allowEdit && hasWorkspacePermissionV2("bb.reviewConfigs.get");
-});
-
-const allowEditSQLReviewPolicy = computed(() => {
- return props.allowEdit && hasWorkspacePermissionV2("bb.reviewConfigs.update");
-});
-
-const allowEditSQLReviewTag = computed(() => {
- return props.allowEdit && hasWorkspacePermissionV2("bb.policies.update");
+ return (
+ hasWorkspacePermissionV2("bb.reviewConfigs.get") &&
+ hasGetPolicyPermission.value
+ );
});
const onReviewPolicySelect = (review: SQLReviewPolicy) => {
diff --git a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
index b792029cfa..17a401d824 100644
--- a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
+++ b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
@@ -24,7 +24,7 @@
<PermissionGuardWrapper
v-else
v-slot="slotProps"
- :permissions="['bb.policies.update']"
+ :permissions="['bb.policies.updateMaskingRulePolicy']"
>
<div class="flex items-center gap-x-2">
<NButton
@@ -196,8 +196,9 @@ const state = reactive<LocalState>({
const policyStore = usePolicyV1Store();
const hasPermission = computed(() => {
- return hasWorkspacePermissionV2("bb.policies.update");
+ return hasWorkspacePermissionV2("bb.policies.updateMaskingRulePolicy");
});
+
const hasSensitiveDataFeature = featureToRef(PlanFeature.FEATURE_DATA_MASKING);
const layout = {
mainContainerRef: ref<HTMLDivElement>(),
diff --git a/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue b/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
index f866f9cdc5..646f9cef56 100644
--- a/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
+++ b/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
@@ -46,7 +46,7 @@ import {
PolicyType,
} from "@/types/proto-es/v1/org_policy_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { autoDatabaseRoute, hasProjectPermissionV2 } from "@/utils";
+import { autoDatabaseRoute } from "@/utils";
import {
batchConvertFromCELString,
type ConditionExpression,
@@ -79,10 +79,6 @@ const databaseStore = useDatabaseV1Store();
const policyStore = usePolicyV1Store();
const $dialog = useDialog();
-const hasPermission = computed(() => {
- return hasProjectPermissionV2(props.project, "bb.policies.update");
-});
-
const { policy, ready } = usePolicyByParentAndType(
computed(() => ({
parentPath: props.project.name,
@@ -303,7 +299,7 @@ const accessTableColumns = computed(
actions={["confirm"]}
isDateDisabled={(date: number) => date < Date.now()}
clearable={true}
- disabled={!hasPermission.value || props.disabled}
+ disabled={props.disabled}
onUpdate:value={(val: number | undefined) =>
onAccessControlUpdate(
item,
@@ -324,7 +320,7 @@ const accessTableColumns = computed(
{
key: "operation",
title: "",
- hide: !hasPermission.value,
+ hide: props.disabled,
width: "4rem",
render: (item: AccessUser) => {
return h(
diff --git a/frontend/src/components/v2/Button/TooltipButton.vue b/frontend/src/components/v2/Button/TooltipButton.vue
index d6b503475d..4779cb6f19 100644
--- a/frontend/src/components/v2/Button/TooltipButton.vue
+++ b/frontend/src/components/v2/Button/TooltipButton.vue
@@ -46,10 +46,10 @@ defineEmits<{
const slots = useSlots();
const tooltipEnabled = computed(() => {
- // Enable tooltip when tooltipMode is "ALWAYS"
- if (props.tooltipMode === "ALWAYS") return true;
// Disable tooltip if no tooltip contents
if (!slots.tooltip) return false;
+ // Enable tooltip when tooltipMode is "ALWAYS"
+ if (props.tooltipMode === "ALWAYS") return true;
// Enable tooltip if button is disabled
// Disable tooltip otherwise
return props.disabled;
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 6072462fa5..31c49cb212 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -36,7 +36,7 @@ import {
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
getValidDataSourceByPolicy,
- hasPermissionToCreateChangeDatabaseIssue,
+ hasPermissionToCreateChangeDatabaseIssueInProject,
} from "@/utils";
import { flattenNoSQLResult } from "./utils";
@@ -219,16 +219,17 @@ const useExecuteSQL = () => {
}
const database = dbStore.getDatabaseByName(databaseName);
+ const dataSourceId = await getDataSourceId(
+ database,
+ params.connection,
+ isBatch ? tab.batchQueryContext.dataSourceType : undefined
+ );
const context: SQLEditorDatabaseQueryContext = {
id: uuidv4(),
params: Object.assign(cloneDeep(params), {
connection: {
...params.connection,
- dataSourceId: getDataSourceId(
- database,
- params.connection,
- isBatch ? tab.batchQueryContext.dataSourceType : undefined
- ),
+ dataSourceId,
},
}),
status: "PENDING",
@@ -331,7 +332,11 @@ const useExecuteSQL = () => {
if (isOnlySelectError(resultSet)) {
// Show a tips to navigate to issue creation
// if the user is allowed to create issue in the project.
- if (hasPermissionToCreateChangeDatabaseIssue(database)) {
+ if (
+ hasPermissionToCreateChangeDatabaseIssueInProject(
+ database.projectEntity
+ )
+ ) {
sqlEditorStore.isShowExecutingHint = true;
sqlEditorStore.executingHintDatabase = database;
}
diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
index 78a485438a..efe86326c4 100644
--- a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
@@ -78,7 +78,10 @@ export const authInterceptor: Interceptor = (next) => async (req) => {
// Throw retry error (not original) - let other handlers deal with it
throw retryError;
}
- } else if (code === Code.PermissionDenied) {
+ } else if (
+ code === Code.PermissionDenied &&
+ router.currentRoute.value.name !== WORKSPACE_ROUTE_403
+ ) {
const errorDetail = extractPermissionDeniedDetail(error);
router.push({
name: WORKSPACE_ROUTE_403,
diff --git a/frontend/src/layouts/SQLEditorLayout.vue b/frontend/src/layouts/SQLEditorLayout.vue
index 0c900e4d21..1768a9a323 100644
--- a/frontend/src/layouts/SQLEditorLayout.vue
+++ b/frontend/src/layouts/SQLEditorLayout.vue
@@ -21,12 +21,7 @@ import BannersWrapper from "@/components/BannersWrapper.vue";
import RoutePermissionGuard from "@/components/Permission/RoutePermissionGuard.vue";
import ProvideSQLEditorContext from "@/components/ProvideSQLEditorContext.vue";
import sqlEditorRoutes from "@/router/sqlEditor";
-import {
- useEnvironmentV1Store,
- usePolicyV1Store,
- useSettingV1Store,
-} from "@/store";
-import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
+import { useEnvironmentV1Store, useSettingV1Store } from "@/store";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { provideSQLEditorContext } from "@/views/sql-editor/context";
import { provideSheetContext } from "@/views/sql-editor/Sheet";
@@ -48,19 +43,6 @@ const ready = ref(false);
const prepare = async () => {
await router.isReady();
- const policyV1Store = usePolicyV1Store();
- // Prepare roles, workspace policies and settings.
- await Promise.all([
- policyV1Store.fetchPolicies({
- resourceType: PolicyResourceType.WORKSPACE,
- }),
- policyV1Store.fetchPolicies({
- resourceType: PolicyResourceType.ENVIRONMENT,
- }),
- policyV1Store.fetchPolicies({
- resourceType: PolicyResourceType.PROJECT,
- }),
- ]);
await Promise.all([
useSettingV1Store().getOrFetchSettingByName(
Setting_SettingName.WORKSPACE_PROFILE
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 4544a24e69..b48d90a06d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -653,7 +653,6 @@
"id": "Workspace ID",
"id-description": "The unique, read-only workspace id.",
"branding": "Branding",
- "only-admin-can-edit": "Only workspace admin can update the settings.",
"logo": "Logo",
"logo-aspect": "The suggested logo size should be 5:2 aspect ratio, e.g 100 x 40.",
"select-logo": "Upload a file",
@@ -798,8 +797,7 @@
}
},
"announcement": {
- "self": "Announcement",
- "admin-or-dba-can-edit": "Only workspace admin or DBA can update announcement setting."
+ "self": "Announcement"
},
"announcement-alert-level": {
"description": "Level"
@@ -1942,6 +1940,10 @@
"require-plan-check-no-error": {
"self": "Require plan checks to pass before rollout",
"description": "All plan checks must pass without errors before creating rollout."
+ },
+ "allow-request-role": {
+ "self": "Allow request role",
+ "description": "Non-project-owner users can request project-level roles themselves"
}
},
"project-labels": {
@@ -2398,7 +2400,6 @@
"title": "SQL Review",
"description": "SQL review policy can define different set of SQL lint rules for the respective environments. It helps teams to adopt SQL best practice and enforce schema consistency across different databases. Whenever you attempt a DDL/DML change or use SQL Editor to query data, the query will be checked against the configured SQL review policy.",
"disabled": "SQL review is disabled",
- "no-policy-set": "No SQL review policy",
"create-policy": "Create SQL review",
"select-review": "Select SQL review",
"select-review-rules": "Select SQL review rules",
@@ -2774,7 +2775,7 @@
},
"project-viewer": {
"self": "Project Viewer",
- "description": "Read-only permissions for viewing basic project information, accessing databases, and initiating privilege requests."
+ "description": "Read-only permissions for viewing basic project and database information; users may self-initiate tickets to request data queries and exports."
}
},
"database-group": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 359aaa9020..7c32cac490 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -653,7 +653,6 @@
"id": "ID del espacio de trabajo",
"id-description": "La identificación única del espacio de trabajo de solo lectura.",
"branding": "Marca",
- "only-admin-can-edit": "Solo el administrador del espacio de trabajo puede actualizar la configuración.",
"logo": "Logo",
"logo-aspect": "El tamaño sugerido para el logo debería tener una proporción de 5:2, por ejemplo, 100 x 40.",
"select-logo": "Subir un archivo",
@@ -798,8 +797,7 @@
}
},
"announcement": {
- "self": "Anuncio",
- "admin-or-dba-can-edit": "Solo el administrador del espacio de trabajo o el DBA pueden actualizar la configuración de anuncios."
+ "self": "Anuncio"
},
"announcement-alert-level": {
"description": "Level"
@@ -1942,6 +1940,10 @@
"require-plan-check-no-error": {
"self": "Requiere que las verificaciones del plan pasen antes del despliegue",
"description": "Todas las verificaciones del plan deben pasar sin errores antes de crear un despliegue."
+ },
+ "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"
}
},
"project-labels": {
@@ -2398,7 +2400,6 @@
"title": "Revisión de SQL",
"description": "La política de revisión de SQL puede definir diferentes conjuntos de reglas de lint SQL para los entornos respectivos. Ayuda a los equipos a adoptar las mejores prácticas de SQL y a hacer cumplir la consistencia del esquema en diferentes bases de datos. Cada vez que intente realizar un cambio DDL/DML o use el Editor SQL para consultar datos, la consulta se verificará en función de la política de revisión de SQL configurada.",
"disabled": "La revisión de SQL está deshabilitada",
- "no-policy-set": "Sin política de revisión de SQL",
"create-policy": "Crear política",
"select-review": "Seleccione revisión SQL",
"select-review-rules": "Seleccionar reglas de revisión de SQL",
@@ -2774,7 +2775,7 @@
},
"project-viewer": {
"self": "Espectador del proyecto",
- "description": "El espectador del proyecto tiene todos los permisos dentro del proyecto, excepto la gestión de miembros del proyecto."
+ "description": "Permisos de solo lectura para ver información básica del proyecto y la base de datos; los usuarios pueden iniciar tickets por su cuenta para solicitar consultas y exportaciones de datos."
}
},
"database-group": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a22071cd0f..637273c6cb 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -653,7 +653,6 @@
"id": "ワークスペースID",
"id-description": "一意の読み取り専用ワークスペース ID",
"branding": "ブランド",
- "only-admin-can-edit": "この設定を変更できるのは管理者だけです",
"logo": "ロゴ",
"logo-aspect": "推奨されるロゴの幅:高さの比率 (例: 100 x 40 ピクセル)",
"select-logo": "選ぶ",
@@ -798,8 +797,7 @@
}
},
"announcement": {
- "self": "お知らせ",
- "admin-or-dba-can-edit": "管理者または DBA のみがお知らせの設定を更新できます。"
+ "self": "お知らせ"
},
"announcement-alert-level": {
"description": "レベル"
@@ -1942,6 +1940,10 @@
"require-plan-check-no-error": {
"self": "ロールアウト前にプランチェック合格が必要",
"description": "ロールアウトを作成する前にすべてのプランチェックがエラーなしで合格する必要があります。"
+ },
+ "allow-request-role": {
+ "self": "ロールリクエストを許可",
+ "description": "プロジェクト所有者以外のユーザーがプロジェクトレベルのロールを自分でリクエストできます"
}
},
"project-labels": {
@@ -2398,7 +2400,6 @@
"title": "SQL監査ポリシー",
"description": "SQL 監査ポリシーは、さまざまな環境に対してさまざまな SQL lint ルールのセットを定義でき、チームが SQL のベスト プラクティスを採用し、さまざまなデータベースでスキーマの一貫性を制約するのに役立ちます。 DDL/DML を変更しようとしたり、SQL エディターを使用してデータをクエリしようとしたりすると、設定された SQL 監査ルールによって対応する実行ステートメントがチェックされます。",
"disabled": "SQL監査ポリシーが無効になっています",
- "no-policy-set": "SQL監査ポリシーなし",
"create-policy": "監査ポリシーを作成する",
"select-review": "SQLレビューを選択",
"select-review-rules": "SQLレビュールールを選択",
@@ -2774,7 +2775,7 @@
},
"project-viewer": {
"self": "プロジェクトビューア",
- "description": "基本的なプロジェクト情報を表示し、独自にデータ クエリとデータ エクスポート リクエストを開始できます。"
+ "description": "プロジェクトとデータベースの基本情報を閲覧するための読み取り専用権限。ユーザーはデータクエリやエクスポートをリクエストするチケットを自分で発行できます。"
}
},
"database-group": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index f526576244..767b4cb36e 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -653,7 +653,6 @@
"id": "ID không gian làm việc",
"id-description": "ID không gian làm việc duy nhất, chỉ đọc.",
"branding": "Thương hiệu",
- "only-admin-can-edit": "Chỉ quản trị viên không gian làm việc mới có thể cập nhật cài đặt.",
"logo": "Logo",
"logo-aspect": "Kích thước logo được đề xuất nên theo tỷ lệ 5:2, ví dụ 100 x 40.",
"select-logo": "Tải lên một tệp",
@@ -798,8 +797,7 @@
}
},
"announcement": {
- "self": "Thông báo",
- "admin-or-dba-can-edit": "Chỉ quản trị viên không gian làm việc hoặc DBA mới có thể cập nhật cài đặt thông báo."
+ "self": "Thông báo"
},
"announcement-alert-level": {
"description": "Cấp độ"
@@ -1942,6 +1940,10 @@
"require-plan-check-no-error": {
"self": "Yêu cầu kiểm tra kế hoạch phải đạt trước khi triển khai",
"description": "Tất cả kiểm tra kế hoạch phải đạt không có lỗi trước khi tạo triển khai."
+ },
+ "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"
}
},
"project-labels": {
@@ -2398,7 +2400,6 @@
"title": "Đánh giá SQL",
"description": "Chính sách đánh giá SQL có thể xác định các bộ quy tắc lint SQL khác nhau cho các môi trường tương ứng. Nó giúp các nhóm áp dụng thực tiễn tốt nhất về SQL và thực thi tính nhất quán của lược đồ trên các cơ sở dữ liệu khác nhau. Bất cứ khi nào bạn cố gắng thay đổi DDL/DML hoặc sử dụng Trình soạn thảo SQL để truy vấn dữ liệu, truy vấn sẽ được kiểm tra theo chính sách đánh giá SQL đã định cấu hình.",
"disabled": "Đánh giá SQL bị vô hiệu hóa",
- "no-policy-set": "Không có chính sách đánh giá SQL",
"create-policy": "Tạo chính sách đánh giá SQL",
"select-review": "Chọn đánh giá SQL",
"select-review-rules": "Chọn quy tắc đánh giá SQL",
@@ -2774,7 +2775,7 @@
},
"project-viewer": {
"self": "Người xem dự án",
- "description": "Quyền chỉ đọc để xem thông tin cơ bản của dự án, truy cập cơ sở dữ liệu và bắt đầu các yêu cầu đặc quyền."
+ "description": "Quyền chỉ đọc để xem thông tin cơ bản của dự án và cơ sở dữ liệu; người dùng có thể tự tạo yêu cầu để truy vấn và xuất dữ liệu."
}
},
"database-group": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 49e65aa1ef..2b948b0819 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -653,7 +653,6 @@
"id": "工作空间 ID",
"id-description": "唯一且只读的工作空间 ID",
"branding": "品牌",
- "only-admin-can-edit": "仅管理员可以更改此设置",
"logo": "Logo",
"logo-aspect": "Logo 建议为 5:2 的宽:高比例(例如 100 x 40 像素)",
"select-logo": "选择",
@@ -798,8 +797,7 @@
}
},
"announcement": {
- "self": "公告",
- "admin-or-dba-can-edit": "只有管理员或 DBA 可以更新公告设置。"
+ "self": "公告"
},
"announcement-alert-level": {
"description": "等级"
@@ -1942,6 +1940,10 @@
"require-plan-check-no-error": {
"self": "发布前要求变更检查通过",
"description": "所有变更检查必须无错误才能创建发布。"
+ },
+ "allow-request-role": {
+ "self": "允许申请角色",
+ "description": "非项目所有者可以自行申请项目级角色"
}
},
"project-labels": {
@@ -2398,7 +2400,6 @@
"title": "SQL 审核策略",
"description": "SQL 审核策略可以为不同的环境定义不同的 SQL lint 规则集. 它可以帮助团队采用 SQL 最佳使用实践,并在不同的数据库上约束 schema 的一致性。每当您尝试做一个 DDL/DML 变更或者使用 SQL 编辑器来查询数据时, 配置的 SQL 审核规则就会检查相应的执行语句。",
"disabled": "SQL 审核策略已禁用",
- "no-policy-set": "没有 SQL 审核策略",
"create-policy": "创建审核策略",
"select-review": "选择 SQL 审核",
"select-review-rules": "选择 SQL 审核规则",
@@ -2774,7 +2775,7 @@
},
"project-viewer": {
"self": "项目查看者",
- "description": "可查看项目基本信息,并可自助发起数据查询、数据导出请求。"
+ "description": "仅可查看项目和数据库的基本信息,用户可自助发起工单请求数据查询和导出。"
}
},
"database-group": {
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
index e511fb3cde..d5fc27be95 100644
--- a/frontend/src/router/dashboard/projectV1.ts
+++ b/frontend/src/router/dashboard/projectV1.ts
@@ -92,6 +92,7 @@ const rolloutRoutes: RouteRecordRaw[] = [
props: true,
meta: {
title: () => t("common.rollout"),
+ requiredPermissionList: () => ["bb.rollouts.get", "bb.taskRuns.list"],
},
children: [
{
@@ -100,9 +101,6 @@ const rolloutRoutes: RouteRecordRaw[] = [
component: () =>
import("@/components/RolloutV1/components/RolloutView.vue"),
props: true,
- meta: {
- requiredPermissionList: () => ["bb.rollouts.get", "bb.taskRuns.list"],
- },
},
{
path: "stages/:stageId",
@@ -110,9 +108,6 @@ const rolloutRoutes: RouteRecordRaw[] = [
component: () =>
import("@/components/RolloutV1/components/RolloutView.vue"),
props: true,
- meta: {
- requiredPermissionList: () => ["bb.rollouts.get", "bb.taskRuns.list"],
- },
},
{
path: "stages/:stageId/tasks/:taskId",
@@ -120,9 +115,6 @@ const rolloutRoutes: RouteRecordRaw[] = [
component: () =>
import("@/components/RolloutV1/components/TaskView.vue"),
props: true,
- meta: {
- requiredPermissionList: () => ["bb.rollouts.get", "bb.taskRuns.list"],
- },
},
],
},
@@ -161,7 +153,6 @@ const projectV1Routes: RouteRecordRaw[] = [
path: "masking-exemption",
meta: {
title: () => t("project.masking-exemption.self"),
- requiredPermissionList: () => ["bb.databases.get", "bb.policies.get"],
},
props: true,
children: [
@@ -171,6 +162,12 @@ const projectV1Routes: RouteRecordRaw[] = [
component: () =>
import("@/views/project/ProjectMaskingExemption.vue"),
props: true,
+ meta: {
+ requiredPermissionList: () => [
+ "bb.databases.get",
+ "bb.policies.getMaskingExemptionPolicy",
+ ],
+ },
},
{
path: "create",
@@ -180,8 +177,10 @@ const projectV1Routes: RouteRecordRaw[] = [
props: true,
meta: {
requiredPermissionList: () => [
- "bb.policies.create",
+ "bb.policies.createMaskingExemptionPolicy",
+ "bb.policies.updateMaskingExemptionPolicy",
"bb.databases.list",
+ "bb.databaseCatalogs.get",
],
},
},
@@ -354,7 +353,6 @@ const projectV1Routes: RouteRecordRaw[] = [
name: PROJECT_V1_ROUTE_SETTINGS,
meta: {
title: () => t("common.settings"),
- requiredPermissionList: () => ["bb.policies.get"],
},
component: () => import("@/views/project/ProjectSettingPanel.vue"),
props: true,
diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.ts
index 17184a205f..5042f49503 100644
--- a/frontend/src/router/dashboard/workspace.ts
+++ b/frontend/src/router/dashboard/workspace.ts
@@ -90,10 +90,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
meta: {
title: () => t("common.environments"),
- requiredPermissionList: () => [
- "bb.settings.getEnvironment",
- "bb.policies.get",
- ],
+ requiredPermissionList: () => ["bb.settings.getEnvironment"],
},
components: {
content: () => import("@/views/EnvironmentDashboard.vue"),
@@ -138,7 +135,6 @@ const workspaceRoutes: RouteRecordRaw[] = [
path: "sql-review",
meta: {
title: () => t("sql-review.title"),
- requiredPermissionList: () => ["bb.policies.get"],
},
components: {
content: () => import("@/layouts/SettingLayout.vue"),
@@ -154,7 +150,10 @@ const workspaceRoutes: RouteRecordRaw[] = [
name: WORKSPACE_ROUTE_SQL_REVIEW,
meta: {
title: () => t("sql-review.title"),
- requiredPermissionList: () => ["bb.reviewConfigs.list"],
+ requiredPermissionList: () => [
+ "bb.reviewConfigs.list",
+ "bb.policies.get",
+ ],
},
component: () => import("@/views/SettingWorkspaceSQLReview.vue"),
props: true,
@@ -174,7 +173,10 @@ const workspaceRoutes: RouteRecordRaw[] = [
name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
meta: {
title: () => t("sql-review.title"),
- requiredPermissionList: () => ["bb.reviewConfigs.get"],
+ requiredPermissionList: () => [
+ "bb.reviewConfigs.get",
+ "bb.policies.get",
+ ],
},
component: () => import("@/views/SettingWorkspaceSQLReviewDetail.vue"),
props: true,
@@ -241,7 +243,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
name: WORKSPACE_ROUTE_GLOBAL_MASKING,
meta: {
title: () => t("settings.sidebar.global-masking"),
- requiredPermissionList: () => ["bb.policies.get"],
+ requiredPermissionList: () => ["bb.policies.getMaskingRulePolicy"],
},
component: () => import("@/views/SettingWorkspaceDataMasking.vue"),
props: true,
diff --git a/frontend/src/router/dashboard/workspaceSetting.ts b/frontend/src/router/dashboard/workspaceSetting.ts
index bcf7f3b02a..68711bf62e 100644
--- a/frontend/src/router/dashboard/workspaceSetting.ts
+++ b/frontend/src/router/dashboard/workspaceSetting.ts
@@ -42,11 +42,7 @@ const workspaceSettingRoutes: RouteRecordRaw[] = [
name: SETTING_ROUTE_WORKSPACE_GENERAL,
meta: {
title: () => t("settings.sidebar.general"),
- requiredPermissionList: () => [
- "bb.settings.get",
- "bb.settings.getWorkspaceProfile",
- "bb.policies.get",
- ],
+ requiredPermissionList: () => ["bb.settings.getWorkspaceProfile"],
},
component: () => import("@/views/SettingWorkspaceGeneral.vue"),
props: true,
diff --git a/frontend/src/store/modules/sqlReview.ts b/frontend/src/store/modules/sqlReview.ts
index 87b15e5646..489a86a27a 100644
--- a/frontend/src/store/modules/sqlReview.ts
+++ b/frontend/src/store/modules/sqlReview.ts
@@ -24,10 +24,19 @@ import {
ReviewConfigSchema,
UpdateReviewConfigRequestSchema,
} from "@/types/proto-es/v1/review_config_service_pb";
-import { usePolicyV1Store } from "./v1/policy";
+import {
+ replacePolicyTypeNameToLowerCase,
+ usePolicyV1Store,
+} from "./v1/policy";
const reviewConfigTagName = "bb.tag.review_config";
+const getTagPolicyName = (resourcePath: string): string => {
+ return replacePolicyTypeNameToLowerCase(
+ `${resourcePath}/${policyNamePrefix}${PolicyType[PolicyType.TAG]}`
+ );
+};
+
const upsertReviewConfigTag = async (
resources: string[],
configName: string
@@ -79,10 +88,6 @@ interface SQLReviewState {
reviewPolicyList: SQLReviewPolicy[];
}
-const getTagPolicyName = (resourcePath: string): string => {
- return `${resourcePath}/${policyNamePrefix}tag`;
-};
-
export const useSQLReviewStore = defineStore("sqlReview", {
state: (): SQLReviewState => ({
reviewPolicyList: [],
diff --git a/frontend/src/store/modules/v1/policy.ts b/frontend/src/store/modules/v1/policy.ts
index 9d0c6b9414..abd3fddb1d 100644
--- a/frontend/src/store/modules/v1/policy.ts
+++ b/frontend/src/store/modules/v1/policy.ts
@@ -6,16 +6,18 @@ import { computed, reactive, ref, unref, watchEffect } from "vue";
import { orgPolicyServiceClientConnect } from "@/connect";
import { silentContextKey } from "@/connect/context-key";
import { policyNamePrefix } from "@/store/modules/v1/common";
-import type { MaybeRef } from "@/types";
+import type { ComposedDatabase, MaybeRef } from "@/types";
import { UNKNOWN_USER_NAME } from "@/types";
import type {
+ DataSourceQueryPolicy,
Policy,
QueryDataPolicy,
} from "@/types/proto-es/v1/org_policy_service_pb";
import {
+ DataSourceQueryPolicy_Restriction,
+ DataSourceQueryPolicySchema,
DeletePolicyRequestSchema,
GetPolicyRequestSchema,
- ListPoliciesRequestSchema,
PolicyResourceType,
PolicySchema,
PolicyType,
@@ -31,7 +33,7 @@ interface PolicyState {
export const DEFAULT_MAX_RESULT_SIZE_IN_MB = 100;
-const replacePolicyTypeNameToLowerCase = (name: string) => {
+export const replacePolicyTypeNameToLowerCase = (name: string) => {
const pattern = /(^|\/)policies\/([^/]+)($|\/)/;
const replaced = name.replace(
pattern,
@@ -45,25 +47,23 @@ const replacePolicyTypeNameToLowerCase = (name: string) => {
return replaced;
};
-const getPolicyParentByResourceType = (
- resourceType: PolicyResourceType
-): string => {
- switch (resourceType) {
- case PolicyResourceType.PROJECT:
- return "projects/-";
- case PolicyResourceType.ENVIRONMENT:
- return "environments/-";
- default:
- return "";
- }
-};
-
export const usePolicyV1Store = defineStore("policy_v1", () => {
const state = reactive<PolicyState>({
policyMapByName: new Map(),
});
- const policyList = computed(() => Array.from(state.policyMapByName.values()));
+ const getDataSourceQueryPolicyByParent = (
+ parent: string
+ ): DataSourceQueryPolicy => {
+ const policy = getPolicyByParentAndType({
+ parentPath: parent,
+ policyType: PolicyType.DATA_SOURCE_QUERY,
+ });
+
+ return policy?.policy?.case === "dataSourceQueryPolicy"
+ ? policy.policy.value
+ : create(DataSourceQueryPolicySchema, {});
+ };
const getQueryDataPolicyByParent = (parent: string): QueryDataPolicy => {
const policy = getPolicyByParentAndType({
@@ -83,104 +83,6 @@ export const usePolicyV1Store = defineStore("policy_v1", () => {
});
};
- const formatQueryDataPolicy = (policy: QueryDataPolicy) => {
- let maximumResultSize = Number(policy.maximumResultSize);
- let maximumResultRows = policy.maximumResultRows;
- let queryTimeoutInSeconds = Number(policy.timeout?.seconds ?? 0);
-
- if (maximumResultSize <= 0) {
- maximumResultSize = DEFAULT_MAX_RESULT_SIZE_IN_MB * 1024 * 1024;
- }
- if (maximumResultRows <= 0) {
- maximumResultRows = Number.MAX_VALUE;
- }
- if (queryTimeoutInSeconds <= 0) {
- queryTimeoutInSeconds = Number.MAX_VALUE;
- }
-
- return {
- disableCopyData: policy.disableCopyData,
- disableExport: policy.disableExport,
- maximumResultSize,
- maximumResultRows,
- queryTimeoutInSeconds,
- };
- };
-
- const getEffectiveQueryDataPolicyForProject = (project: string) => {
- const workspacePolicy = formatQueryDataPolicy(
- getQueryDataPolicyByParent("")
- );
- const projectPolicy = formatQueryDataPolicy(
- getQueryDataPolicyByParent(project)
- );
-
- return {
- disableCopyData:
- projectPolicy.disableCopyData || workspacePolicy.disableCopyData,
- disableExport:
- projectPolicy.disableExport || workspacePolicy.disableExport,
- maximumResultRows: Math.min(
- projectPolicy.maximumResultRows,
- workspacePolicy.maximumResultRows
- ),
- maximumResultSize: Math.min(
- projectPolicy.maximumResultSize,
- workspacePolicy.maximumResultSize
- ),
- queryTimeoutInSeconds: Math.min(
- projectPolicy.queryTimeoutInSeconds,
- workspacePolicy.queryTimeoutInSeconds
- ),
- };
- };
-
- const fetchPolicies = async ({
- resourceType,
- policyType,
- parent,
- showDeleted = false,
- }: {
- resourceType: PolicyResourceType;
- policyType?: PolicyType;
- parent?: string;
- showDeleted?: boolean;
- }) => {
- const request = create(ListPoliciesRequestSchema, {
- parent: parent ?? getPolicyParentByResourceType(resourceType),
- policyType: policyType,
- showDeleted,
- });
- const response = await orgPolicyServiceClientConnect.listPolicies(request);
- const policies = response.policies;
- for (const policy of policies) {
- state.policyMapByName.set(policy.name, policy);
- }
- return policies;
- };
-
- const getPolicies = ({
- resourceType,
- policyType,
- showDeleted,
- }: {
- resourceType: PolicyResourceType;
- policyType: PolicyType;
- showDeleted?: boolean;
- }) => {
- const response: Policy[] = [];
- for (const [_, policy] of state.policyMapByName) {
- if (policy.resourceType != resourceType || policy.type != policyType) {
- continue;
- }
- if (!showDeleted && !policy.enforce) {
- continue;
- }
- response.push(policy);
- }
- return response;
- };
-
const getOrFetchPolicyByParentAndType = async ({
parentPath,
policyType,
@@ -276,20 +178,40 @@ export const usePolicyV1Store = defineStore("policy_v1", () => {
};
return {
- policyList,
- fetchPolicies,
- getPolicies,
getOrFetchPolicyByParentAndType,
getOrFetchPolicyByName,
getPolicyByParentAndType,
- getPolicyByName,
upsertPolicy,
deletePolicy,
getQueryDataPolicyByParent,
- getEffectiveQueryDataPolicyForProject,
+ getDataSourceQueryPolicyByParent,
};
});
+const formatQueryDataPolicy = (policy: QueryDataPolicy) => {
+ let maximumResultSize = Number(policy.maximumResultSize);
+ let maximumResultRows = policy.maximumResultRows;
+ let queryTimeoutInSeconds = Number(policy.timeout?.seconds ?? 0);
+
+ if (maximumResultSize <= 0) {
+ maximumResultSize = DEFAULT_MAX_RESULT_SIZE_IN_MB * 1024 * 1024;
+ }
+ if (maximumResultRows <= 0) {
+ maximumResultRows = Number.MAX_VALUE;
+ }
+ if (queryTimeoutInSeconds <= 0) {
+ queryTimeoutInSeconds = Number.MAX_VALUE;
+ }
+
+ return {
+ disableCopyData: policy.disableCopyData,
+ disableExport: policy.disableExport,
+ maximumResultSize,
+ maximumResultRows,
+ queryTimeoutInSeconds,
+ };
+};
+
const getUpdateMaskFromPolicyType = (policyType: PolicyType) => {
switch (policyType) {
case PolicyType.ROLLOUT_POLICY:
@@ -311,28 +233,6 @@ const getUpdateMaskFromPolicyType = (policyType: PolicyType) => {
}
};
-export const usePolicyListByResourceTypeAndPolicyType = (
- params: MaybeRef<{
- resourceType: PolicyResourceType;
- policyType: PolicyType;
- showDeleted: false;
- }>
-) => {
- const store = usePolicyV1Store();
- const currentUserV1 = useCurrentUserV1();
- watchEffect(() => {
- if (currentUserV1.value.name === UNKNOWN_USER_NAME) return;
- const { resourceType, policyType, showDeleted } = unref(params);
-
- store.fetchPolicies({ resourceType, policyType, showDeleted });
- });
-
- return computed(() => {
- const { resourceType, policyType, showDeleted } = unref(params);
- return store.getPolicies({ resourceType, policyType, showDeleted });
- });
-};
-
export const usePolicyByParentAndType = (
params: MaybeRef<{
parentPath: string;
@@ -367,6 +267,111 @@ export const usePolicyByParentAndType = (
};
};
+export const useDataSourceRestrictionPolicy = (
+ database: MaybeRef<ComposedDatabase>
+) => {
+ const store = usePolicyV1Store();
+ const ready = ref(false);
+
+ watchEffect(async () => {
+ await store.getOrFetchPolicyByParentAndType({
+ parentPath: unref(database).project,
+ policyType: PolicyType.DATA_SOURCE_QUERY,
+ });
+
+ const environment = unref(database).effectiveEnvironment;
+ if (environment) {
+ await store.getOrFetchPolicyByParentAndType({
+ parentPath: environment,
+ policyType: PolicyType.DATA_SOURCE_QUERY,
+ });
+ }
+ ready.value = true;
+ });
+
+ const dataSourceRestriction = computed(() => {
+ const projectLevelPolicy = store.getDataSourceQueryPolicyByParent(
+ unref(database).project
+ );
+ const projectLevelAdminDSRestriction =
+ projectLevelPolicy.adminDataSourceRestriction;
+
+ let envLevelAdminDSRestriction =
+ DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED;
+ const environment = unref(database).effectiveEnvironment;
+ if (environment) {
+ const envLevelPolicy =
+ store.getDataSourceQueryPolicyByParent(environment);
+ envLevelAdminDSRestriction = envLevelPolicy.adminDataSourceRestriction;
+ }
+
+ return {
+ environmentPolicy: envLevelAdminDSRestriction,
+ projectPolicy: projectLevelAdminDSRestriction,
+ };
+ });
+
+ return {
+ ready,
+ dataSourceRestriction,
+ };
+};
+
+export const useEffectiveQueryDataPolicyForProject = (
+ project: MaybeRef<string>
+) => {
+ const store = usePolicyV1Store();
+ const ready = ref(false);
+
+ watchEffect(() => {
+ const projectName = unref(project);
+ // Fetch both workspace-level and project-level DATA_QUERY policies
+ Promise.all([
+ store.getOrFetchPolicyByParentAndType({
+ parentPath: "",
+ policyType: PolicyType.DATA_QUERY,
+ }),
+ store.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.DATA_QUERY,
+ }),
+ ]).finally(() => (ready.value = true));
+ });
+
+ const policy = computed(() => {
+ const workspacePolicy = formatQueryDataPolicy(
+ store.getQueryDataPolicyByParent("")
+ );
+ const projectPolicy = formatQueryDataPolicy(
+ store.getQueryDataPolicyByParent(unref(project))
+ );
+
+ return {
+ disableCopyData:
+ projectPolicy.disableCopyData || workspacePolicy.disableCopyData,
+ disableExport:
+ projectPolicy.disableExport || workspacePolicy.disableExport,
+ maximumResultRows: Math.min(
+ projectPolicy.maximumResultRows,
+ workspacePolicy.maximumResultRows
+ ),
+ maximumResultSize: Math.min(
+ projectPolicy.maximumResultSize,
+ workspacePolicy.maximumResultSize
+ ),
+ queryTimeoutInSeconds: Math.min(
+ projectPolicy.queryTimeoutInSeconds,
+ workspacePolicy.queryTimeoutInSeconds
+ ),
+ };
+ });
+
+ return {
+ policy,
+ ready,
+ };
+};
+
// getEmptyRolloutPolicy returns a default rollout policy for UI display purposes.
//
// IMPORTANT: These defaults MUST match the backend defaults defined in:
diff --git a/frontend/src/types/iam/permission-generated.ts b/frontend/src/types/iam/permission-generated.ts
index cdd4c22cf3..08708c312a 100644
--- a/frontend/src/types/iam/permission-generated.ts
+++ b/frontend/src/types/iam/permission-generated.ts
@@ -55,6 +55,14 @@ export type Permission =
| "bb.policies.get"
| "bb.policies.list"
| "bb.policies.update"
+ | "bb.policies.getMaskingRulePolicy"
+ | "bb.policies.updateMaskingRulePolicy"
+ | "bb.policies.createMaskingRulePolicy"
+ | "bb.policies.deleteMaskingRulePolicy"
+ | "bb.policies.getMaskingExemptionPolicy"
+ | "bb.policies.updateMaskingExemptionPolicy"
+ | "bb.policies.createMaskingExemptionPolicy"
+ | "bb.policies.deleteMaskingExemptionPolicy"
| "bb.projects.create"
| "bb.projects.delete"
| "bb.projects.get"
diff --git a/frontend/src/types/proto-es/v1/org_policy_service_pb.js b/frontend/src/types/proto-es/v1/org_policy_service_pb.js
index c9b9937832..15c056af96 100644
--- a/frontend/src/types/proto-es/v1/org_policy_service_pb.js
+++ b/frontend/src/types/proto-es/v1/org_policy_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_annotation } from "./annotation_pb";
* Describes the file v1/org_policy_service.proto.
*/
export const file_v1_org_policy_service = /*@__PURE__*/
- fileDesc("Cht2MS9vcmdfcG9saWN5X3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIpMBChNDcmVhdGVQb2xpY3lSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EigKBnBvbGljeRgCIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEiUKBHR5cGUYAyABKA4yFy5ieXRlYmFzZS52MS5Qb2xpY3lUeXBlIocBChNVcGRhdGVQb2xpY3lSZXF1ZXN0EigKBnBvbGljeRgBIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAMgASgIIkAKE0RlbGV0ZVBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5Ij0KEEdldFBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5IpsBChNMaXN0UG9saWNpZXNSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EjEKC3BvbGljeV90eXBlGAIgASgOMhcuYnl0ZWJhc2UudjEuUG9saWN5VHlwZUgAiAEBEhQKDHNob3dfZGVsZXRlZBgDIAEoCEIOCgxfcG9saWN5X3R5cGUiPQoUTGlzdFBvbGljaWVzUmVzcG9uc2USJQoIcG9saWNpZXMYASADKAsyEy5ieXRlYmFzZS52MS5Qb2xpY3kiiQYKBlBvbGljeRIMCgRuYW1lGAEgASgJEhsKE2luaGVyaXRfZnJvbV9wYXJlbnQYAiABKAgSJQoEdHlwZRgDIAEoDjIXLmJ5dGViYXNlLnYxLlBvbGljeVR5cGUSNAoOcm9sbG91dF9wb2xpY3kYBCABKAsyGi5ieXRlYmFzZS52MS5Sb2xsb3V0UG9saWN5SAASPQoTbWFza2luZ19ydWxlX3BvbGljeRgFIAEoCzIeLmJ5dGViYXNlLnYxLk1hc2tpbmdSdWxlUG9saWN5SAASRwoYbWFza2luZ19leGVtcHRpb25fcG9saWN5GAYgASgLMiMuYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeUgAEiwKCnRhZ19wb2xpY3kYByABKAsyFi5ieXRlYmFzZS52MS5UYWdQb2xpY3lIABJGChhkYXRhX3NvdXJjZV9xdWVyeV9wb2xpY3kYCCABKAsyIi5ieXRlYmFzZS52MS5EYXRhU291cmNlUXVlcnlQb2xpY3lIABI5ChFxdWVyeV9kYXRhX3BvbGljeRgJIAEoCzIcLmJ5dGViYXNlLnYxLlF1ZXJ5RGF0YVBvbGljeUgAEg8KB2VuZm9yY2UYCiABKAgSOwoNcmVzb3VyY2VfdHlwZRgLIAEoDjIfLmJ5dGViYXNlLnYxLlBvbGljeVJlc291cmNlVHlwZUID4EEDOuUB6kHhAQoTYnl0ZWJhc2UuY29tL1BvbGljeRIRcG9saWNpZXMve3BvbGljeX0SJHByb2plY3RzL3twcm9qZWN0fS9wb2xpY2llcy97cG9saWN5fRIsZW52aXJvbm1lbnRzL3tlbnZpcm9ubWVudH0vcG9saWNpZXMve3BvbGljeX0SJmluc3RhbmNlcy97aW5zdGFuY2V9L3BvbGljaWVzL3twb2xpY3l9EjtpbnN0YW5jZXMve2luc3RhbmNlfS9kYXRhYmFzZXMve2RhdGFiYXNlfS9wb2xpY2llcy97cG9saWN5fUIICgZwb2xpY3kiMQoNUm9sbG91dFBvbGljeRIRCglhdXRvbWF0aWMYASABKAgSDQoFcm9sZXMYAiADKAkiqgEKD1F1ZXJ5RGF0YVBvbGljeRIqCgd0aW1lb3V0GAEgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhYKDmRpc2FibGVfZXhwb3J0GAIgASgIEhsKE21heGltdW1fcmVzdWx0X3NpemUYAyABKAMSGwoTbWF4aW11bV9yZXN1bHRfcm93cxgEIAEoBRIZChFkaXNhYmxlX2NvcHlfZGF0YRgFIAEoCCKfAQoWTWFza2luZ0V4ZW1wdGlvblBvbGljeRJBCgpleGVtcHRpb25zGAEgAygLMi0uYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeS5FeGVtcHRpb24aQgoJRXhlbXB0aW9uEg8KB21lbWJlcnMYASADKAkSJAoJY29uZGl0aW9uGAIgASgLMhEuZ29vZ2xlLnR5cGUuRXhwciKmAQoRTWFza2luZ1J1bGVQb2xpY3kSOQoFcnVsZXMYASADKAsyKi5ieXRlYmFzZS52MS5NYXNraW5nUnVsZVBvbGljeS5NYXNraW5nUnVsZRpWCgtNYXNraW5nUnVsZRIKCgJpZBgBIAEoCRIkCgljb25kaXRpb24YAiABKAsyES5nb29nbGUudHlwZS5FeHByEhUKDXNlbWFudGljX3R5cGUYAyABKAkiaAoJVGFnUG9saWN5Ei4KBHRhZ3MYASADKAsyIC5ieXRlYmFzZS52MS5UYWdQb2xpY3kuVGFnc0VudHJ5GisKCVRhZ3NFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIuIBChVEYXRhU291cmNlUXVlcnlQb2xpY3kSVQodYWRtaW5fZGF0YV9zb3VyY2VfcmVzdHJpY3Rpb24YASABKA4yLi5ieXRlYmFzZS52MS5EYXRhU291cmNlUXVlcnlQb2xpY3kuUmVzdHJpY3Rpb24SFAoMZGlzYWxsb3dfZGRsGAIgASgIEhQKDGRpc2FsbG93X2RtbBgDIAEoCCJGCgtSZXN0cmljdGlvbhIbChdSRVNUUklDVElPTl9VTlNQRUNJRklFRBAAEgwKCEZBTExCQUNLEAESDAoIRElTQUxMT1cQAiqWAQoKUG9saWN5VHlwZRIbChdQT0xJQ1lfVFlQRV9VTlNQRUNJRklFRBAAEhAKDE1BU0tJTkdfUlVMRRABEhUKEU1BU0tJTkdfRVhFTVBUSU9OEAISEgoOUk9MTE9VVF9QT0xJQ1kQAxIHCgNUQUcQBBIVChFEQVRBX1NPVVJDRV9RVUVSWRAFEg4KCkRBVEFfUVVFUlkQBipgChJQb2xpY3lSZXNvdXJjZVR5cGUSHQoZUkVTT1VSQ0VfVFlQRV9VTlNQRUNJRklFRBAAEg0KCVdPUktTUEFDRRABEg8KC0VOVklST05NRU5UEAISCwoHUFJPSkVDVBADMvQMChBPcmdQb2xpY3lTZXJ2aWNlEqACCglHZXRQb2xpY3kSHS5ieXRlYmFzZS52MS5HZXRQb2xpY3lSZXF1ZXN0GhMuYnl0ZWJhc2UudjEuUG9saWN5It4B2kEEbmFtZYrqMA9iYi5wb2xpY2llcy5nZXSQ6jABgtPkkwK5AVoiEiAvdjEve25hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVomEiQvdjEve25hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn1aIxIhL3YxL3tuYW1lPWluc3RhbmNlcy8qL3BvbGljaWVzLyp9Wi8SLS92MS97bmFtZT1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKi9wb2xpY2llcy8qfRIVL3YxL3tuYW1lPXBvbGljaWVzLyp9EqgCCgxMaXN0UG9saWNpZXMSIC5ieXRlYmFzZS52MS5MaXN0UG9saWNpZXNSZXF1ZXN0GiEuYnl0ZWJhc2UudjEuTGlzdFBvbGljaWVzUmVzcG9uc2Ui0gHaQQCK6jAQYmIucG9saWNpZXMubGlzdJDqMAGC0+STArABWiISIC92MS97cGFyZW50PXByb2plY3RzLyp9L3BvbGljaWVzWiYSJC92MS97cGFyZW50PWVudmlyb25tZW50cy8qfS9wb2xpY2llc1ojEiEvdjEve3BhcmVudD1pbnN0YW5jZXMvKn0vcG9saWNpZXNaLxItL3YxL3twYXJlbnQ9aW5zdGFuY2VzLyovZGF0YWJhc2VzLyp9L3BvbGljaWVzEgwvdjEvcG9saWNpZXMS1QIKDENyZWF0ZVBvbGljeRIgLmJ5dGViYXNlLnYxLkNyZWF0ZVBvbGljeVJlcXVlc3QaEy5ieXRlYmFzZS52MS5Qb2xpY3kijQLaQQ1wYXJlbnQscG9saWN5iuowEmJiLnBvbGljaWVzLmNyZWF0ZZDqMAGY6jABgtPkkwLYAToGcG9saWN5Wio6BnBvbGljeSIgL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vcG9saWNpZXNaLjoGcG9saWN5IiQvdjEve3BhcmVudD1lbnZpcm9ubWVudHMvKn0vcG9saWNpZXNaKzoGcG9saWN5IiEvdjEve3BhcmVudD1pbnN0YW5jZXMvKn0vcG9saWNpZXNaNzoGcG9saWN5Ii0vdjEve3BhcmVudD1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKn0vcG9saWNpZXMiDC92MS9wb2xpY2llcxKGAwoMVXBkYXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuVXBkYXRlUG9saWN5UmVxdWVzdBoTLmJ5dGViYXNlLnYxLlBvbGljeSK+AtpBEnBvbGljeSx1cGRhdGVfbWFza4rqMBJiYi5wb2xpY2llcy51cGRhdGWQ6jABmOowAYLT5JMChAI6BnBvbGljeVoxOgZwb2xpY3kyJy92MS97cG9saWN5Lm5hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVo1OgZwb2xpY3kyKy92MS97cG9saWN5Lm5hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn1aMjoGcG9saWN5MigvdjEve3BvbGljeS5uYW1lPWluc3RhbmNlcy8qL3BvbGljaWVzLyp9Wj46BnBvbGljeTI0L3YxL3twb2xpY3kubmFtZT1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKi9wb2xpY2llcy8qfTIcL3YxL3twb2xpY3kubmFtZT1wb2xpY2llcy8qfRKwAgoMRGVsZXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuRGVsZXRlUG9saWN5UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSLlAdpBBG5hbWWK6jASYmIucG9saWNpZXMuZGVsZXRlkOowAZjqMAGC0+STArkBWiIqIC92MS97bmFtZT1wcm9qZWN0cy8qL3BvbGljaWVzLyp9WiYqJC92MS97bmFtZT1lbnZpcm9ubWVudHMvKi9wb2xpY2llcy8qfVojKiEvdjEve25hbWU9aW5zdGFuY2VzLyovcG9saWNpZXMvKn1aLyotL3YxL3tuYW1lPWluc3RhbmNlcy8qL2RhdGFiYXNlcy8qL3BvbGljaWVzLyp9KhUvdjEve25hbWU9cG9saWNpZXMvKn1CqwEKD2NvbS5ieXRlYmFzZS52MUIVT3JnUG9saWN5U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_type_expr, file_v1_annotation]);
+ fileDesc("Cht2MS9vcmdfcG9saWN5X3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIpMBChNDcmVhdGVQb2xpY3lSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EigKBnBvbGljeRgCIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEiUKBHR5cGUYAyABKA4yFy5ieXRlYmFzZS52MS5Qb2xpY3lUeXBlIocBChNVcGRhdGVQb2xpY3lSZXF1ZXN0EigKBnBvbGljeRgBIAEoCzITLmJ5dGViYXNlLnYxLlBvbGljeUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzaxIVCg1hbGxvd19taXNzaW5nGAMgASgIIkAKE0RlbGV0ZVBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5Ij0KEEdldFBvbGljeVJlcXVlc3QSKQoEbmFtZRgBIAEoCUIb4EEC+kEVChNieXRlYmFzZS5jb20vUG9saWN5IpsBChNMaXN0UG9saWNpZXNSZXF1ZXN0EisKBnBhcmVudBgBIAEoCUIb4EEC+kEVEhNieXRlYmFzZS5jb20vUG9saWN5EjEKC3BvbGljeV90eXBlGAIgASgOMhcuYnl0ZWJhc2UudjEuUG9saWN5VHlwZUgAiAEBEhQKDHNob3dfZGVsZXRlZBgDIAEoCEIOCgxfcG9saWN5X3R5cGUiPQoUTGlzdFBvbGljaWVzUmVzcG9uc2USJQoIcG9saWNpZXMYASADKAsyEy5ieXRlYmFzZS52MS5Qb2xpY3kiiQYKBlBvbGljeRIMCgRuYW1lGAEgASgJEhsKE2luaGVyaXRfZnJvbV9wYXJlbnQYAiABKAgSJQoEdHlwZRgDIAEoDjIXLmJ5dGViYXNlLnYxLlBvbGljeVR5cGUSNAoOcm9sbG91dF9wb2xpY3kYBCABKAsyGi5ieXRlYmFzZS52MS5Sb2xsb3V0UG9saWN5SAASPQoTbWFza2luZ19ydWxlX3BvbGljeRgFIAEoCzIeLmJ5dGViYXNlLnYxLk1hc2tpbmdSdWxlUG9saWN5SAASRwoYbWFza2luZ19leGVtcHRpb25fcG9saWN5GAYgASgLMiMuYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeUgAEiwKCnRhZ19wb2xpY3kYByABKAsyFi5ieXRlYmFzZS52MS5UYWdQb2xpY3lIABJGChhkYXRhX3NvdXJjZV9xdWVyeV9wb2xpY3kYCCABKAsyIi5ieXRlYmFzZS52MS5EYXRhU291cmNlUXVlcnlQb2xpY3lIABI5ChFxdWVyeV9kYXRhX3BvbGljeRgJIAEoCzIcLmJ5dGViYXNlLnYxLlF1ZXJ5RGF0YVBvbGljeUgAEg8KB2VuZm9yY2UYCiABKAgSOwoNcmVzb3VyY2VfdHlwZRgLIAEoDjIfLmJ5dGViYXNlLnYxLlBvbGljeVJlc291cmNlVHlwZUID4EEDOuUB6kHhAQoTYnl0ZWJhc2UuY29tL1BvbGljeRIRcG9saWNpZXMve3BvbGljeX0SJHByb2plY3RzL3twcm9qZWN0fS9wb2xpY2llcy97cG9saWN5fRIsZW52aXJvbm1lbnRzL3tlbnZpcm9ubWVudH0vcG9saWNpZXMve3BvbGljeX0SJmluc3RhbmNlcy97aW5zdGFuY2V9L3BvbGljaWVzL3twb2xpY3l9EjtpbnN0YW5jZXMve2luc3RhbmNlfS9kYXRhYmFzZXMve2RhdGFiYXNlfS9wb2xpY2llcy97cG9saWN5fUIICgZwb2xpY3kiMQoNUm9sbG91dFBvbGljeRIRCglhdXRvbWF0aWMYASABKAgSDQoFcm9sZXMYAiADKAkiqgEKD1F1ZXJ5RGF0YVBvbGljeRIqCgd0aW1lb3V0GAEgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhYKDmRpc2FibGVfZXhwb3J0GAIgASgIEhsKE21heGltdW1fcmVzdWx0X3NpemUYAyABKAMSGwoTbWF4aW11bV9yZXN1bHRfcm93cxgEIAEoBRIZChFkaXNhYmxlX2NvcHlfZGF0YRgFIAEoCCKfAQoWTWFza2luZ0V4ZW1wdGlvblBvbGljeRJBCgpleGVtcHRpb25zGAEgAygLMi0uYnl0ZWJhc2UudjEuTWFza2luZ0V4ZW1wdGlvblBvbGljeS5FeGVtcHRpb24aQgoJRXhlbXB0aW9uEg8KB21lbWJlcnMYASADKAkSJAoJY29uZGl0aW9uGAIgASgLMhEuZ29vZ2xlLnR5cGUuRXhwciKmAQoRTWFza2luZ1J1bGVQb2xpY3kSOQoFcnVsZXMYASADKAsyKi5ieXRlYmFzZS52MS5NYXNraW5nUnVsZVBvbGljeS5NYXNraW5nUnVsZRpWCgtNYXNraW5nUnVsZRIKCgJpZBgBIAEoCRIkCgljb25kaXRpb24YAiABKAsyES5nb29nbGUudHlwZS5FeHByEhUKDXNlbWFudGljX3R5cGUYAyABKAkiaAoJVGFnUG9saWN5Ei4KBHRhZ3MYASADKAsyIC5ieXRlYmFzZS52MS5UYWdQb2xpY3kuVGFnc0VudHJ5GisKCVRhZ3NFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIuIBChVEYXRhU291cmNlUXVlcnlQb2xpY3kSVQodYWRtaW5fZGF0YV9zb3VyY2VfcmVzdHJpY3Rpb24YASABKA4yLi5ieXRlYmFzZS52MS5EYXRhU291cmNlUXVlcnlQb2xpY3kuUmVzdHJpY3Rpb24SFAoMZGlzYWxsb3dfZGRsGAIgASgIEhQKDGRpc2FsbG93X2RtbBgDIAEoCCJGCgtSZXN0cmljdGlvbhIbChdSRVNUUklDVElPTl9VTlNQRUNJRklFRBAAEgwKCEZBTExCQUNLEAESDAoIRElTQUxMT1cQAiqWAQoKUG9saWN5VHlwZRIbChdQT0xJQ1lfVFlQRV9VTlNQRUNJRklFRBAAEhAKDE1BU0tJTkdfUlVMRRABEhUKEU1BU0tJTkdfRVhFTVBUSU9OEAISEgoOUk9MTE9VVF9QT0xJQ1kQAxIHCgNUQUcQBBIVChFEQVRBX1NPVVJDRV9RVUVSWRAFEg4KCkRBVEFfUVVFUlkQBipgChJQb2xpY3lSZXNvdXJjZVR5cGUSHQoZUkVTT1VSQ0VfVFlQRV9VTlNQRUNJRklFRBAAEg0KCVdPUktTUEFDRRABEg8KC0VOVklST05NRU5UEAISCwoHUFJPSkVDVBADMvQMChBPcmdQb2xpY3lTZXJ2aWNlEqACCglHZXRQb2xpY3kSHS5ieXRlYmFzZS52MS5HZXRQb2xpY3lSZXF1ZXN0GhMuYnl0ZWJhc2UudjEuUG9saWN5It4B2kEEbmFtZYrqMA9iYi5wb2xpY2llcy5nZXSQ6jACgtPkkwK5AVoiEiAvdjEve25hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVomEiQvdjEve25hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn1aIxIhL3YxL3tuYW1lPWluc3RhbmNlcy8qL3BvbGljaWVzLyp9Wi8SLS92MS97bmFtZT1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKi9wb2xpY2llcy8qfRIVL3YxL3tuYW1lPXBvbGljaWVzLyp9EqgCCgxMaXN0UG9saWNpZXMSIC5ieXRlYmFzZS52MS5MaXN0UG9saWNpZXNSZXF1ZXN0GiEuYnl0ZWJhc2UudjEuTGlzdFBvbGljaWVzUmVzcG9uc2Ui0gHaQQCK6jAQYmIucG9saWNpZXMubGlzdJDqMAGC0+STArABWiISIC92MS97cGFyZW50PXByb2plY3RzLyp9L3BvbGljaWVzWiYSJC92MS97cGFyZW50PWVudmlyb25tZW50cy8qfS9wb2xpY2llc1ojEiEvdjEve3BhcmVudD1pbnN0YW5jZXMvKn0vcG9saWNpZXNaLxItL3YxL3twYXJlbnQ9aW5zdGFuY2VzLyovZGF0YWJhc2VzLyp9L3BvbGljaWVzEgwvdjEvcG9saWNpZXMS1QIKDENyZWF0ZVBvbGljeRIgLmJ5dGViYXNlLnYxLkNyZWF0ZVBvbGljeVJlcXVlc3QaEy5ieXRlYmFzZS52MS5Qb2xpY3kijQLaQQ1wYXJlbnQscG9saWN5iuowEmJiLnBvbGljaWVzLmNyZWF0ZZDqMAKY6jABgtPkkwLYAToGcG9saWN5Wio6BnBvbGljeSIgL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vcG9saWNpZXNaLjoGcG9saWN5IiQvdjEve3BhcmVudD1lbnZpcm9ubWVudHMvKn0vcG9saWNpZXNaKzoGcG9saWN5IiEvdjEve3BhcmVudD1pbnN0YW5jZXMvKn0vcG9saWNpZXNaNzoGcG9saWN5Ii0vdjEve3BhcmVudD1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKn0vcG9saWNpZXMiDC92MS9wb2xpY2llcxKGAwoMVXBkYXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuVXBkYXRlUG9saWN5UmVxdWVzdBoTLmJ5dGViYXNlLnYxLlBvbGljeSK+AtpBEnBvbGljeSx1cGRhdGVfbWFza4rqMBJiYi5wb2xpY2llcy51cGRhdGWQ6jACmOowAYLT5JMChAI6BnBvbGljeVoxOgZwb2xpY3kyJy92MS97cG9saWN5Lm5hbWU9cHJvamVjdHMvKi9wb2xpY2llcy8qfVo1OgZwb2xpY3kyKy92MS97cG9saWN5Lm5hbWU9ZW52aXJvbm1lbnRzLyovcG9saWNpZXMvKn1aMjoGcG9saWN5MigvdjEve3BvbGljeS5uYW1lPWluc3RhbmNlcy8qL3BvbGljaWVzLyp9Wj46BnBvbGljeTI0L3YxL3twb2xpY3kubmFtZT1pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKi9wb2xpY2llcy8qfTIcL3YxL3twb2xpY3kubmFtZT1wb2xpY2llcy8qfRKwAgoMRGVsZXRlUG9saWN5EiAuYnl0ZWJhc2UudjEuRGVsZXRlUG9saWN5UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSLlAdpBBG5hbWWK6jASYmIucG9saWNpZXMuZGVsZXRlkOowApjqMAGC0+STArkBWiIqIC92MS97bmFtZT1wcm9qZWN0cy8qL3BvbGljaWVzLyp9WiYqJC92MS97bmFtZT1lbnZpcm9ubWVudHMvKi9wb2xpY2llcy8qfVojKiEvdjEve25hbWU9aW5zdGFuY2VzLyovcG9saWNpZXMvKn1aLyotL3YxL3tuYW1lPWluc3RhbmNlcy8qL2RhdGFiYXNlcy8qL3BvbGljaWVzLyp9KhUvdjEve25hbWU9cG9saWNpZXMvKn1CqwEKD2NvbS5ieXRlYmFzZS52MUIVT3JnUG9saWN5U2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_type_expr, file_v1_annotation]);
/**
* Describes the message bytebase.v1.CreatePolicyRequest.
diff --git a/frontend/src/utils/iam/permission-utils.ts b/frontend/src/utils/iam/permission-utils.ts
index 9d776abd47..b1ab2a09d0 100644
--- a/frontend/src/utils/iam/permission-utils.ts
+++ b/frontend/src/utils/iam/permission-utils.ts
@@ -1,4 +1,4 @@
-import type { ComposedDatabase, Permission } from "@/types";
+import type { Permission } from "@/types";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { hasProjectPermissionV2 } from "./permission";
@@ -23,11 +23,3 @@ export const hasPermissionToCreateChangeDatabaseIssueInProject = (
hasProjectPermissionV2(project, p)
);
};
-
-export const hasPermissionToCreateChangeDatabaseIssue = (
- database: ComposedDatabase
-) => {
- return hasPermissionToCreateChangeDatabaseIssueInProject(
- database.projectEntity
- );
-};
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index 477c4d09b1..ea85c91070 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -1,7 +1,7 @@
import dayjs from "dayjs";
import { head } from "lodash-es";
import { v1 as uuidv1 } from "uuid";
-import { useDatabaseV1Store, usePolicyV1Store } from "@/store";
+import { useDatabaseV1Store, useDataSourceRestrictionPolicy } from "@/store";
import type {
ComposedDatabase,
QueryDataSourceType,
@@ -19,11 +19,8 @@ import {
DataSourceType,
type InstanceResource,
} from "@/types/proto-es/v1/instance_service_pb";
-import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
-import {
- DataSourceQueryPolicy_Restriction,
- PolicyType,
-} from "@/types/proto-es/v1/org_policy_service_pb";
+import { DataSourceQueryPolicy_Restriction } from "@/types/proto-es/v1/org_policy_service_pb";
+import { wrapRefAsPromise } from "@/utils";
import { instanceV1AllowsCrossDatabaseQuery } from "./v1/instance";
export const NEW_WORKSHEET_TITLE = "new worksheet";
@@ -130,54 +127,24 @@ export const isConnectedSQLEditorTab = (tab: SQLEditorTab) => {
return database && isValidDatabaseName(database.name);
};
-export const getAdminDataSourceRestrictionOfDatabase = (
- database: ComposedDatabase
-) => {
- const policyStore = usePolicyV1Store();
- const projectLevelPolicy = policyStore.getPolicyByParentAndType({
- parentPath: database.project,
- policyType: PolicyType.DATA_SOURCE_QUERY,
- });
- const projectLevelAdminDSRestriction =
- projectLevelPolicy?.policy?.case === "dataSourceQueryPolicy"
- ? projectLevelPolicy.policy.value.adminDataSourceRestriction
- : undefined;
-
- let envLevelPolicy: Policy | undefined;
- if (database.effectiveEnvironment) {
- envLevelPolicy = policyStore.getPolicyByParentAndType({
- parentPath: database.effectiveEnvironment,
- policyType: PolicyType.DATA_SOURCE_QUERY,
- });
- }
-
- const envLevelAdminDSRestriction =
- envLevelPolicy?.policy?.case === "dataSourceQueryPolicy"
- ? envLevelPolicy.policy.value.adminDataSourceRestriction
- : undefined;
- return {
- environmentPolicy:
- envLevelAdminDSRestriction ??
- DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,
- projectPolicy:
- projectLevelAdminDSRestriction ??
- DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,
- };
-};
+const getDataSourceBehavior = async (database: ComposedDatabase) => {
+ const { ready, dataSourceRestriction } =
+ useDataSourceRestrictionPolicy(database);
+ await wrapRefAsPromise(ready, /* expected */ true);
-const getDataSourceBehavior = (database: ComposedDatabase) => {
- const restriction = getAdminDataSourceRestrictionOfDatabase(database);
let behavior: "RO" | "FALLBACK" | "ALLOW_ADMIN";
if (
- restriction.environmentPolicy ===
+ dataSourceRestriction.value.environmentPolicy ===
DataSourceQueryPolicy_Restriction.DISALLOW ||
- restriction.projectPolicy === DataSourceQueryPolicy_Restriction.DISALLOW
+ dataSourceRestriction.value.projectPolicy ===
+ DataSourceQueryPolicy_Restriction.DISALLOW
) {
behavior = "RO";
} else if (
- restriction.environmentPolicy ===
+ dataSourceRestriction.value.environmentPolicy ===
DataSourceQueryPolicy_Restriction.FALLBACK ||
- restriction.projectPolicy === DataSourceQueryPolicy_Restriction.FALLBACK
+ dataSourceRestriction.value.projectPolicy ===
+ DataSourceQueryPolicy_Restriction.FALLBACK
) {
behavior = "FALLBACK";
} else {
@@ -186,7 +153,7 @@ const getDataSourceBehavior = (database: ComposedDatabase) => {
return behavior;
};
-export const getValidDataSourceByPolicy = (
+export const getValidDataSourceByPolicy = async (
database: ComposedDatabase,
type?: QueryDataSourceType
) => {
@@ -197,7 +164,7 @@ export const getValidDataSourceByPolicy = (
(ds) => ds.type === DataSourceType.READ_ONLY
);
- const behavior = getDataSourceBehavior(database);
+ const behavior = await getDataSourceBehavior(database);
switch (behavior) {
case "ALLOW_ADMIN":
diff --git a/frontend/src/views/DatabaseDetail/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail/DatabaseDetail.vue
index 0284299382..b9a681e007 100644
--- a/frontend/src/views/DatabaseDetail/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail/DatabaseDetail.vue
@@ -99,30 +99,45 @@
data-label="bb-database-detail-action-buttons-container"
>
<SyncDatabaseButton
- v-if="allowSyncDatabase"
:type="'default'"
:text="false"
:database="database"
/>
<ExportSchemaButton :database="database" />
- <NButton
- v-if="allowTransferDatabase"
- @click.prevent="tryTransferProject"
- icon-placement="right"
+ <PermissionGuardWrapper
+ v-if="!isDefaultProject"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="['bb.databases.update']"
>
- <span>{{ $t("database.transfer-project") }}</span>
- <template #icon>
- <ArrowRightLeftIcon :size="16" />
- </template>
- </NButton>
- <NButton
- v-if="allowChangeDatabase"
- @click="() => {
- preCreateIssue(database.project, [database.name])
- }"
+ <NButton
+ :disabled="slotProps.disabled"
+ @click.prevent="tryTransferProject"
+ icon-placement="right"
+ >
+ <span>{{ $t("database.transfer-project") }}</span>
+ <template #icon>
+ <ArrowRightLeftIcon :size="16" />
+ </template>
+ </NButton>
+ </PermissionGuardWrapper>
+ <PermissionGuardWrapper
+ v-if="!isDefaultProject"
+ v-slot="slotProps"
+ :project="database.projectEntity"
+ :permissions="[
+ ...PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE
+ ]"
>
- <span>{{ $t("database.change-database") }}</span>
- </NButton>
+ <NButton
+ :disabled="slotProps.disabled"
+ @click="() => {
+ preCreateIssue(database.project, [database.name])
+ }"
+ >
+ <span>{{ $t("database.change-database") }}</span>
+ </NButton>
+ </PermissionGuardWrapper>
</div>
</div>
</main>
@@ -132,20 +147,33 @@
<DatabaseOverviewPanel class="mt-2" :database="database" />
</NTabPane>
<NTabPane
- v-if="allowListChangelogs"
name="changelog"
:tab="$t('common.changelog')"
>
- <DatabaseChangelogPanel class="mt-2" :database="database" />
+ <ComponentPermissionGuard
+ :project="project"
+ :permissions="['bb.changelogs.list']"
+ >
+ <DatabaseChangelogPanel class="mt-2" :database="database" />
+ </ComponentPermissionGuard>
</NTabPane>
<NTabPane name="revision" :tab="$t('database.revision.self')">
- <DatabaseRevisionPanel class="mt-2" :database="database" />
+ <ComponentPermissionGuard
+ :project="project"
+ :permissions="['bb.revisions.list']"
+ >
+ <DatabaseRevisionPanel class="mt-2" :database="database" />
+ </ComponentPermissionGuard>
</NTabPane>
<NTabPane name="catalog" :tab="$t('common.catalog')">
- <DatabaseSensitiveDataPanel class="mt-2" :database="database" />
+ <ComponentPermissionGuard
+ :project="project"
+ :permissions="['bb.databaseCatalogs.get']"
+ >
+ <DatabaseSensitiveDataPanel class="mt-2" :database="database" />
+ </ComponentPermissionGuard>
</NTabPane>
<NTabPane
- v-if="allowUpdateDatabase"
name="setting"
:tab="$t('common.settings')"
>
@@ -212,6 +240,8 @@ import DriftedDatabaseAlert from "@/components/DatabaseDetail/DriftedDatabaseAle
import ExportSchemaButton from "@/components/DatabaseDetail/ExportSchemaButton.vue";
import SyncDatabaseButton from "@/components/DatabaseDetail/SyncDatabaseButton.vue";
import EllipsisText from "@/components/EllipsisText.vue";
+import ComponentPermissionGuard from "@/components/Permission/ComponentPermissionGuard.vue";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { preCreateIssue } from "@/components/Plan/logic/issue";
import TransferOutDatabaseForm from "@/components/TransferOutDatabaseForm";
import {
@@ -231,6 +261,7 @@ import {
extractProjectResourceName,
instanceV1HasAlterSchema,
isDatabaseV1Queryable,
+ PERMISSIONS_FOR_DATABASE_CHANGE_ISSUE,
} from "@/utils";
const databaseHashList = [
@@ -266,18 +297,7 @@ const state = reactive<LocalState>({
selectedTab: "overview",
});
const route = useRoute();
-const {
- allowSyncDatabase,
- allowUpdateDatabase,
- allowTransferDatabase,
- allowChangeData,
- allowAlterSchema,
- allowListChangelogs,
-} = useDatabaseDetailContext();
-
-const allowChangeDatabase = computed(() => {
- return allowChangeData.value || allowAlterSchema.value;
-});
+const { isDefaultProject } = useDatabaseDetailContext();
watch(
() => route.hash,
diff --git a/frontend/src/views/EnvironmentDetail.vue b/frontend/src/views/EnvironmentDetail.vue
index 08e1aea47c..be15880d15 100644
--- a/frontend/src/views/EnvironmentDetail.vue
+++ b/frontend/src/views/EnvironmentDetail.vue
@@ -19,6 +19,7 @@
</template>
<script lang="ts" setup>
+import { create } from "@bufbuild/protobuf";
import { cloneDeep, isEqual } from "lodash-es";
import { computed, reactive, ref, watchEffect } from "vue";
import {
@@ -31,7 +32,11 @@ import { environmentNamePrefix } from "@/store/modules/v1/common";
import { usePolicyV1Store } from "@/store/modules/v1/policy";
import { formatEnvironmentName } from "@/types";
import type { Policy } from "@/types/proto-es/v1/org_policy_service_pb";
-import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ PolicySchema,
+ PolicyType,
+ RolloutPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
import type { Environment } from "@/types/v1/environment";
import { type VueClass } from "@/utils";
@@ -71,7 +76,14 @@ const preparePolicy = async () => {
parentPath: stateEnvironmentName.value,
policyType: PolicyType.ROLLOUT_POLICY,
});
- state.rolloutPolicy = policy;
+ state.rolloutPolicy =
+ policy ??
+ create(PolicySchema, {
+ policy: {
+ case: "rolloutPolicy",
+ value: create(RolloutPolicySchema, {}),
+ },
+ });
};
watchEffect(preparePolicy);
diff --git a/frontend/src/views/SettingWorkspaceGeneral.vue b/frontend/src/views/SettingWorkspaceGeneral.vue
index e00336dabf..72576238fa 100644
--- a/frontend/src/views/SettingWorkspaceGeneral.vue
+++ b/frontend/src/views/SettingWorkspaceGeneral.vue
@@ -3,41 +3,49 @@
<GeneralSetting
ref="generalSettingRef"
:title="$t('common.general')"
- :allow-edit="hasWorkspaceProfilePermission"
/>
<BrandingSetting
ref="brandingSettingRef"
:title="$t('settings.general.workspace.branding')"
- :allow-edit="hasWorkspaceProfilePermission"
/>
<AccountSetting
ref="accountSettingRef"
:title="$t('settings.general.workspace.account')"
- :allow-edit="hasWorkspaceProfilePermission"
/>
<SecuritySetting
ref="securitySettingRef"
:title="$t('settings.general.workspace.security')"
- :allow-edit="hasWorkspaceProfilePermission"
/>
<AIAugmentationSetting
ref="aiAugmentationSettingRef"
:title="$t('settings.general.workspace.ai-assistant.self')"
- :allow-edit="hasSettingPermission"
/>
<AnnouncementSetting
ref="announcementSettingRef"
:title="$t('settings.general.workspace.announcement.self')"
- :allow-edit="hasWorkspaceProfilePermission"
- />
- <ProductImprovementSetting
- ref="productImprovementSettingRef"
- :allow-edit="hasWorkspaceProfilePermission"
- />
- <AuditLogStdoutSetting
- ref="auditLogStdoutSettingRef"
- :allow-edit="hasWorkspaceProfilePermission"
/>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <ProductImprovementSetting
+ ref="productImprovementSettingRef"
+ :allow-edit="!slotProps.disabled"
+ />
+ </PermissionGuardWrapper>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
+ >
+ <AuditLogStdoutSetting
+ ref="auditLogStdoutSettingRef"
+ :allow-edit="!slotProps.disabled"
+ />
+ </PermissionGuardWrapper>
<div v-if="isDirty" class="sticky bottom-0 z-10">
<div
@@ -69,10 +77,10 @@ import {
ProductImprovementSetting,
SecuritySetting,
} from "@/components/GeneralSetting";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";
import { useBodyLayoutContext } from "@/layouts/common";
import { pushNotification } from "@/store";
-import { hasWorkspacePermissionV2 } from "@/utils";
const route = useRoute();
const { t } = useI18n();
@@ -89,13 +97,6 @@ const productImprovementSettingRef =
const auditLogStdoutSettingRef =
ref<InstanceType<typeof AuditLogStdoutSetting>>();
-const hasWorkspaceProfilePermission = computed(() =>
- hasWorkspacePermissionV2("bb.settings.setWorkspaceProfile")
-);
-const hasSettingPermission = computed(() =>
- hasWorkspacePermissionV2("bb.settings.set")
-);
-
const settingRefList = computed(() => {
return [
accountSettingRef,
diff --git a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
index 49ef988d22..174d254759 100644
--- a/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
+++ b/frontend/src/views/SettingWorkspaceSQLReviewDetail.vue
@@ -27,25 +27,51 @@
@on-focus="state.editingTitle = true"
@end-editing="changeName"
/>
- <div v-if="hasUpdateReviwConfigPermission" class="flex gap-x-2">
- <NButton
- v-if="reviewPolicy.enforce"
- @click.prevent="state.showDisableModal = true"
+ <div class="flex gap-x-2">
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.reviewConfigs.update'
+ ]"
>
- {{ $t("common.disable") }}
- </NButton>
- <NButton v-else @click.prevent="state.showEnableModal = true">
- {{ $t("common.enable") }}
- </NButton>
- <NButton
- v-if="reviewPolicy.resources.length > 0 && hasTagPolicyPermission"
- @click.prevent="state.showResourcePanel = true"
+ <NButton
+ v-if="reviewPolicy.enforce"
+ :disabled="slotProps.disabled"
+ @click.prevent="state.showDisableModal = true"
+ >
+ {{ $t("common.disable") }}
+ </NButton>
+ <NButton
+ v-else
+ :disabled="slotProps.disabled"
+ @click.prevent="state.showEnableModal = true"
+ >
+ {{ $t("common.enable") }}
+ </NButton>
+ </PermissionGuardWrapper>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.policies.update'
+ ]"
>
- {{ $t("sql-review.attach-resource.change-resources") }}
- </NButton>
- <NButton type="primary" @click="onEdit">
- {{ $t("sql-review.create.configure-rule.change-template") }}
- </NButton>
+ <NButton
+ :disabled="slotProps.disabled"
+ @click.prevent="state.showResourcePanel = true"
+ >
+ {{ $t("sql-review.attach-resource.change-resources") }}
+ </NButton>
+ </PermissionGuardWrapper>
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.reviewConfigs.update'
+ ]"
+ >
+ <NButton type="primary" :disabled="slotProps.disabled" @click="onEdit">
+ {{ $t("sql-review.create.configure-rule.change-template") }}
+ </NButton>
+ </PermissionGuardWrapper>
</div>
</div>
<div class="mt-4 flex flex-col gap-y-4">
@@ -158,6 +184,7 @@ import {
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { BBAlert, BBAttention, BBButtonConfirm, BBTextField } from "@/bbkit";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { SQLReviewCreation } from "@/components/SQLReview";
import SQLReviewAttachResourcesPanel from "@/components/SQLReview/components/SQLReviewAttachResourcesPanel.vue";
import SQLReviewTabsByEngine from "@/components/SQLReview/components/SQLReviewTabsByEngine.vue";
diff --git a/frontend/src/views/Setup/WorkspaceMode.vue b/frontend/src/views/Setup/WorkspaceMode.vue
index b5af451a00..77d8aa3a60 100644
--- a/frontend/src/views/Setup/WorkspaceMode.vue
+++ b/frontend/src/views/Setup/WorkspaceMode.vue
@@ -4,66 +4,70 @@
{{ $t("settings.general.workspace.default-landing-page.self") }}
</div>
<div class="w-full flex flex-col gap-8">
- <NRadioGroup
- :disabled="disabled"
- :value="mode"
- :size="'large'"
- @update:value="$emit('update:mode', $event)"
+ <PermissionGuardWrapper
+ v-slot="slotProps"
+ :permissions="[
+ 'bb.settings.setWorkspaceProfile'
+ ]"
>
- <NSpace vertical size="large">
- <NRadio :value="DatabaseChangeMode.PIPELINE">
- <div class="flex flex-col gap-1">
- <div class="textinfo">
- {{
- $t(
- "settings.general.workspace.default-landing-page.workspace.self"
- )
- }}
+ <NRadioGroup
+ :disabled="slotProps.disabled"
+ :value="mode"
+ :size="'large'"
+ @update:value="$emit('update:mode', $event)"
+ >
+ <NSpace vertical size="large">
+ <NRadio :value="DatabaseChangeMode.PIPELINE">
+ <div class="flex flex-col gap-1">
+ <div class="textinfo">
+ {{
+ $t(
+ "settings.general.workspace.default-landing-page.workspace.self"
+ )
+ }}
+ </div>
+ <div class="textinfolabel">
+ {{
+ $t(
+ "settings.general.workspace.default-landing-page.workspace.description"
+ )
+ }}
+ </div>
</div>
- <div class="textinfolabel">
- {{
- $t(
- "settings.general.workspace.default-landing-page.workspace.description"
- )
- }}
+ </NRadio>
+ <NRadio :value="DatabaseChangeMode.EDITOR">
+ <div class="flex flex-col gap-1">
+ <div class="textinfo">
+ {{
+ $t(
+ "settings.general.workspace.default-landing-page.sql-editor.self"
+ )
+ }}
+ </div>
+ <div class="textinfolabel">
+ {{
+ $t(
+ "settings.general.workspace.default-landing-page.sql-editor.description"
+ )
+ }}
+ </div>
</div>
- </div>
- </NRadio>
- <NRadio :value="DatabaseChangeMode.EDITOR">
- <div class="flex flex-col gap-1">
- <div class="textinfo">
- {{
- $t(
- "settings.general.workspace.default-landing-page.sql-editor.self"
- )
- }}
- </div>
- <div class="textinfolabel">
- {{
- $t(
- "settings.general.workspace.default-landing-page.sql-editor.description"
- )
- }}
- </div>
- </div>
- </NRadio>
- </NSpace>
- </NRadioGroup>
+ </NRadio>
+ </NSpace>
+ </NRadioGroup>
+ </PermissionGuardWrapper>
</div>
</div>
</template>
<script lang="ts" setup>
import { NRadio, NRadioGroup, NSpace } from "naive-ui";
+import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
-withDefaults(
- defineProps<{
- mode: DatabaseChangeMode;
- disabled?: boolean;
- }>(),
- { disabled: false }
-);
+defineProps<{
+ mode: DatabaseChangeMode;
+}>();
defineEmits<{
(event: "update:mode", mode: DatabaseChangeMode): void;
diff --git a/frontend/src/views/project/ProjectDatabaseLayout.vue b/frontend/src/views/project/ProjectDatabaseLayout.vue
index 4755131600..d6fe598e95 100644
--- a/frontend/src/views/project/ProjectDatabaseLayout.vue
+++ b/frontend/src/views/project/ProjectDatabaseLayout.vue
@@ -34,6 +34,7 @@ onMounted(async () => {
);
await dbSchemaStore.getOrFetchDatabaseMetadata({
database: database.name,
+ silent: true,
});
});
</script>
diff --git a/frontend/src/views/project/ProjectMaskingExemption.vue b/frontend/src/views/project/ProjectMaskingExemption.vue
index 02e1f7d240..7f56b3a747 100644
--- a/frontend/src/views/project/ProjectMaskingExemption.vue
+++ b/frontend/src/views/project/ProjectMaskingExemption.vue
@@ -22,7 +22,12 @@
<PermissionGuardWrapper
v-slot="slotProps"
:project="project"
- :permissions="['bb.policies.create', 'bb.databases.list']"
+ :permissions="[
+ 'bb.policies.createMaskingExemptionPolicy',
+ 'bb.policies.updateMaskingExemptionPolicy',
+ 'bb.databases.list',
+ 'bb.databaseCatalogs.get'
+ ]"
>
<NButton
type="primary"
@@ -53,7 +58,7 @@
</div>
<MaskingExceptionUserTable
size="medium"
- :disabled="false"
+ :disabled="!hasPermission"
:project="project"
:show-database-column="true"
:filter-access-user="filterAccessUser"
@@ -81,6 +86,7 @@ import { PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE } from "@/router/dashboard/pr
import { hasFeature, useProjectByName } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
interface LocalState {
searchText: string;
@@ -102,6 +108,13 @@ const { project } = useProjectByName(
computed(() => `${projectNamePrefix}${props.projectId}`)
);
+const hasPermission = computed(() =>
+ hasProjectPermissionV2(
+ project.value,
+ "bb.policies.updateMaskingExemptionPolicy"
+ )
+);
+
const hasSensitiveDataFeature = computed(() => {
return hasFeature(PlanFeature.FEATURE_DATA_MASKING);
});
diff --git a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
index e21917da0d..c1ef3321f5 100644
--- a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue
@@ -106,10 +106,14 @@ import { useI18n } from "vue-i18n";
import MaxRowCountSelect from "@/components/GrantRequestPanel/MaxRowCountSelect.vue";
import {
useConnectionOfCurrentSQLEditorTab,
- usePolicyV1Store,
useSQLEditorStore,
useSQLEditorTabStore,
} from "@/store";
+import {
+ useDataSourceRestrictionPolicy,
+ useEffectiveQueryDataPolicyForProject,
+ usePolicyV1Store,
+} from "@/store/modules/v1/policy";
import { isValidDatabaseName } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
@@ -122,11 +126,7 @@ import {
PolicyType,
} from "@/types/proto-es/v1/org_policy_service_pb";
import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";
-import {
- getAdminDataSourceRestrictionOfDatabase,
- getValidDataSourceByPolicy,
- readableDataSourceType,
-} from "@/utils";
+import { getValidDataSourceByPolicy, readableDataSourceType } from "@/utils";
defineProps<{
disabled?: boolean;
@@ -141,9 +141,13 @@ const { redisCommandOption, resultRowsLimit, project } = storeToRefs(
useSQLEditorStore()
);
+const { policy: effectiveQueryDataPolicy } =
+ useEffectiveQueryDataPolicyForProject(project);
+
+const { dataSourceRestriction } = useDataSourceRestrictionPolicy(database);
+
const maximumResultRows = computed(() => {
- return policyStore.getEffectiveQueryDataPolicyForProject(project.value)
- .maximumResultRows;
+ return effectiveQueryDataPolicy.value.maximumResultRows;
});
const show = computed(() => {
@@ -158,17 +162,6 @@ const showRedisConfig = computed(() => {
return instance.engine === Engine.REDIS;
});
-const adminDataSourceRestriction = computed(() => {
- if (!database.value) {
- return {
- environmentPolicy:
- DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,
- projectPolicy: DataSourceQueryPolicy_Restriction.RESTRICTION_UNSPECIFIED,
- };
- }
- return getAdminDataSourceRestrictionOfDatabase(database.value);
-});
-
const selectedDataSourceId = computed(() => {
return connection.value.dataSourceId;
});
@@ -189,9 +182,9 @@ const dataSourceUnaccessibleReason = (
): string | undefined => {
if (dataSource.type === DataSourceType.ADMIN) {
if (
- adminDataSourceRestriction.value.environmentPolicy ===
+ dataSourceRestriction.value.environmentPolicy ===
DataSourceQueryPolicy_Restriction.DISALLOW ||
- adminDataSourceRestriction.value.projectPolicy ===
+ dataSourceRestriction.value.projectPolicy ===
DataSourceQueryPolicy_Restriction.DISALLOW
) {
return t(
@@ -203,9 +196,9 @@ const dataSourceUnaccessibleReason = (
);
if (
readOnlyDataSources.length > 0 &&
- (adminDataSourceRestriction.value.environmentPolicy ===
+ (dataSourceRestriction.value.environmentPolicy ===
DataSourceQueryPolicy_Restriction.FALLBACK ||
- adminDataSourceRestriction.value.projectPolicy ===
+ dataSourceRestriction.value.projectPolicy ===
DataSourceQueryPolicy_Restriction.FALLBACK)
) {
return t(
@@ -228,10 +221,10 @@ const onDataSourceSelected = (dataSourceId?: string) => {
watch(
[() => selectedDataSourceId.value, () => database.value],
- ([current, database]) => {
+ async ([current, database]) => {
if (!isValidDatabaseName(database.name)) return;
if (!current) {
- const fixed = getValidDataSourceByPolicy(database);
+ const fixed = await getValidDataSourceByPolicy(database);
onDataSourceSelected(fixed);
}
},
@@ -246,16 +239,21 @@ watch(
if (!isValidDatabaseName(database.value.name)) {
return;
}
- if (database.value.effectiveEnvironment) {
- await policyStore.getOrFetchPolicyByParentAndType({
- parentPath: database.value.effectiveEnvironment,
+ const requests = [
+ policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: database.value.project,
policyType: PolicyType.DATA_SOURCE_QUERY,
- });
+ }),
+ ];
+ if (database.value.effectiveEnvironment) {
+ requests.push(
+ policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: database.value.effectiveEnvironment,
+ policyType: PolicyType.DATA_SOURCE_QUERY,
+ })
+ );
}
- await policyStore.getOrFetchPolicyByParentAndType({
- parentPath: database.value.project,
- policyType: PolicyType.DATA_SOURCE_QUERY,
- });
+ await Promise.all(requests);
},
{
immediate: true,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
index a2f6ceaf98..074364e5c4 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -174,7 +174,7 @@ import {
NTooltip,
} from "naive-ui";
import { storeToRefs } from "pinia";
-import { computed, ref, toRef } from "vue";
+import { computed, ref, toRef, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
import { darkThemeOverrides } from "@/../naive-ui.config";
import { BBSpin } from "@/bbkit";
@@ -187,12 +187,11 @@ import type {
import DataExportButton from "@/components/DataExportButton.vue";
import { parseStringToResource } from "@/components/GrantRequestPanel/DatabaseResourceForm/common";
import { Drawer } from "@/components/v2";
+import { useSQLEditorStore, useSQLEditorTabStore, useSQLStore } from "@/store";
import {
+ useEffectiveQueryDataPolicyForProject,
usePolicyV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useSQLStore,
-} from "@/store";
+} from "@/store/modules/v1/policy";
import type {
ComposedDatabase,
DatabaseResource,
@@ -200,8 +199,8 @@ import type {
SQLResultSetV1,
} from "@/types";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
+import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
-
import type { SQLResultViewContext } from "./context";
import { provideSQLResultViewContext } from "./context";
import { provideBinaryFormatContext } from "./DataTable/common/binary-format-store";
@@ -239,8 +238,17 @@ const policyStore = usePolicyV1Store();
const tabStore = useSQLEditorTabStore();
const { project } = storeToRefs(useSQLEditorStore());
-const effectiveQueryDataPolicy = computed(() => {
- return policyStore.getEffectiveQueryDataPolicyForProject(project.value);
+const { policy: effectiveQueryDataPolicy } =
+ useEffectiveQueryDataPolicyForProject(project);
+
+watchEffect(() => {
+ const environment = props.database.effectiveEnvironment;
+ if (environment) {
+ policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: environment,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ }
});
const detail: SQLResultViewContext["detail"] = ref(undefined);
@@ -306,10 +314,7 @@ const tabName = (index: number) => {
};
const disallowCopyingData = computed(() => {
- if (
- policyStore.getQueryDataPolicyByParent(props.database.project)
- .disableCopyData
- ) {
+ if (effectiveQueryDataPolicy.value.disableCopyData) {
return true;
}
// If the database is provided, use its effective environment.
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
index fb47dbd469..6da348a14c 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
@@ -126,11 +126,11 @@ import { t } from "@/plugins/i18n";
import {
pushNotification,
useDatabaseV1Store,
- usePolicyV1Store,
useSQLEditorStore,
useSQLEditorTabStore,
useSQLStore,
} from "@/store";
+import { useEffectiveQueryDataPolicyForProject } from "@/store/modules/v1/policy";
import type { ComposedDatabase, SQLEditorDatabaseQueryContext } from "@/types";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
@@ -158,14 +158,12 @@ const { currentTab: tab } = storeToRefs(tabStore);
const databaseStore = useDatabaseV1Store();
const sqlStore = useSQLStore();
const showEmpty = ref<boolean>(true);
-const policyStore = usePolicyV1Store();
const { project } = storeToRefs(useSQLEditorStore());
const contextMenu = provideResultTabListContext();
const contextMenuRef = ref<InstanceType<typeof ContextMenu>>();
-const effectiveQueryDataPolicy = computed(() => {
- return policyStore.getEffectiveQueryDataPolicyForProject(project.value);
-});
+const { policy: effectiveQueryDataPolicy } =
+ useEffectiveQueryDataPolicyForProject(project);
const selectedDatabaseNameList = ref<string[]>([]);
diff --git a/proto/v1/v1/org_policy_service.proto b/proto/v1/v1/org_policy_service.proto
index 06f0db930b..089921dd71 100644
--- a/proto/v1/v1/org_policy_service.proto
+++ b/proto/v1/v1/org_policy_service.proto
@@ -29,7 +29,7 @@ service OrgPolicyService {
};
option (google.api.method_signature) = "name";
option (bytebase.v1.permission) = "bb.policies.get";
- option (bytebase.v1.auth_method) = IAM;
+ option (bytebase.v1.auth_method) = CUSTOM;
}
// Lists policies at a specified resource level.
@@ -74,7 +74,7 @@ service OrgPolicyService {
};
option (google.api.method_signature) = "parent,policy";
option (bytebase.v1.permission) = "bb.policies.create";
- option (bytebase.v1.auth_method) = IAM;
+ option (bytebase.v1.auth_method) = CUSTOM;
option (bytebase.v1.audit) = true;
}
@@ -104,7 +104,7 @@ service OrgPolicyService {
};
option (google.api.method_signature) = "policy,update_mask";
option (bytebase.v1.permission) = "bb.policies.update";
- option (bytebase.v1.auth_method) = IAM;
+ option (bytebase.v1.auth_method) = CUSTOM;
option (bytebase.v1.audit) = true;
}
@@ -121,7 +121,7 @@ service OrgPolicyService {
};
option (google.api.method_signature) = "name";
option (bytebase.v1.permission) = "bb.policies.delete";
- option (bytebase.v1.auth_method) = IAM;
+ option (bytebase.v1.auth_method) = CUSTOM;
option (bytebase.v1.audit) = true;
}
}