Organize backend into product executable and shared Go modules

This commit is contained in:
Stephan D committed 2026-09-12 14:14:08 +02:00
1 parent 981e84a4b4
commit f0720ec66b
382 files changed
+1944 -6989

No files matched your search

@@ -0,0 +1,131 @@
package accountserviceimp
import (
"context"
"git.sendico.io/tech/sxchnge/product/auth/config"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model"
"git.sendico.io/tech/sxchnge/product/verification/store"
"git.sendico.io/tech/sxchnge/shared/database"
edgemongo "git.sendico.io/tech/sxchnge/shared/database/dependencies"
"git.sendico.io/tech/sxchnge/shared/errors"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/modules/mongodb"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
"net/url"
"testing"
"time"
)
func customer(login string) *customermodel.Account {
return (&customermodel.AccountData{LoginData: customermodel.LoginData{UserDataBase: customermodel.UserDataBase{Login: login}, Password: "CustomerPassword1!"}, Describable: sharedmodel.Describable{Name: "Customer"}}).ToAccount()
}
// Uses the actual copied repositories against an empty SXCHNGE database.
// There is deliberately no seed, organization, role, policy or Sendico connection.
func TestCustomerLifecycleWithoutTenancy(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
container, err := mongodb.Run(ctx, "mongo:8", mongodb.WithReplicaSet("rs"))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, container.Terminate(context.Background())) })
uri, err := container.ConnectionString(ctx)
require.NoError(t, err)
endpoint, err := url.Parse(uri)
require.NoError(t, err)
query := endpoint.Query()
query.Set("directConnection", "true")
endpoint.RawQuery = query.Encode()
uri = endpoint.String()
factory, err := db.NewConnection(zap.NewNop(), &db.Config{Driver: db.Mongo, Settings: sharedmodel.SettingsT{"uri": uri, "database": "sxchnge_customers"}})
require.NoError(t, err)
t.Cleanup(factory.CloseConnection)
// Custom collections prove lifecycle and login storage select the same data.
config := &middleware.AuthStorageConfig{AccountsCollection: "customers", VerificationTokensCollection: "customer_verification", RefreshTokensCollection: "customer_sessions"}
svc, err := NewAccountService(zap.NewNop(), factory, &middleware.PasswordConfig{Check: middleware.PasswordChecks{MinLength: 12}}, config)
require.NoError(t, err)
first, second := customer("first@example.test"), customer("second@example.test")
firstToken, err := svc.CreateAccount(ctx, first)
require.NoError(t, err)
require.NotEmpty(t, firstToken)
require.Equal(t, customermodel.AccountPendingVerification, first.Status)
require.True(t, first.MatchPassword("CustomerPassword1!"))
_, err = svc.CreateAccount(ctx, second)
require.NoError(t, err)
require.NotEqual(t, first.ID, second.ID)
// Activation tokens cannot be used as another customer's token.
_, err = svc.vdb.Consume(ctx, second.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
require.Error(t, err)
_, err = svc.vdb.Consume(ctx, first.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
require.NoError(t, err)
_, err = svc.CreateAccount(ctx, customer("first@example.test"))
require.ErrorIs(t, err, merrors.ErrDataConflict)
require.NoError(t, svc.ValidateAccount(customer("validate@example.test")))
require.ErrorIs(t, svc.ValidateAccount(nil), merrors.ErrInvalidArg)
_, err = svc.CreateAccount(ctx, nil)
require.ErrorIs(t, err, merrors.ErrInvalidArg)
require.ErrorIs(t, svc.DeleteAccount(ctx, bson.NilObjectID), merrors.ErrInvalidArg)
for _, c := range []*customermodel.Account{first, second} {
require.NoError(t, svc.sessions.Create(ctx, &sessionmodel.RefreshToken{AccountRef: &c.ID, ExpiresAt: time.Now().Add(time.Hour), ClientRefreshToken: sessionmodel.ClientRefreshToken{SessionIdentifier: sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}, RefreshToken: c.ID.Hex()}}))
}
require.NoError(t, svc.DeleteAccount(ctx, first.ID))
var stored customermodel.Account
require.ErrorIs(t, svc.accountDB.Get(ctx, first.ID, &stored), merrors.ErrNoData)
require.NoError(t, svc.accountDB.Get(ctx, second.ID, &stored))
session := &sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}
_, err = svc.sessions.GetSession(ctx, first.ID, session)
require.Error(t, err)
_, err = svc.sessions.GetSession(ctx, second.ID, session)
require.NoError(t, err)
// The final local customer can be deleted; there is no sole-member restriction.
require.NoError(t, svc.DeleteAccount(ctx, second.ID))
deps, err := edgemongo.ResolveDependencies(factory)
require.NoError(t, err)
collections, err := deps.Database.ListCollectionNames(ctx, bson.D{})
require.NoError(t, err)
for _, forbidden := range []string{"organizations", "roles", "policies", "policy_assignments", "invitations", "accounts"} {
require.NotContains(t, collections, forbidden)
}
// A token issuance failure must roll back the preceding customer insert.
realVerification := svc.vdb
failure := merrors.Internal("injected verification failure")
svc.vdb = &failingVerification{DB: realVerification, failure: failure}
candidate := customer("rollback@example.test")
_, err = svc.CreateAccount(ctx, candidate)
require.ErrorIs(t, err, failure)
require.True(t, candidate.ID.IsZero())
_, err = svc.accountDB.GetByEmail(ctx, candidate.Login)
require.ErrorIs(t, err, merrors.ErrNoData)
svc.vdb = realVerification
// If an outer workflow fails after token issuance, neither write may commit.
outerFailure := merrors.Internal("injected outer failure")
_, err = factory.TransactionFactory().CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
_, e := svc.CreateAccount(tx, customer("outer@example.test"))
if e != nil {
return nil, e
}
return nil, outerFailure
})
require.ErrorIs(t, err, outerFailure)
_, err = svc.accountDB.GetByEmail(ctx, "outer@example.test")
require.ErrorIs(t, err, merrors.ErrNoData)
count, err := deps.Database.Collection(config.VerificationTokensCollection).CountDocuments(ctx, bson.D{})
require.NoError(t, err)
require.EqualValues(t, 2, count)
}
type failingVerification struct {
verification.DB
failure error
}
func (f *failingVerification) Create(context.Context, *verification.Request) (string, error) {
return "", f.failure
}
@@ -0,0 +1,248 @@
package accountserviceimp
import (
"context"
"errors"
"fmt"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model"
"time"
"unicode"
"git.sendico.io/tech/sxchnge/product/auth/config"
authstorage "git.sendico.io/tech/sxchnge/product/auth/storage"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/product/verification/store"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/database/transaction"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type service struct {
logger mlogger.Logger
accountDB account.DB
config *middleware.PasswordConfig
vdb verification.DB
sessions refreshtokens.DB
transactions transaction.Factory
}
func validateUserRequest(u *customermodel.Account) error {
if u == nil {
return merrors.InvalidArgument("account is required")
}
if u.Name == "" {
return merrors.InvalidArgument("Name must not be empty")
}
if u.Login == "" {
return merrors.InvalidArgument("Login must not be empty")
}
if u.Password == "" {
return merrors.InvalidArgument("Password must not be empty")
}
return nil
}
func (s *service) ValidatePassword(
password string,
oldPassword *string,
) error {
var hasDigit, hasUpper, hasLower, hasSpecial bool
if oldPassword != nil {
if *oldPassword == password {
return merrors.InvalidArgument("New password cannot be the same as the old password")
}
}
if len(password) < s.config.Check.MinLength {
return merrors.InvalidArgument(fmt.Sprintf("Password must be at least %d characters long", s.config.Check.MinLength))
}
// Check for digit, uppercase, lowercase, and special character
for _, char := range password {
switch {
case unicode.IsDigit(char):
hasDigit = true
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
if s.config.Check.Digit && !hasDigit {
return merrors.InvalidArgument("Password must contain at least one digit")
}
if s.config.Check.Upper && !hasUpper {
return merrors.InvalidArgument("Password must contain at least one uppercase letter")
}
if s.config.Check.Lower && !hasLower {
return merrors.InvalidArgument("Password must contain at least one lowercase letter")
}
if s.config.Check.Special && !hasSpecial {
return merrors.InvalidArgument("Password must contain at least one special character")
}
// If all checks pass, return nil (no error)
return nil
}
func (s *service) ValidateAccount(acct *customermodel.Account) error {
if err := validateUserRequest(acct); err != nil {
s.logger.Warn("Invalid signup account received", zap.Error(err))
return err
}
if err := s.ValidatePassword(acct.Password, nil); err != nil {
s.logger.Warn("Password validation failed", zap.Error(err), mzap.Email(acct.Login))
return err
}
if err := acct.HashPassword(); err != nil {
s.logger.Warn("Failed to hash password", zap.Error(err), mzap.Email(acct.Login))
return err
}
return nil
}
func (s *service) CreateAccount(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil {
return "", merrors.InvalidArgument("account is required")
}
if !acct.ID.IsZero() {
return "", merrors.InvalidArgument("new account must not have an ID")
}
candidate := acct.Copy()
if err := s.ValidateAccount(candidate); err != nil {
return "", err
}
candidate.Status = customermodel.AccountPendingVerification
// The customer and activation token either both commit or neither does.
var saved *customermodel.Account
result, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
saved = candidate.Copy()
if err := s.accountDB.Create(tx, saved); err != nil {
return nil, err
}
return s.VerifyAccount(tx, saved)
})
if err != nil {
if errors.Is(err, merrors.ErrDataConflict) {
s.logger.Info("Customer login already exists")
} else {
s.logger.Warn("Customer creation failed", zap.Error(err))
}
return "", err
}
token, ok := result.(string)
if !ok {
return "", merrors.Internal("unexpected account creation result")
}
*acct = *saved
s.logger.Info("Customer created pending verification", mzap.AccRef(acct.ID))
return token, nil
}
func (s *service) VerifyAccount(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
token, err := s.vdb.Create(
ctx,
verification.NewLinkRequest(*acct.GetID(), verificationmodel.PurposeAccountActivation, "").
WithTTL(time.Hour*24),
)
if err != nil {
s.logger.Warn("Failed to create verification token for new account", zap.Error(err), mzap.StorableRef(acct))
return "", err
}
return token, nil
}
func (s *service) DeleteAccount(
ctx context.Context,
accountRef bson.ObjectID,
) error {
if accountRef.IsZero() {
return merrors.InvalidArgument("account reference is required")
}
_, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
if err := s.sessions.RevokeAll(tx, accountRef, ""); err != nil {
return nil, err
}
return nil, s.accountDB.Delete(tx, accountRef)
})
if err != nil {
s.logger.Warn("Customer deletion failed", zap.Error(err), mzap.AccRef(accountRef))
return err
}
s.logger.Info("Customer deleted and sessions revoked", mzap.AccRef(accountRef))
return nil
}
func (s *service) ResetPassword(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), verificationmodel.PurposePasswordReset, "").
WithTTL(time.Hour),
)
}
func (s *service) UpdateLogin(
ctx context.Context,
acct *customermodel.Account,
newLogin string,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), verificationmodel.PurposeEmailChange, newLogin).
WithTTL(time.Hour),
)
}
func NewAccountService(
l mlogger.Logger,
dbf db.Factory,
config *middleware.PasswordConfig,
storageConfig *middleware.AuthStorageConfig,
) (*service, error) {
logger := l.Named("account_service")
if config == nil {
return nil, merrors.Internal("password configuration is required")
}
stores, err := authstorage.OpenStores(logger, dbf, storageConfig)
if err != nil {
return nil, err
}
return &service{logger: logger, config: config, accountDB: stores.Accounts,
vdb: stores.Verification, sessions: stores.RefreshTokens, transactions: dbf.TransactionFactory()}, nil
}
@@ -0,0 +1,245 @@
package accountserviceimp
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"testing"
apiconfig "git.sendico.io/tech/sxchnge/product/auth/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// TestValidatePassword tests the password validation logic directly
func TestValidatePassword(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 8,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 32,
}
// Create a minimal service for testing password validation
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
t.Run("ValidPassword", func(t *testing.T) {
err := service.ValidatePassword("TestPassword123!", nil)
assert.NoError(t, err)
})
t.Run("PasswordTooShort", func(t *testing.T) {
err := service.ValidatePassword("Test1!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least 8 characters")
})
t.Run("PasswordMissingDigit", func(t *testing.T) {
err := service.ValidatePassword("TestPassword!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one digit")
})
t.Run("PasswordMissingUppercase", func(t *testing.T) {
err := service.ValidatePassword("testpassword123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one uppercase")
})
t.Run("PasswordMissingLowercase", func(t *testing.T) {
err := service.ValidatePassword("TESTPASSWORD123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one lowercase")
})
t.Run("PasswordMissingSpecialCharacter", func(t *testing.T) {
err := service.ValidatePassword("TestPassword123", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one special character")
})
t.Run("PasswordSameAsOld", func(t *testing.T) {
oldPassword := "TestPassword123!"
err := service.ValidatePassword("TestPassword123!", &oldPassword)
assert.Error(t, err)
assert.Contains(t, err.Error(), "cannot be the same as the old password")
})
}
// TestValidateAccount tests the account validation logic directly
func TestValidateAccount(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 8,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 32,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
t.Run("ValidAccount", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "TestPassword123!",
}
originalPassword := account.Password
err := service.ValidateAccount(account)
require.NoError(t, err)
// Password should be hashed after validation
assert.NotEqual(t, originalPassword, account.Password)
})
t.Run("AccountMissingName", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "TestPassword123!",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Name must not be empty")
})
t.Run("AccountMissingLogin", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
},
Password: "TestPassword123!",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Login must not be empty")
})
t.Run("AccountMissingPassword", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Password must not be empty")
})
t.Run("AccountInvalidPassword", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "weak", // Should fail validation
}
err := service.ValidateAccount(account)
assert.Error(t, err)
// Should fail on password validation
assert.Contains(t, err.Error(), "at least 8 characters")
})
}
// TestPasswordConfiguration verifies different password rule configurations
func TestPasswordConfiguration(t *testing.T) {
t.Run("MinimalRequirements", func(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 4,
Digit: false,
Upper: false,
Lower: false,
Special: false,
},
TokenLength: 16,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
// Should pass with minimal requirements
err := service.ValidatePassword("test", nil)
assert.NoError(t, err)
})
t.Run("StrictRequirements", func(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 12,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 64,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
// Should fail with shorter password
err := service.ValidatePassword("Test123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least 12 characters")
// Should pass with longer password
err = service.ValidatePassword("TestPassword123!", nil)
assert.NoError(t, err)
})
}