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(auth): prevent nil panic in GetCurrentUser for service accounts (#20367)
Danny Xue3023766badd
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.goindex 86725eb46f..6248d3157a 100644--- a/backend/api/auth/auth.go+++ b/backend/api/auth/auth.go@@ -218,10 +218,13 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr s}// Convert to UserMessage for context storage.- user, err := in.accountToUser(ctx, account)+ user, err := in.store.ResolvePrincipalAsUser(ctx, account)if err != nil {return nil, nil, err}+ if user == nil {+ return nil, nil, errs.Errorf("user %q not found", account.Email)+ }return user, claims, nil}@@ -268,29 +271,6 @@ func (in *APIAuthInterceptor) verifyWorkspaceMembership(ctx context.Context, wor}}-// accountToUser converts an AccountMessage to a UserMessage for context storage.-// For END_USER, loads the full user record. For SA/WI, constructs a minimal UserMessage.-func (in *APIAuthInterceptor) accountToUser(ctx context.Context, account *store.AccountMessage) (*store.UserMessage, error) {- if account.Type == storepb.PrincipalType_END_USER {- user, err := in.store.GetUserByEmail(ctx, account.Email)- if err != nil {- return nil, errs.Errorf("failed to get user %q", account.Email)- }- if user == nil {- return nil, errs.Errorf("user %q not found", account.Email)- }- return user, nil- }-- // SA/WI: construct a minimal UserMessage with the fields available from AccountMessage.- return &store.UserMessage{- Email: account.Email,- Name: account.Name,- Type: account.Type,- MemberDeleted: account.MemberDeleted,- }, nil-}-// authenticateConnect is a ConnectRPC-specific version that returns ConnectRPC errors.func (in *APIAuthInterceptor) authenticateConnect(ctx context.Context, accessTokenStr string) (*store.UserMessage, *claimsMessage, error) {user, claims, err := in.authenticate(ctx, accessTokenStr)diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex 0a2410b070..4d28139815 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -541,7 +541,14 @@ func (s *AuthService) getAndVerifyUser(ctx context.Context, request *v1pb.LoginR}// Convert AccountMessage to UserMessage for downstream use.- return s.accountToUser(ctx, account)+ user, err := s.store.ResolvePrincipalAsUser(ctx, account)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to resolve principal %q", account.Email))+ }+ if user == nil {+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("user %q not found", account.Email))+ }+ return user, nil}// getOrCreateUserWithIDP authenticates a user via an identity provider (SSO).@@ -1424,29 +1431,6 @@ func (s *AuthService) ExchangeToken(ctx context.Context, req *connect.Request[v1}), nil}-// accountToUser converts an AccountMessage to a UserMessage.-// For END_USER, loads the full user record. For SA/WI, constructs a minimal UserMessage.-func (s *AuthService) accountToUser(ctx context.Context, account *store.AccountMessage) (*store.UserMessage, error) {- if account.Type == storepb.PrincipalType_END_USER {- user, err := s.store.GetUserByEmail(ctx, account.Email)- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get user %q", account.Email))- }- if user == nil {- return nil, connect.NewError(connect.CodeUnauthenticated, errors.Errorf("user %q not found", account.Email))- }- return user, nil- }-- // SA/WI: construct a minimal UserMessage with the fields available from AccountMessage.- return &store.UserMessage{- Email: account.Email,- Name: account.Name,- Type: account.Type,- MemberDeleted: account.MemberDeleted,- }, nil-}-func getAccountRestriction(ctx context.Context,stores *store.Store,diff --git a/backend/store/account.go b/backend/store/account.goindex 24dde543fc..94c0cc205f 100644--- a/backend/store/account.go+++ b/backend/store/account.go@@ -3,6 +3,8 @@ package storeimport ("context"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store")@@ -77,3 +79,31 @@ func (s *Store) GetAccountByEmail(ctx context.Context, email string) (*AccountMeMemberDeleted: user.MemberDeleted,}, nil}++// ResolvePrincipalAsUser converts an AccountMessage into a *UserMessage suitable+// for downstream code that expects the legacy single-table principal shape.+//+// For END_USER, it loads the full record from the principal table. For service+// accounts and workload identities (which live in separate tables and have no+// profile/MFA data), it returns a minimal UserMessage with Profile and MFAConfig+// zero-initialized so downstream code dereferencing those fields does not panic.+//+// Returns (nil, nil) if account.Type == END_USER and no matching user exists.+// Callers map this to their own not-found error.+func (s *Store) ResolvePrincipalAsUser(ctx context.Context, account *AccountMessage) (*UserMessage, error) {+ if account.Type == storepb.PrincipalType_END_USER {+ user, err := s.GetUserByEmail(ctx, account.Email)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get user %q", account.Email)+ }+ return user, nil+ }+ return &UserMessage{+ Email: account.Email,+ Name: account.Name,+ Type: account.Type,+ MemberDeleted: account.MemberDeleted,+ Profile: &storepb.UserProfile{},+ MFAConfig: &storepb.MFAConfig{},+ }, nil+}diff --git a/backend/tests/user_test.go b/backend/tests/user_test.goindex f9c1e913a6..5a9c83298a 100644--- a/backend/tests/user_test.go+++ b/backend/tests/user_test.go@@ -8,6 +8,7 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/genproto/googleapis/type/expr"+ "google.golang.org/protobuf/types/known/emptypb""google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common"@@ -352,3 +353,66 @@ func TestUpdateUserEmail(t *testing.T) {a.NoError(err)a.Empty(oldEmailAuditLogs.Msg.AuditLogs, "Should not have audit logs with old email")}++func TestGetCurrentUser_ServiceAccount(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // Create a dummy user to get the workspace reference.+ userResp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{+ Title: "dummy",+ Email: "[email protected]",+ Password: "1024bytebase",+ },+ }))+ a.NoError(err)+ workspace := userResp.Msg.Workspace++ // Get actuator info using the workspace reference.+ actuator, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{+ Name: workspace,+ }))+ a.NoError(err)++ // Create a service account.+ saResp, err := ctl.serviceAccountServiceClient.CreateServiceAccount(ctx, connect.NewRequest(&v1pb.CreateServiceAccountRequest{+ Parent: actuator.Msg.Workspace,+ ServiceAccountId: "sa-test",+ ServiceAccount: &v1pb.ServiceAccount{+ Title: "SA Test",+ },+ }))+ a.NoError(err)+ sa := saResp.Msg++ // Grant the service account workspace admin role.+ _, err = ctl.addMemberToWorkspaceIAM(ctx, actuator.Msg.Workspace, fmt.Sprintf("serviceAccount:%v", sa.Email), "roles/workspaceAdmin")+ a.NoError(err)++ // Login as the service account using its service_key as password.+ loginResp, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{+ Email: sa.Email,+ Password: sa.ServiceKey,+ }))+ a.NoError(err)++ // Swap the controller token to the service account's token.+ originalToken := ctl.authInterceptor.token+ ctl.authInterceptor.token = loginResp.Msg.Token+ defer func() {+ ctl.authInterceptor.token = originalToken+ }()++ meResp, err := ctl.userServiceClient.GetCurrentUser(ctx, connect.NewRequest(&emptypb.Empty{}))++ // Assertions per the task specification.+ a.NoError(err)+ a.NotNil(meResp.Msg)+ a.Equal(sa.Email, meResp.Msg.Email)+ a.NotNil(meResp.Msg.Profile)+}