Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement authorization checks for environment and instance services (#4065)
Danny Xu0aefbd7f4290
diff --git a/server/api/auth/acl.go b/server/api/auth/acl.goindex 6dc64ca871..c9495d7184 100644--- a/server/api/auth/acl.go+++ b/server/api/auth/acl.go@@ -13,20 +13,24 @@ import (// ACLInterceptor is the unary interceptor for gRPC API.func (in *APIAuthInterceptor) ACLInterceptor(ctx context.Context, req interface{}, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {- role, err := in.getWorkspaceRole(ctx, serverInfo.FullMethod)+ methodName := getShortMethodName(serverInfo.FullMethod)+ role, err := in.getWorkspaceRole(ctx, methodName)if err != nil {return nil, status.Errorf(codes.PermissionDenied, err.Error())}- // Stores principalID into context.- childCtx := context.WithValue(ctx, common.RoleContextKey, role)+ if role == api.Developer && isOwnerAndDBAMethod(methodName) {+ return nil, status.Errorf(codes.PermissionDenied, "only workspace owner and DBA can access method %q", methodName)+ }- // TODO(d): implement the authorization.+ // TODO(d): implement authorization checks for project resources.+ // Stores principalID into context.+ childCtx := context.WithValue(ctx, common.RoleContextKey, role)return handler(childCtx, req)}-func (in *APIAuthInterceptor) getWorkspaceRole(ctx context.Context, fullMethod string) (api.Role, error) {- if isAuthenticationAllowed(fullMethod) {+func (in *APIAuthInterceptor) getWorkspaceRole(ctx context.Context, methodName string) (api.Role, error) {+ if isAuthenticationAllowed(methodName) {return api.Owner, nil}// If RBAC feature is not enabled, all users are treated as OWNER.diff --git a/server/api/auth/auth.go b/server/api/auth/auth.goindex 6f48ec93e6..c4208ffcdc 100644--- a/server/api/auth/auth.go+++ b/server/api/auth/auth.go@@ -52,48 +52,49 @@ func New(store *store.Store, secret string, licenseService enterpriseAPI.License// AuthenticationInterceptor is the unary interceptor for gRPC API.func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, req interface{}, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {// TODO(d): skips actuator, GET /subscription request, OpenAPI SQL endpoint.- if isAuthenticationAllowed(serverInfo.FullMethod) {+ methodName := getShortMethodName(serverInfo.FullMethod)+ if isAuthenticationAllowed(methodName) {return handler(ctx, req)}md, ok := metadata.FromIncomingContext(ctx)if !ok {- return nil, status.Error(codes.PermissionDenied, "failed to parse metadata from incoming context")+ return nil, status.Error(codes.Unauthenticated, "failed to parse metadata from incoming context")}if len(md.Get("Authorization")) == 0 {- return nil, status.Error(codes.PermissionDenied, "failed to get authorization metadata from incoming context")+ return nil, status.Error(codes.Unauthenticated, "failed to get authorization metadata from incoming context")}authorization := md.Get("Authorization")[0]authHeaderParts := strings.Fields(authorization)if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {- return nil, status.Error(codes.PermissionDenied, "authorization header format must be Bearer {token}")+ return nil, status.Error(codes.Unauthenticated, "authorization header format must be Bearer {token}")}token := authHeaderParts[1]claims := &claims{}if _, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {if t.Method.Alg() != jwt.SigningMethodHS256.Name {- return nil, status.Errorf(codes.PermissionDenied, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)+ return nil, status.Errorf(codes.Unauthenticated, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)}if kid, ok := t.Header["kid"].(string); ok {if kid == "v1" {return []byte(in.secret), nil}}- return nil, status.Errorf(codes.PermissionDenied, "unexpected access token kid=%v", t.Header["kid"])+ return nil, status.Errorf(codes.Unauthenticated, "unexpected access token kid=%v", t.Header["kid"])}); err != nil {var ve *jwt.ValidationErrorif errors.As(err, &ve) {// If expiration error is the only error, we will clear the err// and generate new access token and refresh tokenif ve.Errors == jwt.ValidationErrorExpired {- return nil, status.Errorf(codes.PermissionDenied, "access token is expired")+ return nil, status.Errorf(codes.Unauthenticated, "access token is expired")}}- return nil, status.Errorf(codes.PermissionDenied, "failed to parse claim")+ return nil, status.Errorf(codes.Unauthenticated, "failed to parse claim")}if !audienceContains(claims.Audience, fmt.Sprintf(accessTokenAudienceFmt, in.mode)) {- return nil, status.Errorf(codes.PermissionDenied,+ return nil, status.Errorf(codes.Unauthenticated,"invalid access token, audience mismatch, got %q, expected %q. you may send request to the wrong environment",claims.Audience,fmt.Sprintf(accessTokenAudienceFmt, in.mode),@@ -102,14 +103,14 @@ func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, reqprincipalID, err := strconv.Atoi(claims.Subject)if err != nil {- return nil, status.Errorf(codes.PermissionDenied, "malformed ID %q in the access token", claims.Subject)+ return nil, status.Errorf(codes.Unauthenticated, "malformed ID %q in the access token", claims.Subject)}user, err := in.store.GetPrincipalByID(ctx, principalID)if err != nil {- return nil, status.Errorf(codes.PermissionDenied, "failed to find user ID %q in the access token", principalID)+ return nil, status.Errorf(codes.Unauthenticated, "failed to find user ID %q in the access token", principalID)}if user == nil {- return nil, status.Errorf(codes.PermissionDenied, "user ID %q not exists in the access token", principalID)+ return nil, status.Errorf(codes.Unauthenticated, "user ID %q not exists in the access token", principalID)}// Stores principalID into context.childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, principalID)diff --git a/server/api/auth/config.go b/server/api/auth/config.goindex 0c5ba6e54b..42ae10d9bc 100644--- a/server/api/auth/config.go+++ b/server/api/auth/config.go@@ -1,21 +1,34 @@package authimport (- "fmt""strings")const apiPackagePrefix = "/bytebase.v1."-var authenticationAllowlistMethods = []string{- "AuthService/Login",+var authenticationAllowlistMethods = map[string]bool{+ "AuthService/Login": true,}-func isAuthenticationAllowed(fullMethod string) bool {- for _, allow := range authenticationAllowlistMethods {- if strings.HasPrefix(fullMethod, fmt.Sprintf("%s%s", apiPackagePrefix, allow)) {- return true- }- }- return false+var ownerAndDBAMethods = map[string]bool{+ "EnvironmentService/CreateEnvironment": true,+ "EnvironmentService/UpdateEnvironment": true,+ "EnvironmentService/DeleteEnvironment": true,+ "EnvironmentService/UndeleteEnvironment": true,+ "InstanceService/CreateInstance": true,+ "InstanceService/UpdateInstance": true,+ "InstanceService/DeleteInstance": true,+ "InstanceService/UndeleteInstance": true,+}++func getShortMethodName(fullMethod string) string {+ return strings.TrimPrefix(fullMethod, apiPackagePrefix)+}++func isAuthenticationAllowed(methodName string) bool {+ return authenticationAllowlistMethods[methodName]+}++func isOwnerAndDBAMethod(methodName string) bool {+ return ownerAndDBAMethods[methodName]}