Skip to content

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

chore: policy resource (#15206)

Danny Xuf5dc0978a873
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index 5662825197..d3d5494c53 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -361,7 +361,7 @@ func (s *InstanceService) syncSlowQueriesForInstance(ctx context.Context, instan
return nil, status.Errorf(codes.NotFound, "instance %q has been deleted", instanceName)
}
- slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, api.PolicyResourceTypeInstance, instance.UID)
+ slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, instance.ResourceID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -475,7 +475,7 @@ func (s *InstanceService) syncSlowQueriesForProject(ctx context.Context, project
continue
}
- slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, api.PolicyResourceTypeInstance, instance.UID)
+ slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, instance.ResourceID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 81fe02400f..c81c917908 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -727,7 +727,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, request *v1pb.ApproveIs
return nil, status.Errorf(codes.Internal, "failed to find user by id %v", principalID)
}
- policy, err := s.store.GetProjectIamPolicy(ctx, issue.Project.UID)
+ policy, err := s.store.GetProjectIamPolicy(ctx, issue.Project.ResourceID)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get project policy, error: %v", err)
}
@@ -948,7 +948,7 @@ func (s *IssueService) RejectIssue(ctx context.Context, request *v1pb.RejectIssu
return nil, status.Errorf(codes.Internal, "failed to find user by id %v", principalID)
}
- policy, err := s.store.GetProjectIamPolicy(ctx, issue.Project.UID)
+ policy, err := s.store.GetProjectIamPolicy(ctx, issue.Project.ResourceID)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get project policy, error: %v", err)
}
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index b11b14dd7a..d323197833 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -3,7 +3,6 @@ package v1
import (
"context"
"fmt"
- "log/slog"
"strings"
"github.com/pkg/errors"
@@ -14,7 +13,6 @@ import (
"google.golang.org/protobuf/types/known/emptypb"
"github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/log"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/store"
@@ -39,12 +37,12 @@ func NewOrgPolicyService(store *store.Store, licenseService enterprise.LicenseSe
// GetPolicy gets a policy in a specific resource.
func (s *OrgPolicyService) GetPolicy(ctx context.Context, request *v1pb.GetPolicyRequest) (*v1pb.Policy, error) {
- policy, parent, err := s.findPolicyMessage(ctx, request.Name)
+ policy, _, err := s.findPolicyMessage(ctx, request.Name)
if err != nil {
return nil, err
}
- response, err := s.convertToPolicy(ctx, parent, policy)
+ response, err := s.convertToPolicy(ctx, policy)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -54,14 +52,14 @@ func (s *OrgPolicyService) GetPolicy(ctx context.Context, request *v1pb.GetPolic
// ListPolicies lists policies in a specific resource.
func (s *OrgPolicyService) ListPolicies(ctx context.Context, request *v1pb.ListPoliciesRequest) (*v1pb.ListPoliciesResponse, error) {
- resourceType, resourceID, err := s.getPolicyResourceTypeAndID(ctx, request.Parent)
+ resourceType, resource, err := getPolicyResourceTypeAndResource(request.Parent)
if err != nil {
return nil, err
}
find := &store.FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: resourceID,
+ Resource: resource,
ShowDeleted: request.ShowDeleted,
}
@@ -80,16 +78,7 @@ func (s *OrgPolicyService) ListPolicies(ctx context.Context, request *v1pb.ListP
response := &v1pb.ListPoliciesResponse{}
for _, policy := range policies {
- parentPath, err := s.getPolicyParentPath(ctx, policy)
- if err != nil {
- st := status.Convert(err)
- if st.Code() == codes.NotFound {
- slog.Debug("failed to found resource for policy", log.BBError(err), slog.String("resource_type", string(policy.ResourceType)), slog.Int("resource_id", policy.ResourceUID))
- continue
- }
- return nil, err
- }
- p, err := s.convertToPolicy(ctx, parentPath, policy)
+ p, err := s.convertToPolicy(ctx, policy)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -134,7 +123,7 @@ func (s *OrgPolicyService) UpdatePolicy(ctx context.Context, request *v1pb.Updat
patch := &store.UpdatePolicyMessage{
ResourceType: policy.ResourceType,
Type: policy.Type,
- ResourceUID: policy.ResourceUID,
+ Resource: policy.Resource,
}
for _, path := range request.UpdateMask.Paths {
switch path {
@@ -159,7 +148,7 @@ func (s *OrgPolicyService) UpdatePolicy(ctx context.Context, request *v1pb.Updat
return nil, status.Error(codes.Internal, err.Error())
}
- response, err := s.convertToPolicy(ctx, parent, p)
+ response, err := s.convertToPolicy(ctx, p)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -192,12 +181,12 @@ func (s *OrgPolicyService) findPolicyMessage(ctx context.Context, policyName str
if strings.HasSuffix(policyParent, "/") {
policyParent = policyParent[:(len(policyParent) - 1)]
}
- resourceType, resourceID, err := s.getPolicyResourceTypeAndID(ctx, policyParent)
+ resourceType, resource, err := getPolicyResourceTypeAndResource(policyParent)
if err != nil {
return nil, policyParent, err
}
- if resourceID == nil && resourceType != api.PolicyResourceTypeWorkspace {
- return nil, policyParent, status.Errorf(codes.InvalidArgument, "resource id for %s must be specific", resourceType)
+ if resource == nil && resourceType != api.PolicyResourceTypeWorkspace {
+ return nil, policyParent, status.Errorf(codes.InvalidArgument, "resource for %s must be specific", resourceType)
}
policyType, err := convertPolicyType(tokens[1])
@@ -208,7 +197,7 @@ func (s *OrgPolicyService) findPolicyMessage(ctx context.Context, policyName str
policy, err := s.store.GetPolicyV2(ctx, &store.FindPolicyMessage{
ResourceType: &resourceType,
Type: &policyType,
- ResourceUID: resourceID,
+ Resource: resource,
})
if err != nil {
return nil, policyParent, status.Error(codes.Internal, err.Error())
@@ -220,7 +209,7 @@ func (s *OrgPolicyService) findPolicyMessage(ctx context.Context, policyName str
return policy, policyParent, nil
}
-func (s *OrgPolicyService) getPolicyResourceTypeAndID(ctx context.Context, requestName string) (api.PolicyResourceType, *int, error) {
+func getPolicyResourceTypeAndResource(requestName string) (api.PolicyResourceType, *string, error) {
if requestName == "" {
return api.PolicyResourceTypeWorkspace, nil, nil
}
@@ -233,19 +222,10 @@ func (s *OrgPolicyService) getPolicyResourceTypeAndID(ctx context.Context, reque
if projectID == "-" {
return api.PolicyResourceTypeProject, nil, nil
}
- project, err := s.findActiveProject(ctx, &store.FindProjectMessage{
- ResourceID: &projectID,
- })
- if err != nil {
- return api.PolicyResourceTypeUnknown, nil, status.Error(codes.Internal, err.Error())
- }
-
- return api.PolicyResourceTypeProject, &project.UID, nil
+ return api.PolicyResourceTypeProject, &requestName, nil
}
- sections := strings.Split(requestName, "/")
-
- if strings.HasPrefix(requestName, common.EnvironmentNamePrefix) && len(sections) == 2 {
+ if strings.HasPrefix(requestName, common.EnvironmentNamePrefix) {
// environment policy request name should be environments/{environment id}
environmentID, err := common.GetEnvironmentID(requestName)
if err != nil {
@@ -254,16 +234,10 @@ func (s *OrgPolicyService) getPolicyResourceTypeAndID(ctx context.Context, reque
if environmentID == "-" {
return api.PolicyResourceTypeEnvironment, nil, nil
}
- environment, err := s.findActiveEnvironment(ctx, &store.FindEnvironmentMessage{
- ResourceID: &environmentID,
- })
- if err != nil {
- return api.PolicyResourceTypeUnknown, nil, err
- }
-
- return api.PolicyResourceTypeEnvironment, &environment.UID, nil
+ return api.PolicyResourceTypeEnvironment, &requestName, nil
}
+ sections := strings.Split(requestName, "/")
if strings.HasPrefix(requestName, common.InstanceNamePrefix) && len(sections) == 2 {
// instance policy request name should be instances/{instance id}
instanceID, err := common.GetInstanceID(requestName)
@@ -273,108 +247,29 @@ func (s *OrgPolicyService) getPolicyResourceTypeAndID(ctx context.Context, reque
if instanceID == "-" {
return api.PolicyResourceTypeInstance, nil, nil
}
-
- instance, err := s.findActiveInstance(ctx, &store.FindInstanceMessage{
- ResourceID: &instanceID,
- })
- if err != nil {
- return api.PolicyResourceTypeUnknown, nil, err
- }
-
- return api.PolicyResourceTypeInstance, &instance.UID, nil
+ return api.PolicyResourceTypeInstance, &requestName, nil
}
if strings.HasPrefix(requestName, common.InstanceNamePrefix) && len(sections) == 4 {
// database policy request name should be instances/{instance id}/databases/{db name}
-
- instanceID, databaseName, err := common.GetInstanceDatabaseID(requestName)
+ _, databaseName, err := common.GetInstanceDatabaseID(requestName)
if err != nil {
return api.PolicyResourceTypeUnknown, nil, status.Error(codes.InvalidArgument, err.Error())
}
if databaseName == "-" {
return api.PolicyResourceTypeDatabase, nil, nil
}
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
- if err != nil {
- return api.PolicyResourceTypeUnknown, nil, status.Error(codes.Internal, err.Error())
- }
- if instance == nil {
- return api.PolicyResourceTypeUnknown, nil, status.Errorf(codes.NotFound, "instance %q not found", instanceID)
- }
- database, err := s.findActiveDatabase(ctx, &store.FindDatabaseMessage{
- InstanceID: &instanceID,
- DatabaseName: &databaseName,
- IgnoreCaseSensitive: store.IgnoreDatabaseAndTableCaseSensitive(instance),
- })
- if err != nil {
- return api.PolicyResourceTypeUnknown, nil, status.Error(codes.Internal, err.Error())
- }
- if database == nil {
- return api.PolicyResourceTypeUnknown, nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)
- }
-
- return api.PolicyResourceTypeDatabase, &database.UID, nil
+ return api.PolicyResourceTypeDatabase, &requestName, nil
}
return api.PolicyResourceTypeUnknown, nil, status.Errorf(codes.InvalidArgument, "unknown request name %s", requestName)
}
-func (s *OrgPolicyService) findActiveProject(ctx context.Context, find *store.FindProjectMessage) (*store.ProjectMessage, error) {
- find.ShowDeleted = false
- project, err := s.store.GetProjectV2(ctx, find)
- if err != nil {
- return nil, status.Error(codes.Internal, err.Error())
- }
- if project == nil {
- return nil, status.Errorf(codes.NotFound, "project not found")
- }
- return project, nil
-}
-
-func (s *OrgPolicyService) findActiveEnvironment(ctx context.Context, find *store.FindEnvironmentMessage) (*store.EnvironmentMessage, error) {
- find.ShowDeleted = false
- environment, err := s.store.GetEnvironmentV2(ctx, find)
- if err != nil {
- return nil, status.Error(codes.Internal, err.Error())
- }
- if environment == nil {
- return nil, status.Errorf(codes.NotFound, "environment %v not found", find)
- }
- return environment, nil
-}
-
-func (s *OrgPolicyService) findActiveInstance(ctx context.Context, find *store.FindInstanceMessage) (*store.InstanceMessage, error) {
- find.ShowDeleted = false
- instance, err := s.store.GetInstanceV2(ctx, find)
- if err != nil {
- return nil, status.Error(codes.Internal, err.Error())
- }
- if instance == nil {
- return nil, status.Errorf(codes.NotFound, "instance %v not found", find)
- }
- return instance, nil
-}
-
-func (s *OrgPolicyService) findActiveDatabase(ctx context.Context, find *store.FindDatabaseMessage) (*store.DatabaseMessage, error) {
- find.ShowDeleted = false
- database, err := s.store.GetDatabaseV2(ctx, find)
- if err != nil {
- return nil, status.Error(codes.Internal, err.Error())
- }
- if database == nil {
- return nil, status.Errorf(codes.NotFound, "database %v not found", find)
- }
- return database, nil
-}
-
func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent string, policy *v1pb.Policy) (*v1pb.Policy, error) {
- resourceType, resourceID, err := s.getPolicyResourceTypeAndID(ctx, parent)
+ resourceType, _, err := getPolicyResourceTypeAndResource(parent)
if err != nil {
return nil, err
}
- if resourceID == nil && resourceType != api.PolicyResourceTypeWorkspace {
- return nil, status.Errorf(codes.InvalidArgument, "resource id for %s must be specific", resourceType)
- }
policyType, err := convertPolicyType(policy.Type.String())
if err != nil {
@@ -396,22 +291,20 @@ func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent strin
create := &store.PolicyMessage{
ResourceType: resourceType,
+ Resource: parent,
Payload: payloadStr,
Type: policyType,
InheritFromParent: policy.InheritFromParent,
// Enforce cannot be false while creating a policy.
Enforce: true,
}
- if resourceID != nil {
- create.ResourceUID = *resourceID
- }
p, err := s.store.CreatePolicyV2(ctx, create)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
- response, err := s.convertToPolicy(ctx, parent, p)
+ response, err := s.convertToPolicy(ctx, p)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -419,45 +312,6 @@ func (s *OrgPolicyService) createPolicyMessage(ctx context.Context, parent strin
return response, nil
}
-func (s *OrgPolicyService) getPolicyParentPath(ctx context.Context, policyMessage *store.PolicyMessage) (string, error) {
- switch policyMessage.ResourceType {
- case api.PolicyResourceTypeEnvironment:
- env, err := s.findActiveEnvironment(ctx, &store.FindEnvironmentMessage{
- UID: &policyMessage.ResourceUID,
- })
- if err != nil {
- return "", err
- }
- return common.FormatEnvironment(env.ResourceID), nil
- case api.PolicyResourceTypeProject:
- proj, err := s.findActiveProject(ctx, &store.FindProjectMessage{
- UID: &policyMessage.ResourceUID,
- })
- if err != nil {
- return "", err
- }
- return common.FormatProject(proj.ResourceID), nil
- case api.PolicyResourceTypeInstance:
- ins, err := s.findActiveInstance(ctx, &store.FindInstanceMessage{
- UID: &policyMessage.ResourceUID,
- })
- if err != nil {
- return "", err
- }
- return common.FormatInstance(ins.ResourceID), nil
- case api.PolicyResourceTypeDatabase:
- db, err := s.findActiveDatabase(ctx, &store.FindDatabaseMessage{
- UID: &policyMessage.ResourceUID,
- })
- if err != nil {
- return "", err
- }
- return common.FormatDatabase(db.InstanceID, db.DatabaseName), nil
- default:
- return "", nil
- }
-}
-
func validatePolicyType(policyType api.PolicyType, policyResourceType api.PolicyResourceType) error {
for _, rt := range api.AllowedResourceTypes[policyType] {
if rt == policyResourceType {
@@ -622,7 +476,7 @@ func (s *OrgPolicyService) convertPolicyPayloadToString(ctx context.Context, pol
return "", status.Errorf(codes.InvalidArgument, "invalid policy %v", policy.Type)
}
-func (s *OrgPolicyService) convertToPolicy(ctx context.Context, parentPath string, policyMessage *store.PolicyMessage) (*v1pb.Policy, error) {
+func (s *OrgPolicyService) convertToPolicy(ctx context.Context, policyMessage *store.PolicyMessage) (*v1pb.Policy, error) {
resourceType := v1pb.PolicyResourceType_RESOURCE_TYPE_UNSPECIFIED
switch policyMessage.ResourceType {
case api.PolicyResourceTypeWorkspace:
@@ -725,8 +579,8 @@ func (s *OrgPolicyService) convertToPolicy(ctx context.Context, parentPath strin
policy.Type = pType
policy.Name = fmt.Sprintf("%s%s", common.PolicyNamePrefix, strings.ToLower(pType.String()))
- if parentPath != "" {
- policy.Name = fmt.Sprintf("%s/%s", parentPath, policy.Name)
+ if policyMessage.Resource != "" {
+ policy.Name = fmt.Sprintf("%s/%s", policyMessage.Resource, policy.Name)
}
return policy, nil
diff --git a/backend/api/v1/predicate_columns_check.go b/backend/api/v1/predicate_columns_check.go
index d6a7ca546a..3044a8815b 100644
--- a/backend/api/v1/predicate_columns_check.go
+++ b/backend/api/v1/predicate_columns_check.go
@@ -117,7 +117,7 @@ func (s *QueryResultMasker) getSensitiveColumnsForPredicate(
}
if _, ok := maskingExceptionPolicyMap[database.ProjectID]; !ok {
- policy, err := s.store.GetMaskingExceptionPolicyByProjectUID(ctx, project.UID)
+ policy, err := s.store.GetMaskingExceptionPolicyByProjectUID(ctx, project.ResourceID)
if err != nil {
return nil, errors.Wrapf(err, "failed to find masking exception policy for project %q", project.ResourceID)
}
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index 28a1c18b04..893f79a04f 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -349,7 +349,7 @@ func (s *ProjectService) GetIamPolicy(ctx context.Context, request *v1pb.GetIamP
return nil, status.Errorf(codes.NotFound, "cannot found project %s", projectID)
}
- policy, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ policy, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -375,7 +375,7 @@ func (s *ProjectService) BatchGetIamPolicy(ctx context.Context, request *v1pb.Ba
if project == nil {
continue
}
- policy, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ policy, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
@@ -422,7 +422,7 @@ func (s *ProjectService) SetIamPolicy(ctx context.Context, request *v1pb.SetIamP
return nil, status.Error(codes.Internal, err.Error())
}
- policyMessage, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ policyMessage, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find project iam policy with error: %v", err.Error())
}
@@ -436,7 +436,7 @@ func (s *ProjectService) SetIamPolicy(ctx context.Context, request *v1pb.SetIamP
return nil, status.Error(codes.Internal, err.Error())
}
if _, err := s.store.CreatePolicyV2(ctx, &store.PolicyMessage{
- ResourceUID: project.UID,
+ Resource: common.FormatProject(project.ResourceID),
ResourceType: api.PolicyResourceTypeProject,
Payload: string(policyPayload),
Type: api.PolicyTypeIAM,
@@ -447,7 +447,7 @@ func (s *ProjectService) SetIamPolicy(ctx context.Context, request *v1pb.SetIamP
return nil, status.Error(codes.Internal, err.Error())
}
- iamPolicyMessage, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ iamPolicyMessage, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
diff --git a/backend/api/v1/query_result_masker.go b/backend/api/v1/query_result_masker.go
index 7699c89c30..db8f829aff 100644
--- a/backend/api/v1/query_result_masker.go
+++ b/backend/api/v1/query_result_masker.go
@@ -182,7 +182,7 @@ func (s *QueryResultMasker) getMaskerForColumnResource(
// If we cannot find the maskingExceptionPolicy before, we need to find it from the database and record it in cache.
if _, ok := maskingExceptionPolicyMap[database.ProjectID]; !ok {
- policy, err := s.store.GetMaskingExceptionPolicyByProjectUID(ctx, project.UID)
+ policy, err := s.store.GetMaskingExceptionPolicyByProjectUID(ctx, project.ResourceID)
if err != nil {
return nil, errors.Wrapf(err, "failed to find masking exception policy for project %q", project.ResourceID)
}
diff --git a/backend/api/v1/review_config_service.go b/backend/api/v1/review_config_service.go
index ade37a4bf1..16fecba41b 100644
--- a/backend/api/v1/review_config_service.go
+++ b/backend/api/v1/review_config_service.go
@@ -208,36 +208,49 @@ func (s *ReviewConfigService) convertToV1ReviewConfig(ctx context.Context, revie
switch policy.ResourceType {
case api.PolicyResourceTypeEnvironment:
+ environmentID, err := common.GetEnvironmentID(policy.Resource)
+ if err != nil {
+ return nil, err
+ }
environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{
- UID: &policy.ResourceUID,
+ ResourceID: &environmentID,
ShowDeleted: false,
})
if err != nil {
- return nil, status.Errorf(codes.Internal, "failed to get environment %d with error: %v", policy.ResourceUID, err)
+ return nil, status.Errorf(codes.Internal, "failed to get environment %s with error: %v", environmentID, err)
}
if environment == nil {
continue
}
config.Resources = append(config.Resources, common.FormatEnvironment(environment.ResourceID))
case api.PolicyResourceTypeProject:
+ projectID, err := common.GetProjectID(policy.Resource)
+ if err != nil {
+ return nil, err
+ }
project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{
- UID: &policy.ResourceUID,
+ ResourceID: &projectID,
ShowDeleted: false,
})
if err != nil {
- return nil, status.Errorf(codes.Internal, "failed to get project %d with error: %v", policy.ResourceUID, err)
+ return nil, status.Errorf(codes.Internal, "failed to get project %s with error: %v", projectID, err)
}
if project == nil {
continue
}
config.Resources = append(config.Resources, common.FormatProject(project.ResourceID))
case api.PolicyResourceTypeDatabase:
+ instanceID, databaseName, err := common.GetInstanceDatabaseID(policy.Resource)
+ if err != nil {
+ return nil, err
+ }
database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
- UID: &policy.ResourceUID,
- ShowDeleted: false,
+ InstanceID: &instanceID,
+ DatabaseName: &databaseName,
+ ShowDeleted: false,
})
if err != nil {
- return nil, status.Errorf(codes.Internal, "failed to get database %d with error: %v", policy.ResourceUID, err)
+ return nil, status.Errorf(codes.Internal, "failed to get database %s with error: %v", policy.Resource, err)
}
if database == nil {
continue
diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.go
index d6432c11b0..837d5b5c40 100644
--- a/backend/api/v1/rollout_service.go
+++ b/backend/api/v1/rollout_service.go
@@ -1262,7 +1262,7 @@ func (s *RolloutService) canUserRunStageTasks(ctx context.Context, user *store.U
return false, err
}
- policy, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ policy, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return false, common.Wrapf(err, common.Internal, "failed to get project %d policy", project.UID)
}
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index d57b1f4f41..bfbdfbd50f 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1139,7 +1139,7 @@ func (s *SQLService) accessCheck(
return status.Errorf(codes.Internal, "failed to get workspace iam policy, error: %v", err)
}
// Allow query databases across different projects.
- projectPolicy, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ projectPolicy, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
@@ -1945,10 +1945,10 @@ func checkAndGetDataSourceQueriable(ctx context.Context, storeInstance *store.St
}
dataSourceQueryPolicyType := api.PolicyTypeDataSourceQuery
environmentResourceType := api.PolicyResourceTypeEnvironment
- projectResourceType := api.PolicyResourceTypeProject
+ environmentResource := common.FormatEnvironment(environment.ResourceID)
environmentPolicy, err := storeInstance.GetPolicyV2(ctx, &store.FindPolicyMessage{
ResourceType: &environmentResourceType,
- ResourceUID: &environment.UID,
+ Resource: &environmentResource,
Type: &dataSourceQueryPolicyType,
})
if err != nil {
@@ -1962,16 +1962,11 @@ func checkAndGetDataSourceQueriable(ctx context.Context, storeInstance *store.St
envAdminDataSourceRestriction = envPayload.DataSourceQueryPolicy.GetAdminDataSourceRestriction()
}
- project, err := storeInstance.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &database.ProjectID})
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get project")
- }
- if project == nil {
- return nil, errors.Errorf("project %q not found", database.ProjectID)
- }
+ projectResourceType := api.PolicyResourceTypeProject
+ projectResource := common.FormatProject(database.ProjectID)
projectPolicy, err := storeInstance.GetPolicyV2(ctx, &store.FindPolicyMessage{
ResourceType: &projectResourceType,
- ResourceUID: &project.UID,
+ Resource: &projectResource,
Type: &dataSourceQueryPolicyType,
})
if err != nil {
@@ -2017,10 +2012,11 @@ func checkDataSourceQueryPolicy(ctx context.Context, storeInstance *store.Store,
return status.Errorf(codes.NotFound, "environment %q not found", database.EffectiveEnvironmentID)
}
resourceType := api.PolicyResourceTypeEnvironment
+ environmentResource := common.FormatEnvironment(environment.ResourceID)
policyType := api.PolicyTypeDataSourceQuery
dataSourceQueryPolicy, err := storeInstance.GetPolicyV2(ctx, &store.FindPolicyMessage{
- ResourceUID: &environment.UID,
ResourceType: &resourceType,
+ Resource: &environmentResource,
Type: &policyType,
})
if err != nil {
diff --git a/backend/component/iam/manager.go b/backend/component/iam/manager.go
index db3f846ff3..b6df2ec9d4 100644
--- a/backend/component/iam/manager.go
+++ b/backend/component/iam/manager.go
@@ -79,7 +79,7 @@ func (m *Manager) CheckPermission(ctx context.Context, p Permission, user *store
if project == nil {
return false, errors.Errorf("project %q not found", projectID)
}
- policyMessage, err := m.store.GetProjectIamPolicy(ctx, project.UID)
+ policyMessage, err := m.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
return false, err
}
diff --git a/backend/component/webhook/manager.go b/backend/component/webhook/manager.go
index 8a0ed0f9bc..c7bcd9789d 100644
--- a/backend/component/webhook/manager.go
+++ b/backend/component/webhook/manager.go
@@ -202,7 +202,7 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
}
for _, projectRole := range u.RolloutPolicy.GetProjectRoles() {
role := api.Role(strings.TrimPrefix(projectRole, "roles/"))
- usersGetters = append(usersGetters, getUsersFromProjectRole(m.store, role, e.Project.UID))
+ usersGetters = append(usersGetters, getUsersFromProjectRole(m.store, role, e.Project.ResourceID))
}
for _, issueRole := range u.RolloutPolicy.GetIssueRoles() {
switch issueRole {
@@ -269,15 +269,15 @@ func (m *Manager) getWebhookContextFromEvent(ctx context.Context, e *Event, acti
case storepb.ApprovalNode_WORKSPACE_DBA:
usersGetter = m.getUsersFromWorkspaceRole(api.WorkspaceDBA)
case storepb.ApprovalNode_PROJECT_OWNER:
- usersGetter = getUsersFromProjectRole(m.store, api.ProjectOwner, e.Project.UID)
+ usersGetter = getUsersFromProjectRole(m.store, api.ProjectOwner, e.Project.ResourceID)
case storepb.ApprovalNode_PROJECT_MEMBER:
- usersGetter = getUsersFromProjectRole(m.store, api.ProjectDeveloper, e.Project.UID)
+ usersGetter = getUsersFromProjectRole(m.store, api.ProjectDeveloper, e.Project.ResourceID)
default:
return nil, errors.Errorf("invalid group value")
}
case *storepb.ApprovalNode_Role:
role := api.Role(strings.TrimPrefix(val.Role, "roles/"))
- usersGetter = getUsersFromProjectRole(m.store, role, e.Project.UID)
+ usersGetter = getUsersFromProjectRole(m.store, role, e.Project.ResourceID)
case *storepb.ApprovalNode_ExternalNodeId:
usersGetter = func(_ context.Context) ([]*store.UserMessage, error) {
return nil, nil
@@ -400,9 +400,9 @@ func (m *Manager) getUsersFromWorkspaceRole(role api.Role) func(context.Context)
}
}
-func getUsersFromProjectRole(s *store.Store, role api.Role, projectUID int) func(context.Context) ([]*store.UserMessage, error) {
+func getUsersFromProjectRole(s *store.Store, role api.Role, projectID string) func(context.Context) ([]*store.UserMessage, error) {
return func(ctx context.Context) ([]*store.UserMessage, error) {
- policyMessage, err := s.GetProjectIamPolicy(ctx, projectUID)
+ policyMessage, err := s.GetProjectIamPolicy(ctx, projectID)
if err != nil {
return nil, err
}
diff --git a/backend/metric/collector/policy_count.go b/backend/metric/collector/policy_count.go
index f1fb3aee8c..fb2ebd0904 100644
--- a/backend/metric/collector/policy_count.go
+++ b/backend/metric/collector/policy_count.go
@@ -3,6 +3,7 @@ package collector
import (
"context"
+ "github.com/bytebase/bytebase/backend/common"
api "github.com/bytebase/bytebase/backend/legacyapi"
metricapi "github.com/bytebase/bytebase/backend/metric"
"github.com/bytebase/bytebase/backend/plugin/metric"
@@ -40,7 +41,11 @@ func (c *policyCountCollector) Collect(ctx context.Context) ([]*metric.Metric, e
if policy.ResourceType != api.PolicyResourceTypeEnvironment {
continue
}
- environment, err := c.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{UID: &policy.ResourceUID})
+ environmentID, err := common.GetEnvironmentID(policy.Resource)
+ if err != nil {
+ return nil, err
+ }
+ environment, err := c.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &environmentID})
if err != nil {
continue
}
diff --git a/backend/migrator/migration/3.4/0009##policy_resource.sql b/backend/migrator/migration/3.4/0009##policy_resource.sql
new file mode 100644
index 0000000000..7a15306c75
--- /dev/null
+++ b/backend/migrator/migration/3.4/0009##policy_resource.sql
@@ -0,0 +1,11 @@
+DROP INDEX IF EXISTS idx_policy_unique_resource_type_resource_id_type;
+ALTER TABLE policy ADD COLUMN IF NOT EXISTS resource TEXT;
+-- DML.
+UPDATE policy SET resource = '' WHERE resource_type = 'WORKSPACE';
+UPDATE policy SET resource = 'projectss/' || project.resource_id FROM project WHERE resource_type = 'PROJECT' AND project.id = policy.resource_id;
+UPDATE policy SET resource = 'environments/' || environment.resource_id FROM environment WHERE resource_type = 'ENVIRONMENT' AND environment.id = policy.resource_id;
+UPDATE policy SET resource = 'instances/' || instance.resource_id FROM instance WHERE resource_type = 'INSTANCE' AND instance.id = policy.resource_id;
+UPDATE policy SET resource = 'instances/' || db.instance || '/databases/' || db.name FROM db WHERE resource_type = 'DATABASE' AND db.id = policy.resource_id;
+ALTER TABLE policy DROP COLUMN IF EXISTS resource_id;
+ALTER TABLE policy ALTER COLUMN resource SET NOT NULL;
+CREATE UNIQUE INDEX idx_policy_unique_resource_type_resource_type ON policy(resource_type, resource, type);
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 49b0a3c9e4..83005a8958 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -70,8 +70,7 @@ CREATE UNIQUE INDEX idx_environment_unique_resource_id ON environment(resource_i
ALTER SEQUENCE environment_id_seq RESTART WITH 101;
-- Policy
--- policy stores the policies for each environment.
--- Policies are associated with environments. Since we may have policies not associated with environment later, we name the table policy.
+-- policy stores the policies for each resources.
CREATE TYPE resource_type AS ENUM ('WORKSPACE', 'ENVIRONMENT', 'PROJECT', 'INSTANCE', 'DATABASE');
CREATE TABLE policy (
@@ -81,11 +80,11 @@ CREATE TABLE policy (
type text NOT NULL CHECK (type LIKE 'bb.policy.%'),
payload jsonb NOT NULL DEFAULT '{}',
resource_type resource_type NOT NULL,
- resource_id integer NOT NULL,
+ resource TEXT NOT NULL,
inherit_from_parent boolean NOT NULL DEFAULT TRUE
);
-CREATE UNIQUE INDEX idx_policy_unique_resource_type_resource_id_type ON policy(resource_type, resource_id, type);
+CREATE UNIQUE INDEX idx_policy_unique_resource_type_resource_type ON policy(resource_type, resource, type);
ALTER SEQUENCE policy_id_seq RESTART WITH 101;
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 1802d91cdc..b161dc85e6 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -212,5 +212,5 @@ func TestMigrationCompatibility(t *testing.T) {
func TestGetCutoffVersion(t *testing.T) {
releaseVersion, err := getProdCutoffVersion()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.4.8"), releaseVersion)
+ require.Equal(t, semver.MustParse("3.4.9"), releaseVersion)
}
diff --git a/backend/runner/mail/slow_query_weekly_mail.go b/backend/runner/mail/slow_query_weekly_mail.go
index 7c57f3d7d1..6194310175 100644
--- a/backend/runner/mail/slow_query_weekly_mail.go
+++ b/backend/runner/mail/slow_query_weekly_mail.go
@@ -180,7 +180,7 @@ func (s *SlowQueryWeeklyMailSender) sendEmail(ctx context.Context, now time.Time
continue
}
- policyMessage, err := s.store.GetProjectIamPolicy(ctx, project.UID)
+ policyMessage, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)
if err != nil {
slog.Error("Failed to get project policy", log.BBError(err))
continue
@@ -281,7 +281,11 @@ func (s *SlowQueryWeeklyMailSender) generateWeeklyEmailForProject(ctx context.Co
instanceMap := make(map[string]*store.InstanceMessage)
for _, policy := range policies {
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &policy.ResourceUID})
+ instanceID, err := common.GetInstanceID(policy.Resource)
+ if err != nil {
+ return "", err
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
if err != nil {
slog.Warn("Failed to get instance", log.BBError(err))
continue
@@ -515,7 +519,11 @@ func (s *SlowQueryWeeklyMailSender) generateWeeklyEmailForDBA(ctx context.Contex
instanceMap := make(map[string][]*store.InstanceMessage)
for _, policy := range policies {
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &policy.ResourceUID})
+ instanceID, err := common.GetInstanceID(policy.Resource)
+ if err != nil {
+ return "", err
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})
if err != nil {
slog.Warn("Failed to get instance", log.BBError(err))
continue
diff --git a/backend/runner/slowquerysync/syncer.go b/backend/runner/slowquerysync/syncer.go
index e08c5672ea..b4dc8f7cae 100644
--- a/backend/runner/slowquerysync/syncer.go
+++ b/backend/runner/slowquerysync/syncer.go
@@ -108,7 +108,7 @@ func (s *Syncer) syncSlowQuery(ctx context.Context, message *state.InstanceSlowQ
}
func (s *Syncer) syncInstanceSlowQuery(ctx context.Context, instance *store.InstanceMessage) error {
- slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, api.PolicyResourceTypeInstance, instance.UID)
+ slowQueryPolicy, err := s.store.GetSlowQueryPolicy(ctx, instance.ResourceID)
if err != nil {
return err
}
diff --git a/backend/server/onboard.go b/backend/server/onboard.go
index c3ea0ad6db..d25a668558 100644
--- a/backend/server/onboard.go
+++ b/backend/server/onboard.go
@@ -177,7 +177,7 @@ func (s *Server) generateOnboardingData(ctx context.Context, user *store.UserMes
}
_, err = s.store.CreatePolicyV2(ctx, &store.PolicyMessage{
- ResourceUID: api.DefaultProdEnvironmentUID,
+ Resource: common.FormatEnvironment(api.DefaultProdEnvironmentID),
ResourceType: api.PolicyResourceTypeEnvironment,
Payload: string(policyPayload),
Type: api.PolicyTypeTag,
diff --git a/backend/store/environment.go b/backend/store/environment.go
index 509beba501..89eb30e589 100644
--- a/backend/store/environment.go
+++ b/backend/store/environment.go
@@ -151,7 +151,7 @@ func (s *Store) CreateEnvironmentV2(ctx context.Context, create *EnvironmentMess
}
if _, err := upsertPolicyV2Impl(ctx, tx, &PolicyMessage{
ResourceType: api.PolicyResourceTypeEnvironment,
- ResourceUID: uid,
+ Resource: common.FormatEnvironment(create.ResourceID),
Type: api.PolicyTypeEnvironmentTier,
InheritFromParent: true,
Payload: string(payload),
@@ -220,11 +220,12 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, patch *UpdateEnvironmen
// TODO(d): consider moving tier to environment table to simplify things.
if patch.Protected != nil || patch.Color != nil {
resourceType := api.PolicyResourceTypeEnvironment
+ resource := common.FormatEnvironment(patch.ResourceID)
policyType := api.PolicyTypeEnvironmentTier
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
Type: &policyType,
- ResourceUID: &patch.UID,
+ Resource: &resource,
})
if err != nil {
return nil, err
@@ -253,7 +254,7 @@ func (s *Store) UpdateEnvironmentV2(ctx context.Context, patch *UpdateEnvironmen
}
if _, err := upsertPolicyV2Impl(ctx, tx, &PolicyMessage{
ResourceType: resourceType,
- ResourceUID: patch.UID,
+ Resource: resource,
Type: policyType,
InheritFromParent: true,
Payload: string(payload),
@@ -311,7 +312,7 @@ func listEnvironmentImplV2(ctx context.Context, tx *Tx, find *FindEnvironmentMes
environment.row_status,
policy.payload
FROM environment
- LEFT JOIN policy ON environment.id = policy.resource_id AND policy.resource_type = 'ENVIRONMENT' AND policy.type = 'bb.policy.environment-tier'
+ LEFT JOIN policy ON environment.resource_id = policy.resource AND policy.resource_type = 'ENVIRONMENT' AND policy.type = 'bb.policy.environment-tier'
WHERE %s
ORDER BY environment.order ASC`, strings.Join(where, " AND ")),
args...,
diff --git a/backend/store/policy.go b/backend/store/policy.go
index bbc5523c11..1a1ecf179e 100644
--- a/backend/store/policy.go
+++ b/backend/store/policy.go
@@ -95,11 +95,12 @@ func (s *Store) PatchWorkspaceIamPolicy(ctx context.Context, patch *PatchIamPoli
return s.GetWorkspaceIamPolicy(ctx)
}
-func (s *Store) GetProjectIamPolicy(ctx context.Context, projectUID int) (*IamPolicyMessage, error) {
+func (s *Store) GetProjectIamPolicy(ctx context.Context, projectID string) (*IamPolicyMessage, error) {
resourceType := api.PolicyResourceTypeProject
+ resource := common.FormatProject(projectID)
return s.getIamPolicy(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &projectUID,
+ Resource: &resource,
})
}
@@ -128,15 +129,12 @@ func (s *Store) getIamPolicy(ctx context.Context, find *FindPolicyMessage) (*Iam
}
func (s *Store) GetRolloutPolicy(ctx context.Context, environment string) (*storepb.RolloutPolicy, error) {
- e, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{ResourceID: &environment})
- if err != nil {
- return nil, err
- }
+ resource := common.FormatEnvironment(environment)
resourceType := api.PolicyResourceTypeEnvironment
pType := api.PolicyTypeRollout
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &e.UID,
+ Resource: &resource,
Type: &pType,
})
if err != nil {
@@ -158,9 +156,11 @@ func (s *Store) GetRolloutPolicy(ctx context.Context, environment string) (*stor
func (s *Store) GetDataExportPolicy(ctx context.Context) (*storepb.ExportDataPolicy, error) {
resourceType := api.PolicyResourceTypeWorkspace
+ resource := ""
pType := api.PolicyTypeExportData
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
+ Resource: &resource,
Type: &pType,
})
if err != nil {
@@ -182,27 +182,30 @@ func (s *Store) GetDataExportPolicy(ctx context.Context) (*storepb.ExportDataPol
// GetReviewConfigForDatabase will get the review config for a database.
func (s *Store) GetReviewConfigForDatabase(ctx context.Context, database *DatabaseMessage) (*storepb.ReviewConfigPayload, error) {
- resources := []DatabaseReviewConfig{
- &databaseReviewConfigResource{},
- &databaseProjectReviewConfigResource{},
- &databaseEnvironmentReviewConfigResource{},
- }
-
- for _, resource := range resources {
- resourceType := resource.GetResourceType()
- resourceUID, err := resource.GetResourceUID(ctx, s, database)
- if err != nil {
- slog.Debug("failed to resource id", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
- continue
- }
-
- reviewConfig, err := s.getReviewConfigByResource(ctx, resourceType, resourceUID)
+ for _, v := range []struct {
+ resourceType api.PolicyResourceType
+ resource string
+ }{
+ {
+ resourceType: api.PolicyResourceTypeEnvironment,
+ resource: common.FormatEnvironment(database.EffectiveEnvironmentID),
+ },
+ {
+ resourceType: api.PolicyResourceTypeProject,
+ resource: common.FormatProject(database.ProjectID),
+ },
+ {
+ resourceType: api.PolicyResourceTypeDatabase,
+ resource: common.FormatDatabase(database.InstanceID, database.DatabaseName),
+ },
+ } {
+ reviewConfig, err := s.getReviewConfigByResource(ctx, v.resourceType, v.resource)
if err != nil {
- slog.Debug("failed to get review config", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
+ slog.Debug("failed to get review config", slog.String("resource_type", string(v.resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
continue
}
if reviewConfig == nil {
- slog.Debug("review config is empty", slog.String("resource_type", string(resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
+ slog.Debug("review config is empty", slog.String("resource_type", string(v.resourceType)), slog.String("database", database.DatabaseName), log.BBError(err))
continue
}
return reviewConfig, nil
@@ -211,22 +214,22 @@ func (s *Store) GetReviewConfigForDatabase(ctx context.Context, database *Databa
return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy for database %s not found", database.DatabaseName)}
}
-func (s *Store) getReviewConfigByResource(ctx context.Context, resourceType api.PolicyResourceType, resourceUID int) (*storepb.ReviewConfigPayload, error) {
+func (s *Store) getReviewConfigByResource(ctx context.Context, resourceType api.PolicyResourceType, resource string) (*storepb.ReviewConfigPayload, error) {
pType := api.PolicyTypeTag
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &resourceUID,
+ Resource: &resource,
Type: &pType,
})
if err != nil {
return nil, err
}
if policy == nil {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy for resource %v/%d not found", resourceType, resourceUID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy for resource %v/%s not found", resourceType, resource)}
}
if !policy.Enforce {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy is not enforced for resource %v/%d", resourceType, resourceUID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("tag policy is not enforced for resource %v/%s", resourceType, resource)}
}
payload := &storepb.TagPolicy{}
@@ -236,7 +239,7 @@ func (s *Store) getReviewConfigByResource(ctx context.Context, resourceType api.
reviewConfigName, ok := payload.Tags[string(api.ReservedTagReviewConfig)]
if !ok {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config tag for resource %v/%d not found", resourceType, resourceUID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config tag for resource %v/%s not found", resourceType, resource)}
}
reviewConfigID, err := common.GetReviewConfigID(reviewConfigName)
if err != nil {
@@ -248,21 +251,23 @@ func (s *Store) getReviewConfigByResource(ctx context.Context, resourceType api.
return nil, err
}
if reviewConfig == nil {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config for resource %v/%d not found", resourceType, resourceUID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config for resource %v/%s not found", resourceType, resource)}
}
if !reviewConfig.Enforce {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config is not enforced for resource %v/%d", resourceType, resourceUID)}
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("review config is not enforced for resource %v/%s", resourceType, resource)}
}
return reviewConfig.Payload, nil
}
// GetSlowQueryPolicy will get the slow query policy for instance ID.
-func (s *Store) GetSlowQueryPolicy(ctx context.Context, resourceType api.PolicyResourceType, resourceID int) (*storepb.SlowQueryPolicy, error) {
+func (s *Store) GetSlowQueryPolicy(ctx context.Context, instanceID string) (*storepb.SlowQueryPolicy, error) {
+ resourceType := api.PolicyResourceTypeInstance
+ resource := common.FormatInstance(instanceID)
pType := api.PolicyTypeSlowQuery
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &resourceID,
+ Resource: &resource,
Type: &pType,
})
if err != nil {
@@ -304,12 +309,13 @@ func (s *Store) GetMaskingRulePolicy(ctx context.Context) (*storepb.MaskingRuleP
}
// GetMaskingExceptionPolicyByProjectUID gets the masking exception policy for a project.
-func (s *Store) GetMaskingExceptionPolicyByProjectUID(ctx context.Context, projectUID int) (*storepb.MaskingExceptionPolicy, error) {
+func (s *Store) GetMaskingExceptionPolicyByProjectUID(ctx context.Context, projectID string) (*storepb.MaskingExceptionPolicy, error) {
resourceType := api.PolicyResourceTypeProject
+ resource := common.FormatProject(projectID)
pType := api.PolicyTypeMaskingException
policy, err := s.GetPolicyV2(ctx, &FindPolicyMessage{
ResourceType: &resourceType,
- ResourceUID: &projectUID,
+ Resource: &resource,
Type: &pType,
})
if err != nil {
@@ -330,7 +336,7 @@ func (s *Store) GetMaskingExceptionPolicyByProjectUID(ctx context.Context, proje
// PolicyMessage is the mssage for policy.
type PolicyMessage struct {
- ResourceUID int
+ Resource string
ResourceType api.PolicyResourceType
Payload string
InheritFromParent bool
@@ -345,7 +351,7 @@ type PolicyMessage struct {
// FindPolicyMessage is the message for finding policies.
type FindPolicyMessage struct {
ResourceType *api.PolicyResourceType
- ResourceUID *int
+ Resource *string
Type *api.PolicyType
ShowDeleted bool
}
@@ -353,7 +359,7 @@ type FindPolicyMessage struct {
// UpdatePolicyMessage is the message for updating a policy.
type UpdatePolicyMessage struct {
ResourceType api.PolicyResourceType
- ResourceUID int
+ Resource string
Type api.PolicyType
InheritFromParent *bool
Payload *string
@@ -362,8 +368,8 @@ type UpdatePolicyMessage struct {
// GetPolicyV2 gets a policy.
func (s *Store) GetPolicyV2(ctx context.Context, find *FindPolicyMessage) (*PolicyMessage, error) {
- if find.ResourceType != nil && find.ResourceUID != nil && find.Type != nil {
- if v, ok := s.policyCache.Get(getPolicyCacheKey(*find.ResourceType, *find.ResourceUID, *find.Type)); ok {
+ if find.ResourceType != nil && find.Resource != nil && find.Type != nil {
+ if v, ok := s.policyCache.Get(getPolicyCacheKey(*find.ResourceType, *find.Resource, *find.Type)); ok {
return v, nil
}
}
@@ -382,8 +388,8 @@ func (s *Store) GetPolicyV2(ctx context.Context, find *FindPolicyMessage) (*Poli
}
if len(policies) == 0 {
// Cache the policy for not found as well to reduce the look up latency.
- if find.ResourceType != nil && find.ResourceUID != nil && find.Type != nil {
- s.policyCache.Add(getPolicyCacheKey(*find.ResourceType, *find.ResourceUID, *find.Type), nil)
+ if find.ResourceType != nil && find.Resource != nil && find.Type != nil {
+ s.policyCache.Add(getPolicyCacheKey(*find.ResourceType, *find.Resource, *find.Type), nil)
}
return nil, nil
}
@@ -396,7 +402,7 @@ func (s *Store) GetPolicyV2(ctx context.Context, find *FindPolicyMessage) (*Poli
return nil, err
}
- s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.ResourceUID, policy.Type), policy)
+ s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.Resource, policy.Type), policy)
return policy, nil
}
@@ -419,7 +425,7 @@ func (s *Store) ListPoliciesV2(ctx context.Context, find *FindPolicyMessage) ([]
}
for _, policy := range policies {
- s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.ResourceUID, policy.Type), policy)
+ s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.Resource, policy.Type), policy)
}
return policies, nil
@@ -442,7 +448,7 @@ func (s *Store) CreatePolicyV2(ctx context.Context, create *PolicyMessage) (*Pol
return nil, err
}
- s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.ResourceUID, policy.Type), policy)
+ s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.Resource, policy.Type), policy)
return policy, nil
}
@@ -463,7 +469,7 @@ func (s *Store) UpdatePolicyV2(ctx context.Context, patch *UpdatePolicyMessage)
}
set, args = append(set, fmt.Sprintf(`"row_status" = $%d`, len(args)+1)), append(args, rowStatus)
}
- args = append(args, patch.ResourceType, patch.ResourceUID, patch.Type)
+ args = append(args, patch.ResourceType, patch.Resource, patch.Type)
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
@@ -472,7 +478,7 @@ func (s *Store) UpdatePolicyV2(ctx context.Context, patch *UpdatePolicyMessage)
defer tx.Rollback()
policy := &PolicyMessage{
- ResourceUID: patch.ResourceUID,
+ Resource: patch.Resource,
ResourceType: patch.ResourceType,
Type: patch.Type,
}
@@ -481,7 +487,7 @@ func (s *Store) UpdatePolicyV2(ctx context.Context, patch *UpdatePolicyMessage)
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
UPDATE policy
SET `+strings.Join(set, ", ")+`
- WHERE resource_type = $%d AND resource_id = $%d AND type =$%d
+ WHERE resource_type = $%d AND resource = $%d AND type =$%d
RETURNING
payload,
inherit_from_parent,
@@ -508,7 +514,7 @@ func (s *Store) UpdatePolicyV2(ctx context.Context, patch *UpdatePolicyMessage)
return nil, err
}
- s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.ResourceUID, policy.Type), policy)
+ s.policyCache.Add(getPolicyCacheKey(policy.ResourceType, policy.Resource, policy.Type), policy)
return policy, nil
}
@@ -522,9 +528,9 @@ func (s *Store) DeletePolicyV2(ctx context.Context, policy *PolicyMessage) error
defer tx.Rollback()
if _, err := tx.ExecContext(ctx,
- `DELETE FROM policy WHERE resource_type = $1 AND resource_id = $2 AND type = $3`,
+ `DELETE FROM policy WHERE resource_type = $1 AND resource = $2 AND type = $3`,
policy.ResourceType,
- policy.ResourceUID,
+ policy.Resource,
policy.Type,
); err != nil {
return err
@@ -534,7 +540,7 @@ func (s *Store) DeletePolicyV2(ctx context.Context, policy *PolicyMessage) error
return err
}
- s.policyCache.Remove(getPolicyCacheKey(policy.ResourceType, policy.ResourceUID, policy.Type))
+ s.policyCache.Remove(getPolicyCacheKey(policy.ResourceType, policy.Resource, policy.Type))
return nil
}
@@ -548,14 +554,14 @@ func upsertPolicyV2Impl(ctx context.Context, tx *Tx, create *PolicyMessage) (*Po
if err := tx.QueryRowContext(ctx, `
INSERT INTO policy (
resource_type,
- resource_id,
+ resource,
inherit_from_parent,
type,
payload,
row_status
)
VALUES ($1, $2, $3, $4, $5, $6)
- ON CONFLICT(resource_type, resource_id, type) DO UPDATE SET
+ ON CONFLICT(resource_type, resource, type) DO UPDATE SET
inherit_from_parent = EXCLUDED.inherit_from_parent,
payload = EXCLUDED.payload,
row_status = EXCLUDED.row_status
@@ -564,7 +570,7 @@ func upsertPolicyV2Impl(ctx context.Context, tx *Tx, create *PolicyMessage) (*Po
updated_at
`,
create.ResourceType,
- create.ResourceUID,
+ create.Resource,
create.InheritFromParent,
create.Type,
create.Payload,
@@ -584,8 +590,8 @@ func (*Store) listPolicyImplV2(ctx context.Context, tx *Tx, find *FindPolicyMess
if v := find.ResourceType; v != nil {
where, args = append(where, fmt.Sprintf("resource_type = $%d", len(args)+1)), append(args, *v)
}
- if v := find.ResourceUID; v != nil {
- where, args = append(where, fmt.Sprintf("resource_id = $%d", len(args)+1)), append(args, *v)
+ if v := find.Resource; v != nil {
+ where, args = append(where, fmt.Sprintf("resource = $%d", len(args)+1)), append(args, *v)
}
if v := find.Type; v != nil {
where, args = append(where, fmt.Sprintf("type = $%d", len(args)+1)), append(args, *v)
@@ -599,7 +605,7 @@ func (*Store) listPolicyImplV2(ctx context.Context, tx *Tx, find *FindPolicyMess
id,
updated_at,
resource_type,
- resource_id,
+ resource,
inherit_from_parent,
type,
payload,
@@ -622,7 +628,7 @@ func (*Store) listPolicyImplV2(ctx context.Context, tx *Tx, find *FindPolicyMess
&policyMessage.UID,
&policyMessage.UpdatedAt,
&policyMessage.ResourceType,
- &policyMessage.ResourceUID,
+ &policyMessage.Resource,
&policyMessage.InheritFromParent,
&policyMessage.Type,
&policyMessage.Payload,
diff --git a/backend/store/project.go b/backend/store/project.go
index c84ae15c96..a29c220abb 100644
--- a/backend/store/project.go
+++ b/backend/store/project.go
@@ -181,8 +181,8 @@ func (s *Store) CreateProjectV2(ctx context.Context, create *ProjectMessage, cre
return nil, err
}
if _, err := s.CreatePolicyV2(ctx, &PolicyMessage{
- ResourceUID: project.UID,
ResourceType: api.PolicyResourceTypeProject,
+ Resource: common.FormatProject(project.ResourceID),
Payload: string(policyPayload),
Type: api.PolicyTypeIAM,
InheritFromParent: false,
diff --git a/backend/store/sql_review.go b/backend/store/sql_review.go
deleted file mode 100644
index f9dee80b85..0000000000
--- a/backend/store/sql_review.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package store
-
-import (
- "context"
-
- "github.com/pkg/errors"
-
- api "github.com/bytebase/bytebase/backend/legacyapi"
-)
-
-type DatabaseReviewConfig interface {
- GetResourceType() api.PolicyResourceType
- GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error)
-}
-
-type databaseEnvironmentReviewConfigResource struct{}
-
-func (*databaseEnvironmentReviewConfigResource) GetResourceType() api.PolicyResourceType {
- return api.PolicyResourceTypeEnvironment
-}
-
-func (*databaseEnvironmentReviewConfigResource) GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error) {
- environment, err := store.GetEnvironmentV2(ctx, &FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})
- if err != nil {
- return 0, err
- }
- if environment == nil {
- return 0, errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)
- }
-
- return environment.UID, nil
-}
-
-type databaseProjectReviewConfigResource struct{}
-
-func (*databaseProjectReviewConfigResource) GetResourceType() api.PolicyResourceType {
- return api.PolicyResourceTypeProject
-}
-
-func (*databaseProjectReviewConfigResource) GetResourceUID(ctx context.Context, store *Store, database *DatabaseMessage) (int, error) {
- project, err := store.GetProjectV2(ctx, &FindProjectMessage{ResourceID: &database.ProjectID})
- if err != nil {
- return 0, err
- }
- if project == nil {
- return 0, errors.Errorf("project %q not found", database.ProjectID)
- }
-
- return project.UID, nil
-}
-
-type databaseReviewConfigResource struct{}
-
-func (*databaseReviewConfigResource) GetResourceType() api.PolicyResourceType {
- return api.PolicyResourceTypeDatabase
-}
-
-func (*databaseReviewConfigResource) GetResourceUID(_ context.Context, _ *Store, database *DatabaseMessage) (int, error) {
- return database.UID, nil
-}
diff --git a/backend/store/store.go b/backend/store/store.go
index 794651bb8e..ba1262b3fa 100644
--- a/backend/store/store.go
+++ b/backend/store/store.go
@@ -198,8 +198,8 @@ func getInstanceCacheKey(instanceID string) string {
return instanceID
}
-func getPolicyCacheKey(resourceType api.PolicyResourceType, resourceUID int, policyType api.PolicyType) string {
- return fmt.Sprintf("policies/%s/%d/%s", resourceType, resourceUID, policyType)
+func getPolicyCacheKey(resourceType api.PolicyResourceType, resource string, policyType api.PolicyType) string {
+ return fmt.Sprintf("policies/%s/%s/%s", resourceType, resource, policyType)
}
func getDatabaseCacheKey(instanceID, databaseName string) string {
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 8095389845..1d00d30012 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -370,7 +370,7 @@ func handleApprovalNodeExternalNode(ctx context.Context, s *store.Store, relayCl
// UpdateProjectPolicyFromGrantIssue updates the project policy from grant issue.
func UpdateProjectPolicyFromGrantIssue(ctx context.Context, stores *store.Store, issue *store.IssueMessage, grantRequest *storepb.GrantRequest) error {
- policyMessage, err := stores.GetProjectIamPolicy(ctx, issue.Project.UID)
+ policyMessage, err := stores.GetProjectIamPolicy(ctx, issue.Project.ResourceID)
if err != nil {
return errors.Wrapf(err, "failed to get project policy for project %q", issue.Project.UID)
}
@@ -426,7 +426,7 @@ func UpdateProjectPolicyFromGrantIssue(ctx context.Context, stores *store.Store,
return err
}
if _, err := stores.CreatePolicyV2(ctx, &store.PolicyMessage{
- ResourceUID: issue.Project.UID,
+ Resource: common.FormatProject(issue.Project.ResourceID),
ResourceType: api.PolicyResourceTypeProject,
Payload: string(policyPayload),
Type: api.PolicyTypeIAM,