Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: get resource (#12940)
Danny Xue23379926175
diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.goindex 0810ea883c..4aa5980307 100644--- a/backend/api/v1/acl.go+++ b/backend/api/v1/acl.go@@ -3,6 +3,7 @@ package v1import ("context""log/slog"+ "regexp""strings"annotationsproto "google.golang.org/genproto/googleapis/api/annotations"@@ -43,7 +44,18 @@ func NewACLInterceptor(store *store.Store, secret string, iamManager *iam.Manage}// ACLInterceptor is the unary interceptor for gRPC API.-func (in *ACLInterceptor) ACLInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {+func (in *ACLInterceptor) ACLInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) {+ defer func() {+ if r := recover(); r != nil {+ perr, ok := r.(error)+ if !ok {+ perr = errors.Errorf("%v", r)+ }+ err = errors.Errorf("iam check PANIC RECOVER, method: %v, err: %v", serverInfo.FullMethod, perr)++ slog.Error("iam check PANIC RECOVER", log.BBError(perr), log.BBStack("panic-stack"))+ }+ }()user, err := in.getUser(ctx)if err != nil {return nil, status.Errorf(codes.PermissionDenied, err.Error())@@ -74,15 +86,31 @@ func (in *ACLInterceptor) ACLInterceptor(ctx context.Context, request any, servereturn nil, status.Errorf(codes.Unauthenticated, "unauthenticated for method %q", serverInfo.FullMethod)}- if err := in.checkIAMPermission(ctx, serverInfo.FullMethod, request, user, authContext); err != nil {- return nil, err+ ok, extra, err := in.doIAMPermissionCheck(ctx, serverInfo.FullMethod, request, user, authContext)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to check permission for method %q, extra %v, err: %v", serverInfo.FullMethod, extra, err)+ }+ if !ok {+ return nil, status.Errorf(codes.PermissionDenied, "permission denied for method %q, user does not have permission %q, extra %v", serverInfo.FullMethod, authContext.Permission, extra)}return handler(ctx, request)}// ACLStreamInterceptor is the unary interceptor for gRPC API.-func (in *ACLInterceptor) ACLStreamInterceptor(request any, ss grpc.ServerStream, serverInfo *grpc.StreamServerInfo, handler grpc.StreamHandler) error {+func (in *ACLInterceptor) ACLStreamInterceptor(request any, ss grpc.ServerStream, serverInfo *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {+ defer func() {+ if r := recover(); r != nil {+ perr, ok := r.(error)+ if !ok {+ perr = errors.Errorf("%v", r)+ }+ err = errors.Errorf("iam check PANIC RECOVER, method: %v, err: %v", serverInfo.FullMethod, perr)++ slog.Error("iam check PANIC RECOVER", log.BBError(perr), log.BBStack("panic-stack"))+ }+ }()+ctx := ss.Context()user, err := in.getUser(ctx)@@ -116,8 +144,12 @@ func (in *ACLInterceptor) ACLStreamInterceptor(request any, ss grpc.ServerStreamreturn status.Errorf(codes.Unauthenticated, "unauthenticated for method %q", serverInfo.FullMethod)}- if err := in.checkIAMPermission(ctx, serverInfo.FullMethod, request, user, authContext); err != nil {- return err+ ok, extra, err := in.doIAMPermissionCheck(ctx, serverInfo.FullMethod, request, user, authContext)+ if err != nil {+ return status.Errorf(codes.Internal, "failed to check permission for method %q, extra %v, err: %v", serverInfo.FullMethod, extra, err)+ }+ if !ok {+ return status.Errorf(codes.PermissionDenied, "permission denied for method %q, user does not have permission %q, extra %v", serverInfo.FullMethod, authContext.Permission, extra)}return handler(request, ss)@@ -167,29 +199,6 @@ func hasPath(fieldMask *fieldmaskpb.FieldMask, want string) bool {return false}-func (in *ACLInterceptor) checkIAMPermission(ctx context.Context, fullMethod string, req any, user *store.UserMessage, authContext *common.AuthContext) (err error) {- defer func() {- if r := recover(); r != nil {- perr, ok := r.(error)- if !ok {- perr = errors.Errorf("%v", r)- }- err = errors.Errorf("iam check PANIC RECOVER, method: %v, err: %v", fullMethod, perr)-- slog.Error("iam check PANIC RECOVER", log.BBError(perr), log.BBStack("panic-stack"))- }- }()- ok, extra, err := in.doIAMPermissionCheck(ctx, fullMethod, req, user, authContext)- if err != nil {- return status.Errorf(codes.Internal, "failed to check permission for method %q, extra %v, err: %v", fullMethod, extra, err)- }- if !ok {- return status.Errorf(codes.PermissionDenied, "permission denied for method %q, user does not have permission %q, extra %v", fullMethod, authContext.Permission, extra)- }-- return nil-}-func (in *ACLInterceptor) doIAMPermissionCheck(ctx context.Context, fullMethod string, req any, user *store.UserMessage, authContext *common.AuthContext) (bool, []string, error) {if auth.IsAuthenticationAllowed(fullMethod, authContext) {return true, nil, nil@@ -253,67 +262,84 @@ func (in *ACLInterceptor) checkIAMPermissionInstancesGet(ctx context.Context, us}func (*ACLInterceptor) populateRawResources(authContext *common.AuthContext, request any, method string) error {- name := getResourceFromRequest(request, method)- if name != "" {- authContext.Resources = append(authContext.Resources, &common.Resource{- Name: name,- })+ resource := getResourceFromRequest(request, method)+ if resource != nil {+ authContext.Resources = append(authContext.Resources, resource)}return nil}-func getResourceFromRequest(request any, method string) string {- var resource string+func getResourceFromRequest(request any, method string) *common.Resource {pm, ok := request.(proto.Message)if !ok {- return ""+ return nil}mr := pm.ProtoReflect()parentDesc := mr.Descriptor().Fields().ByName("parent")if parentDesc != nil && proto.HasExtension(parentDesc.Options(), annotationsproto.E_ResourceReference) {v := mr.Get(parentDesc)- return v.String()+ return &common.Resource{Name: v.String()}}nameDesc := mr.Descriptor().Fields().ByName("name")if nameDesc != nil && proto.HasExtension(nameDesc.Options(), annotationsproto.E_ResourceReference) {v := mr.Get(nameDesc)- return v.String()+ return &common.Resource{Name: v.String()}}// This is primarily used by Get/SetIAMPolicy().- resourceDesc := mr.Descriptor().Fields().ByName("resource")- if resourceDesc != nil && proto.HasExtension(resourceDesc.Options(), annotationsproto.E_ResourceReference) {- v := mr.Get(resourceDesc)- return v.String()+ resourceFieldDesc := mr.Descriptor().Fields().ByName("resource")+ if resourceFieldDesc != nil && proto.HasExtension(resourceFieldDesc.Options(), annotationsproto.E_ResourceReference) {+ v := mr.Get(resourceFieldDesc)+ return &common.Resource{Name: v.String()}}+methodTokens := strings.Split(method, "/")if len(methodTokens) != 3 {- return ""+ return nil}- if strings.HasPrefix(methodTokens[2], "Create") {- return ""++ // Listing top-level resources.+ if strings.HasPrefix(methodTokens[2], "List") {+ return &common.Resource{Workspace: true}}- mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {- if fd.Name() == "name" {- resource = v.String()- return false+ isCreate := strings.HasPrefix(methodTokens[2], "Create")+ isUpdate := strings.HasPrefix(methodTokens[2], "Update")+ if !isCreate && !isUpdate {+ return nil+ }+ var resourceName string+ if isCreate {+ resourceName = strings.TrimPrefix(methodTokens[2], "Create")+ }+ if isUpdate {+ resourceName = strings.TrimPrefix(methodTokens[2], "Update")+ }+ resourceName = toSnakeCase(resourceName)+ resourceDesc := mr.Descriptor().Fields().ByName(protoreflect.Name(resourceName))+ if resourceDesc == nil {+ return nil+ }+ if proto.HasExtension(resourceDesc.Message().Options(), annotationsproto.E_Resource) {+ // Parent-less resource. Return workspace resource for Create() method.+ if isCreate {+ return &common.Resource{Workspace: true}}- fdm := fd.Message()- if fdm == nil {- return true- }- if !proto.HasExtension(fdm.Options(), annotationsproto.E_Resource) {- return true+ resourceValue := mr.Get(resourceDesc)+ resourceNameDesc := resourceDesc.Message().Fields().ByName("name")+ if resourceNameDesc != nil {+ v := resourceValue.Message().Get(resourceNameDesc)+ return &common.Resource{Name: v.String()}}+ }+ return nil+}- nameDesc := fdm.Fields().ByName("name")- if nameDesc != nil {- rn := v.Message().Get(nameDesc)- resource = rn.String()- return false- }- return false- })- return resource+var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")+var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")++func toSnakeCase(str string) string {+ snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")+ snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")+ return strings.ToLower(snake)}diff --git a/backend/api/v1/acl_test.go b/backend/api/v1/acl_test.goindex 3d2a477683..e4674942c1 100644--- a/backend/api/v1/acl_test.go+++ b/backend/api/v1/acl_test.go@@ -5,6 +5,7 @@ import ("github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -12,20 +13,21 @@ func TestGetResourceFromRequest(t *testing.T) {tests := []struct {request anymethod string- want string+ want *common.Resource}{{request: &v1pb.LoginRequest{Email: "[email protected]"},method: "/bytebase.v1.AuthService/Login",- want: "",+ want: nil,},- // The database group has not been annotated with resource yet.{- request: &v1pb.CreateDatabaseGroupRequest{- Parent: "projects/hello",+ request: &v1pb.CreateProjectRequest{+ Project: &v1pb.Project{+ Name: "projects/hello",+ },},- method: "/bytebase.v1.DatabaseGroupService/CreateDatabaseGroup",- want: "",+ method: "/bytebase.v1.ProjectService/CreateProject",+ want: &common.Resource{Workspace: true},},{request: &v1pb.UpdateProjectRequest{@@ -34,7 +36,20 @@ func TestGetResourceFromRequest(t *testing.T) {},},method: "/bytebase.v1.ProjectService/UpdateProject",- want: "projects/hello",+ want: &common.Resource{Name: "projects/hello"},+ },+ {+ request: &v1pb.ListProjectsRequest{},+ method: "/bytebase.v1.ProjectService/ListProjects",+ want: &common.Resource{Workspace: true},+ },+ // The database group has not been annotated with resource yet.+ {+ request: &v1pb.CreateDatabaseGroupRequest{+ Parent: "projects/hello",+ },+ method: "/bytebase.v1.DatabaseGroupService/CreateDatabaseGroup",+ want: nil,},{// The instance has not been annotated with resource yet.@@ -44,7 +59,14 @@ func TestGetResourceFromRequest(t *testing.T) {},},method: "/bytebase.v1.InstanceService/UpdateInstance",- want: "",+ want: nil,+ },+ {+ request: &v1pb.UpdateSubscriptionRequest{+ Patch: &v1pb.PatchSubscription{License: "123"},+ },+ method: "/bytebase.v1.SubscriptionService/UpdateSubscription",+ want: nil,},}@@ -53,3 +75,28 @@ func TestGetResourceFromRequest(t *testing.T) {require.Equal(t, tt.want, got, tt.method)}}++func TestToSnakeCase(t *testing.T) {+ tests := []struct {+ input string+ want string+ }{+ {+ input: "DatabaseGroup",+ want: "database_group",+ },+ {+ input: "User",+ want: "user",+ },+ {+ input: "Instance",+ want: "instance",+ },+ }++ for _, tt := range tests {+ got := toSnakeCase(tt.input)+ require.Equal(t, tt.want, got, tt.input)+ }+}