From 28eb2e3c834dce41bc783300d5f0a35dc3e11936 Mon Sep 17 00:00:00 2001 From: Marwen Abid Date: Wed, 17 Apr 2024 09:27:52 -0700 Subject: [PATCH] [SDP-1155] decommission stellar-multitenant CLI (#261) * SDP-1155 Decommission MTN CLI * SDP-1155 re-arrange code inside stellar-multitenant package * SDP-1155 remove dead code --- internal/utils/network_type.go | 12 - .../cmd/stellarmultitenant/main.go | 24 -- .../internal/httphandler/health_handler.go | 0 .../httphandler/health_handler_test.go | 0 .../internal/httphandler/tenants_handler.go | 4 +- .../httphandler/tenants_handler_test.go | 2 +- .../internal/provisioning/manager.go | 0 .../internal/provisioning/manager_test.go | 0 .../internal/validators/tenant_validator.go | 0 .../validators/tenant_validator_test.go | 0 .../internal/validators/validator.go | 0 .../internal/validators/validator_test.go | 0 stellar-multitenant/pkg/cli/add_tenants.go | 239 ----------- .../pkg/cli/add_tenants_test.go | 404 ------------------ stellar-multitenant/pkg/cli/config_tenant.go | 127 ------ stellar-multitenant/pkg/cli/migrate.go | 26 -- stellar-multitenant/pkg/cli/migrate_test.go | 219 ---------- stellar-multitenant/pkg/cli/root.go | 70 --- .../pkg/cli/utils/custom_set_value.go | 89 ---- stellar-multitenant/pkg/serve/serve.go | 4 +- 20 files changed, 5 insertions(+), 1215 deletions(-) delete mode 100644 stellar-multitenant/cmd/stellarmultitenant/main.go rename stellar-multitenant/{pkg => }/internal/httphandler/health_handler.go (100%) rename stellar-multitenant/{pkg => }/internal/httphandler/health_handler_test.go (100%) rename stellar-multitenant/{pkg => }/internal/httphandler/tenants_handler.go (98%) rename stellar-multitenant/{pkg => }/internal/httphandler/tenants_handler_test.go (99%) rename stellar-multitenant/{pkg => }/internal/provisioning/manager.go (100%) rename stellar-multitenant/{pkg => }/internal/provisioning/manager_test.go (100%) rename stellar-multitenant/{pkg => }/internal/validators/tenant_validator.go (100%) rename stellar-multitenant/{pkg => }/internal/validators/tenant_validator_test.go (100%) rename stellar-multitenant/{pkg => }/internal/validators/validator.go (100%) rename stellar-multitenant/{pkg => }/internal/validators/validator_test.go (100%) delete mode 100644 stellar-multitenant/pkg/cli/add_tenants.go delete mode 100644 stellar-multitenant/pkg/cli/add_tenants_test.go delete mode 100644 stellar-multitenant/pkg/cli/config_tenant.go delete mode 100644 stellar-multitenant/pkg/cli/migrate.go delete mode 100644 stellar-multitenant/pkg/cli/migrate_test.go delete mode 100644 stellar-multitenant/pkg/cli/root.go delete mode 100644 stellar-multitenant/pkg/cli/utils/custom_set_value.go diff --git a/internal/utils/network_type.go b/internal/utils/network_type.go index c8783eafc..7cec3f01d 100644 --- a/internal/utils/network_type.go +++ b/internal/utils/network_type.go @@ -2,7 +2,6 @@ package utils import ( "fmt" - "strings" "github.com/stellar/go/network" ) @@ -24,14 +23,3 @@ func GetNetworkTypeFromNetworkPassphrase(networkPassphrase string) (NetworkType, return "", fmt.Errorf("invalid network passphrase provided") } } - -func GetNetworkTypeFromString(networkType string) (NetworkType, error) { - switch NetworkType(strings.ToLower(networkType)) { - case PubnetNetworkType: - return PubnetNetworkType, nil - case TestnetNetworkType: - return TestnetNetworkType, nil - default: - return "", fmt.Errorf("invalid network type provided") - } -} diff --git a/stellar-multitenant/cmd/stellarmultitenant/main.go b/stellar-multitenant/cmd/stellarmultitenant/main.go deleted file mode 100644 index da6ee6f6c..000000000 --- a/stellar-multitenant/cmd/stellarmultitenant/main.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "github.com/sirupsen/logrus" - "github.com/stellar/go/support/log" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/cli" -) - -// Version is the official version of this application. -const Version = "0.1.0" - -// GitCommit is populated at build time by -// go build -ldflags "-X main.GitCommit=$GIT_COMMIT" -var GitCommit string - -func main() { - log.DefaultLogger = log.New() - log.DefaultLogger.SetLevel(logrus.TraceLevel) - - cmd := cli.SetupCLI(Version, GitCommit) - if err := cmd.Execute(); err != nil { - log.Ctx(cmd.Context()).Fatalf("error executing: %s", err.Error()) - } -} diff --git a/stellar-multitenant/pkg/internal/httphandler/health_handler.go b/stellar-multitenant/internal/httphandler/health_handler.go similarity index 100% rename from stellar-multitenant/pkg/internal/httphandler/health_handler.go rename to stellar-multitenant/internal/httphandler/health_handler.go diff --git a/stellar-multitenant/pkg/internal/httphandler/health_handler_test.go b/stellar-multitenant/internal/httphandler/health_handler_test.go similarity index 100% rename from stellar-multitenant/pkg/internal/httphandler/health_handler_test.go rename to stellar-multitenant/internal/httphandler/health_handler_test.go diff --git a/stellar-multitenant/pkg/internal/httphandler/tenants_handler.go b/stellar-multitenant/internal/httphandler/tenants_handler.go similarity index 98% rename from stellar-multitenant/pkg/internal/httphandler/tenants_handler.go rename to stellar-multitenant/internal/httphandler/tenants_handler.go index 844bf479c..63f4e3812 100644 --- a/stellar-multitenant/pkg/internal/httphandler/tenants_handler.go +++ b/stellar-multitenant/internal/httphandler/tenants_handler.go @@ -13,8 +13,8 @@ import ( "github.com/stellar/stellar-disbursement-platform-backend/db" "github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httperror" "github.com/stellar/stellar-disbursement-platform-backend/internal/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/provisioning" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/validators" + "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/internal/provisioning" + "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/internal/validators" "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" ) diff --git a/stellar-multitenant/pkg/internal/httphandler/tenants_handler_test.go b/stellar-multitenant/internal/httphandler/tenants_handler_test.go similarity index 99% rename from stellar-multitenant/pkg/internal/httphandler/tenants_handler_test.go rename to stellar-multitenant/internal/httphandler/tenants_handler_test.go index 0bb337f04..7757b63f2 100644 --- a/stellar-multitenant/pkg/internal/httphandler/tenants_handler_test.go +++ b/stellar-multitenant/internal/httphandler/tenants_handler_test.go @@ -25,7 +25,7 @@ import ( preconditionsMocks "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/preconditions/mocks" "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/signing" "github.com/stellar/stellar-disbursement-platform-backend/internal/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/provisioning" + "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/internal/provisioning" "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" ) diff --git a/stellar-multitenant/pkg/internal/provisioning/manager.go b/stellar-multitenant/internal/provisioning/manager.go similarity index 100% rename from stellar-multitenant/pkg/internal/provisioning/manager.go rename to stellar-multitenant/internal/provisioning/manager.go diff --git a/stellar-multitenant/pkg/internal/provisioning/manager_test.go b/stellar-multitenant/internal/provisioning/manager_test.go similarity index 100% rename from stellar-multitenant/pkg/internal/provisioning/manager_test.go rename to stellar-multitenant/internal/provisioning/manager_test.go diff --git a/stellar-multitenant/pkg/internal/validators/tenant_validator.go b/stellar-multitenant/internal/validators/tenant_validator.go similarity index 100% rename from stellar-multitenant/pkg/internal/validators/tenant_validator.go rename to stellar-multitenant/internal/validators/tenant_validator.go diff --git a/stellar-multitenant/pkg/internal/validators/tenant_validator_test.go b/stellar-multitenant/internal/validators/tenant_validator_test.go similarity index 100% rename from stellar-multitenant/pkg/internal/validators/tenant_validator_test.go rename to stellar-multitenant/internal/validators/tenant_validator_test.go diff --git a/stellar-multitenant/pkg/internal/validators/validator.go b/stellar-multitenant/internal/validators/validator.go similarity index 100% rename from stellar-multitenant/pkg/internal/validators/validator.go rename to stellar-multitenant/internal/validators/validator.go diff --git a/stellar-multitenant/pkg/internal/validators/validator_test.go b/stellar-multitenant/internal/validators/validator_test.go similarity index 100% rename from stellar-multitenant/pkg/internal/validators/validator_test.go rename to stellar-multitenant/internal/validators/validator_test.go diff --git a/stellar-multitenant/pkg/cli/add_tenants.go b/stellar-multitenant/pkg/cli/add_tenants.go deleted file mode 100644 index 5895bc582..000000000 --- a/stellar-multitenant/pkg/cli/add_tenants.go +++ /dev/null @@ -1,239 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "go/types" - "regexp" - - "github.com/spf13/cobra" - "github.com/stellar/go/clients/horizonclient" - "github.com/stellar/go/support/config" - "github.com/stellar/go/support/log" - "golang.org/x/exp/slices" - - cmdUtils "github.com/stellar/stellar-disbursement-platform-backend/cmd/utils" - "github.com/stellar/stellar-disbursement-platform-backend/db" - di "github.com/stellar/stellar-disbursement-platform-backend/internal/dependencyinjection" - "github.com/stellar/stellar-disbursement-platform-backend/internal/message" - "github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httpclient" - "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine" - "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/preconditions" - "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/signing" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/cli/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/provisioning" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" -) - -var validTenantName *regexp.Regexp = regexp.MustCompile(`^[a-z-]+$`) - -type AddTenantsCommandOptions struct { - SDPUIBaseURL *string - NetworkType string - MessengerOptions message.MessengerOptions - TenantAccountNativeAssetBootstrapAmount int -} - -func AddTenantsCmd() *cobra.Command { - tenantsOpts := AddTenantsCommandOptions{} - configOptions := config.ConfigOptions{ - { - Name: "network-type", - Usage: "The Stellar Network type", - OptType: types.String, - CustomSetValue: utils.SetConfigOptionNetworkType, - ConfigKey: &tenantsOpts.NetworkType, - FlagDefault: "testnet", - Required: true, - }, - { - Name: "sdp-ui-base-url", - Usage: "The Tenant SDP UI/dashboard Base URL.", - OptType: types.String, - CustomSetValue: utils.SetConfigOptionURLString, - ConfigKey: &tenantsOpts.SDPUIBaseURL, - FlagDefault: "http://localhost:3000", - Required: true, - }, - { - Name: "email-sender-type", - Usage: fmt.Sprintf("The messenger type used to send invitations to new dashboard users. Options: %+v", message.MessengerType("").ValidEmailTypes()), - OptType: types.String, - CustomSetValue: utils.SetConfigOptionMessengerType, - ConfigKey: &tenantsOpts.MessengerOptions.MessengerType, - Required: true, - }, - { - Name: "aws-access-key-id", - Usage: "The AWS access key ID", - OptType: types.String, - ConfigKey: &tenantsOpts.MessengerOptions.AWSAccessKeyID, - Required: false, - }, - { - Name: "aws-secret-access-key", - Usage: "The AWS secret access key", - OptType: types.String, - ConfigKey: &tenantsOpts.MessengerOptions.AWSSecretAccessKey, - Required: false, - }, - { - Name: "aws-region", - Usage: "The AWS region", - OptType: types.String, - ConfigKey: &tenantsOpts.MessengerOptions.AWSRegion, - Required: false, - }, - cmdUtils.TenantXLMBootstrapAmount(&tenantsOpts.TenantAccountNativeAssetBootstrapAmount), - } - - txSubOpts := di.TxSubmitterEngineOptions{} - configOptions = append(configOptions, cmdUtils.TransactionSubmitterEngineConfigOptions(&txSubOpts)...) - configOptions = append(configOptions, cmdUtils.NetworkPassphrase(&txSubOpts.SignatureServiceOptions.NetworkPassphrase)) - - distAccResolverOpts := signing.DistributionAccountResolverOptions{} - configOptions = append(configOptions, cmdUtils.DistributionPublicKey(&distAccResolverOpts.HostDistributionAccountPublicKey)) - - cmd := cobra.Command{ - Use: "add-tenants", - Short: "Add a new tenant", - Example: "add-tenants [tenant name] [user first name] [user last name] [user email] [organization name]", - Long: "Add a new tenant. The tenant name should only contain lower case characters and dash (-)", - Args: cobra.MatchAll( - cobra.ExactArgs(5), - validateTenantNameArg, - ), - PersistentPreRun: func(cmd *cobra.Command, args []string) { - cmdUtils.PropagatePersistentPreRun(cmd, args) - configOptions.Require() - err := configOptions.SetValues() - if err != nil { - log.Ctx(cmd.Context()).Fatalf("Error setting values of config options: %s", err.Error()) - } - }, - Run: func(cmd *cobra.Command, args []string) { - ctx := cmd.Context() - - // Get messenger client - emailMessengerClient, err := di.NewEmailClient(di.EmailClientOptions{ - EmailType: tenantsOpts.MessengerOptions.MessengerType, - MessengerOptions: &tenantsOpts.MessengerOptions, - }) - if err != nil { - log.Ctx(ctx).Fatalf("creating email client: %v", err) - } - - // Get TSS DB connection pool - // TODO: in SDP-874, make sure to add metrics to this DB options, like we do in cmd/serve.go - dbcpOptions := di.DBConnectionPoolOptions{DatabaseURL: globalOptions.multitenantDbURL} - tssDBConnectionPool, err := di.NewTSSDBConnectionPool(ctx, dbcpOptions) - if err != nil { - log.Ctx(ctx).Fatalf("getting TSS DBConnectionPool: %v", err) - } - defer func() { - di.CleanupInstanceByValue(ctx, tssDBConnectionPool) - }() - - // Get Admin DB connection pool - adminDBConnectionPool, err := di.NewAdminDBConnectionPool(ctx, dbcpOptions) - if err != nil { - log.Ctx(ctx).Fatalf("getting Admin database connection pool: %v", err) - } - defer func() { - di.CleanupInstanceByValue(ctx, adminDBConnectionPool) - }() - - tenantName, userFirstName, userLastName, userEmail, organizationName := args[0], args[1], args[2], args[3], args[4] - err = executeAddTenant( - ctx, - adminDBConnectionPool, tssDBConnectionPool, - tenantName, userFirstName, userLastName, userEmail, organizationName, - emailMessengerClient, - tenantsOpts, - txSubOpts, - distAccResolverOpts, - ) - if err != nil { - log.Ctx(ctx).Fatalf("Error adding tenant: %v", err) - } - }, - } - - if err := configOptions.Init(&cmd); err != nil { - log.Ctx(cmd.Context()).Fatalf("initializing config options: %v", err) - } - - return &cmd -} - -func validateTenantNameArg(cmd *cobra.Command, args []string) error { - if !validTenantName.MatchString(args[0]) { - return fmt.Errorf("invalid tenant name %q. It should only contains lower case letters and dash (-)", args[0]) - } - return nil -} - -func executeAddTenant( - ctx context.Context, - adminDBConnectionPool, tssDBConnectionPool db.DBConnectionPool, - tenantName, userFirstName, userLastName, userEmail, organizationName string, - messengerClient message.MessengerClient, - tenantsOpts AddTenantsCommandOptions, - txSubOpts di.TxSubmitterEngineOptions, - distAccResolverOpts signing.DistributionAccountResolverOptions, -) error { - if !slices.Contains(signing.DistributionSignatureClientTypes(), txSubOpts.SignatureServiceOptions.DistributionSignerType) { - return fmt.Errorf("invalid distribution account signer type %q", txSubOpts.SignatureServiceOptions.DistributionSignerType) - } - txSubOpts.SignatureServiceOptions.DBConnectionPool = tssDBConnectionPool - - horizonClient := &horizonclient.Client{ - HorizonURL: txSubOpts.HorizonURL, - HTTP: httpclient.DefaultClient(), - } - - distAccResolver, err := signing.NewDistributionAccountResolver(signing.DistributionAccountResolverOptions{ - AdminDBConnectionPool: adminDBConnectionPool, - HostDistributionAccountPublicKey: distAccResolverOpts.HostDistributionAccountPublicKey, - }) - if err != nil { - return fmt.Errorf("creating a new distribution account resolver instance: %w", err) - } - txSubOpts.SignatureServiceOptions.DistributionAccountResolver = distAccResolver - - ledgerNumberTracker, err := preconditions.NewLedgerNumberTracker(horizonClient) - if err != nil { - return fmt.Errorf("grabbing ledger number tracker instance: %w", err) - } - txSubOpts.SignatureServiceOptions.LedgerNumberTracker = ledgerNumberTracker - - signatureService, err := signing.NewSignatureService(txSubOpts.SignatureServiceOptions) - if err != nil { - return fmt.Errorf("grabbing signature service instance: %w", err) - } - - txSubmitterEngine := engine.SubmitterEngine{ - HorizonClient: horizonClient, - LedgerNumberTracker: ledgerNumberTracker, - SignatureService: signatureService, - MaxBaseFee: txSubOpts.MaxBaseFee, - } - - p := provisioning.NewManager( - provisioning.WithDatabase(adminDBConnectionPool), - provisioning.WithMessengerClient(messengerClient), - provisioning.WithTenantManager(tenant.NewManager(tenant.WithDatabase(adminDBConnectionPool))), - provisioning.WithSubmitterEngine(txSubmitterEngine), - provisioning.WithNativeAssetBootstrapAmount(tenantsOpts.TenantAccountNativeAssetBootstrapAmount), - ) - - t, err := p.ProvisionNewTenant(ctx, tenantName, userFirstName, userLastName, userEmail, organizationName, *tenantsOpts.SDPUIBaseURL, tenantsOpts.NetworkType) - if err != nil { - return fmt.Errorf("adding tenant with name %s: %w", tenantName, err) - } - - log.Ctx(ctx).Infof("tenant %s added successfully", tenantName) - log.Ctx(ctx).Infof("tenant ID: %s", t.ID) - - return nil -} diff --git a/stellar-multitenant/pkg/cli/add_tenants_test.go b/stellar-multitenant/pkg/cli/add_tenants_test.go deleted file mode 100644 index b99f41951..000000000 --- a/stellar-multitenant/pkg/cli/add_tenants_test.go +++ /dev/null @@ -1,404 +0,0 @@ -package cli - -import ( - "context" - "errors" - "fmt" - "net/url" - "slices" - "strings" - "testing" - - migrate "github.com/rubenv/sql-migrate" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/stellar/go/clients/horizonclient" - "github.com/stellar/go/keypair" - "github.com/stellar/go/network" - "github.com/stellar/go/support/log" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - cmdDB "github.com/stellar/stellar-disbursement-platform-backend/cmd/db" - "github.com/stellar/stellar-disbursement-platform-backend/db" - "github.com/stellar/stellar-disbursement-platform-backend/db/dbtest" - "github.com/stellar/stellar-disbursement-platform-backend/db/router" - di "github.com/stellar/stellar-disbursement-platform-backend/internal/dependencyinjection" - "github.com/stellar/stellar-disbursement-platform-backend/internal/message" - "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine/signing" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" -) - -// AssertEntriesContains asserts that the entries []logrus.Entry slice contain the provided message. -var AssertEntriesContains = func(t *testing.T, entries []logrus.Entry, message string) { - t.Helper() - - entriesContain := slices.ContainsFunc(entries, func(e logrus.Entry) bool { - return e.Message == message - }) - - assert.True(t, entriesContain, fmt.Sprintf("entries should contain message: %s", message)) -} - -func Test_validateTenantNameArg(t *testing.T) { - testCases := []struct { - name string - err error - }{ - { - name: "orgname", - err: nil, - }, - { - name: "orgname-ukraine", - err: nil, - }, - { - name: "ORGNAME", - err: errors.New(`invalid tenant name "ORGNAME". It should only contains lower case letters and dash (-)`), - }, - { - name: "orgname org", - err: errors.New(`invalid tenant name "orgname org". It should only contains lower case letters and dash (-)`), - }, - { - name: "orgname126", - err: errors.New(`invalid tenant name "orgname126". It should only contains lower case letters and dash (-)`), - }, - { - name: "@rgn#ame$", - err: errors.New(`invalid tenant name "@rgn#ame$". It should only contains lower case letters and dash (-)`), - }, - { - name: "orgname_ukraine", - err: errors.New(`invalid tenant name "orgname_ukraine". It should only contains lower case letters and dash (-)`), - }, - } - - for _, tc := range testCases { - err := validateTenantNameArg(&cobra.Command{}, []string{tc.name}) - if tc.err != nil { - assert.Equal(t, tc.err, err) - } else { - assert.Nil(t, err) - } - } -} - -func Test_executeAddTenant(t *testing.T) { - dbt := dbtest.Open(t) - defer dbt.Close() - dbConnectionPool, err := db.OpenDBConnectionPool(dbt.DSN) - require.NoError(t, err) - defer dbConnectionPool.Close() - - messengerClientMock := &message.MessengerClientMock{} - messengerClientMock. - On("SendMessage", mock.AnythingOfType("message.Message")). - Return(nil) - - ctx := context.Background() - - tenantName := "myorg" - userFirstName := "First" - userLastName := "Last" - userEmail := "email@email.com" - organizationName := "My Org" - uiBaseURL := "http://localhost:3000" - networkType := "testnet" - encryptionPassphrase := keypair.MustRandom().Seed() - distributionAcc := keypair.MustRandom() - distributionAccPrivKey := distributionAcc.Seed() - distributionAccPubKey := distributionAcc.Address() - - distAccResolverOpts := signing.DistributionAccountResolverOptions{ - AdminDBConnectionPool: dbConnectionPool, - HostDistributionAccountPublicKey: distributionAccPubKey, - } - distAccResolver, err := signing.NewDistributionAccountResolver(distAccResolverOpts) - require.NoError(t, err) - - txSubOpts := di.TxSubmitterEngineOptions{ - SignatureServiceOptions: signing.SignatureServiceOptions{ - DistributionSignerType: signing.DistributionAccountEnvSignatureClientType, - DistAccEncryptionPassphrase: encryptionPassphrase, - ChAccEncryptionPassphrase: encryptionPassphrase, - DistributionPrivateKey: distributionAccPrivKey, - NetworkPassphrase: network.TestNetworkPassphrase, - DistributionAccountResolver: distAccResolver, - DBConnectionPool: dbConnectionPool, - }, - HorizonURL: horizonclient.DefaultTestNetClient.HorizonURL, - MaxBaseFee: 100, - } - - tenantsOpts := AddTenantsCommandOptions{ - SDPUIBaseURL: &uiBaseURL, - NetworkType: networkType, - TenantAccountNativeAssetBootstrapAmount: tenant.MinTenantDistributionAccountAmount, - } - - t.Run("adds a new tenant successfully", func(t *testing.T) { - di.ClearInstancesTestHelper(t) - tenant.DeleteAllTenantsFixture(t, ctx, dbConnectionPool) - - getEntries := log.DefaultLogger.StartTest(log.InfoLevel) - - err := executeAddTenant(ctx, dbConnectionPool, dbConnectionPool, tenantName, userFirstName, userLastName, userEmail, organizationName, messengerClientMock, tenantsOpts, txSubOpts, distAccResolverOpts) - assert.Nil(t, err) - - const q = "SELECT id FROM tenants WHERE name = $1" - var tenantID string - err = dbConnectionPool.GetContext(ctx, &tenantID, q, tenantName) - require.NoError(t, err) - - entries := getEntries() - AssertEntriesContains(t, entries, "tenant myorg added successfully") - AssertEntriesContains(t, entries, fmt.Sprintf("tenant ID: %s", tenantID)) - }) - - t.Run("duplicated tenant name", func(t *testing.T) { - di.ClearInstancesTestHelper(t) - tenant.DeleteAllTenantsFixture(t, ctx, dbConnectionPool) - - getEntries := log.DefaultLogger.StartTest(log.DebugLevel) - - err := executeAddTenant(ctx, dbConnectionPool, dbConnectionPool, tenantName, userFirstName, userLastName, userEmail, organizationName, messengerClientMock, tenantsOpts, txSubOpts, distAccResolverOpts) - assert.Nil(t, err) - - err = executeAddTenant(ctx, dbConnectionPool, dbConnectionPool, tenantName, userFirstName, userLastName, userEmail, organizationName, messengerClientMock, tenantsOpts, txSubOpts, distAccResolverOpts) - assert.ErrorIs(t, err, tenant.ErrDuplicatedTenantName) - - const q = "SELECT id FROM tenants WHERE name = $1" - var tenantID string - err = dbConnectionPool.GetContext(ctx, &tenantID, q, tenantName) - require.NoError(t, err) - - entries := getEntries() - AssertEntriesContains(t, entries, "tenant myorg added successfully") - AssertEntriesContains(t, entries, fmt.Sprintf("tenant ID: %s", tenantID)) - }) - - messengerClientMock.AssertExpectations(t) -} - -func Test_AddTenantsCmd(t *testing.T) { - dbt := dbtest.OpenWithAdminMigrationsOnly(t) - defer dbt.Close() - dbConnectionPool, outerErr := db.OpenDBConnectionPool(dbt.DSN) - require.NoError(t, outerErr) - defer dbConnectionPool.Close() - - ctx := context.Background() - - // Run TSS migrations in tss schema: - manager, err := cmdDB.NewTSSDatabaseMigrationManager(dbConnectionPool) - require.NoError(t, err) - err = manager.CreateTSSSchemaIfNeeded(ctx) - require.NoError(t, err) - tssDNS, err := router.GetDNSForTSS(dbt.DSN) - require.NoError(t, err) - err = cmdDB.RunTSSMigrations(ctx, tssDNS, migrate.Up, 0) - require.NoError(t, err) - - t.Setenv("DISTRIBUTION_SIGNER_TYPE", "DISTRIBUTION_ACCOUNT_ENV") - encryptionPassphrase := keypair.MustRandom().Seed() - t.Setenv("CHANNEL_ACCOUNT_ENCRYPTION_PASSPHRASE", encryptionPassphrase) - t.Setenv("DISTRIBUTION_ACCOUNT_ENCRYPTION_PASSPHRASE", encryptionPassphrase) - t.Setenv("DISTRIBUTION_PUBLIC_KEY", "GDAZUHI4ARV73G3FI4JEZP57MPQTJ5I6BW7VZLNVHQJPANKPUGY2SDUY") - t.Setenv("DISTRIBUTION_SEED", "SBIIOER5NAQTMFIPCRDDSQSCIMVPMIEPZEIZSBIGYPDCU6I5LLRSODK7") - - t.Run("shows usage", func(t *testing.T) { - di.ClearInstancesTestHelper(t) - - out := new(strings.Builder) - mockCmd := cobra.Command{} - mockCmd.AddCommand(AddTenantsCmd()) - mockCmd.SetOut(out) - mockCmd.SetErr(out) - mockCmd.SetArgs([]string{"add-tenants"}) - err := mockCmd.ExecuteContext(ctx) - assert.EqualError(t, err, "accepts 5 arg(s), received 0") - - expectErrMsg := "Error: accepts 5 arg(s), received 0" - expectUsageMessages := []string{ - "Usage:", - "add-tenants [flags]", - "Examples:", - "add-tenants [tenant name] [user first name] [user last name] [user email] [organization name]", - "Flags:", - "--aws-access-key-id string", - "--aws-region string", - "--aws-secret-access-key string", - "--channel-account-encryption-passphrase string", - "--distribution-account-encryption-passphrase string", - "--distribution-public-key string", - "--distribution-seed string", - "--distribution-signer-type string", - "--email-sender-type string", - "-h, --help", - "--horizon-url string", - "--max-base-fee int", - "--network-passphrase string", - "--network-type string", - "--sdp-ui-base-url string", - "--tenant-xlm-bootstrap-amount int", - } - outputStr := out.String() - assert.Contains(t, outputStr, expectErrMsg) - for _, expected := range expectUsageMessages { - assert.Contains(t, outputStr, expected) - } - - out.Reset() - mockCmd.SetArgs([]string{"add-tenants", "--help"}) - err = mockCmd.ExecuteContext(ctx) - require.NoError(t, err) - outputStr = out.String() - for _, expected := range expectUsageMessages { - assert.Contains(t, outputStr, expected) - } - }) - - t.Run("adds new tenant successfully testnet", func(t *testing.T) { - di.ClearInstancesTestHelper(t) - - tenantName := "unhcr" - userFirstName := "First" - userLastName := "Last" - userEmail := "email@email.com" - organizationName := "UNHCR" - - out := new(strings.Builder) - rootCmd := rootCmd() - rootCmd.AddCommand(AddTenantsCmd()) - rootCmd.SetOut(out) - rootCmd.SetErr(out) - rootCmd.SetArgs([]string{ - "add-tenants", tenantName, userFirstName, userLastName, userEmail, organizationName, - "--email-sender-type", "DRY_RUN", - "--network-type", "testnet", - "--multitenant-db-url", dbt.DSN, - }) - getEntries := log.DefaultLogger.StartTest(log.InfoLevel) - - err := rootCmd.ExecuteContext(ctx) - require.NoError(t, err) - assert.Empty(t, out.String()) - - const q = "SELECT id FROM tenants WHERE name = $1" - var tenantID string - err = dbConnectionPool.GetContext(ctx, &tenantID, q, tenantName) - require.NoError(t, err) - - entries := getEntries() - AssertEntriesContains(t, entries, "tenant unhcr added successfully") - AssertEntriesContains(t, entries, fmt.Sprintf("tenant ID: %s", tenantID)) - - // Connecting to the new schema - schemaName := fmt.Sprintf("sdp_%s", tenantName) - dataSourceName, err := dbConnectionPool.DSN(ctx) - require.NoError(t, err) - u, err := url.Parse(dataSourceName) - require.NoError(t, err) - uq := u.Query() - uq.Set("search_path", schemaName) - u.RawQuery = uq.Encode() - - tenantSchemaConnectionPool, err := db.OpenDBConnectionPool(u.String()) - require.NoError(t, err) - defer tenantSchemaConnectionPool.Close() - - expectedTablesAfterMigrationsApplied := []string{ - "assets", - "auth_migrations", - "auth_user_mfa_codes", - "auth_user_password_reset", - "auth_users", - "countries", - "disbursements", - "sdp_migrations", - "messages", - "organizations", - "payments", - "receiver_verifications", - "receiver_wallets", - "receivers", - "wallets", - "wallets_assets", - } - tenant.TenantSchemaMatchTablesFixture(t, ctx, tenantSchemaConnectionPool, schemaName, expectedTablesAfterMigrationsApplied) - tenant.AssertRegisteredAssetsFixture(t, ctx, tenantSchemaConnectionPool, []string{"USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5", "XLM:"}) - tenant.AssertRegisteredWalletsFixture(t, ctx, tenantSchemaConnectionPool, []string{"Demo Wallet", "Vibrant Assist"}) - tenant.AssertRegisteredUserFixture(t, ctx, tenantSchemaConnectionPool, userFirstName, userLastName, userEmail) - }) - - t.Run("adds new tenant successfully pubnet", func(t *testing.T) { - di.ClearInstancesTestHelper(t) - - tenantName := "irc" - userFirstName := "First" - userLastName := "Last" - userEmail := "email@email.com" - organizationName := "UNHCR" - - out := new(strings.Builder) - rootCmd := rootCmd() - rootCmd.AddCommand(AddTenantsCmd()) - rootCmd.SetOut(out) - rootCmd.SetErr(out) - rootCmd.SetArgs([]string{"add-tenants", tenantName, userFirstName, userLastName, userEmail, organizationName, "--email-sender-type", "DRY_RUN", "--network-type", "pubnet", "--multitenant-db-url", dbt.DSN}) - getEntries := log.DefaultLogger.StartTest(log.InfoLevel) - - err := rootCmd.ExecuteContext(ctx) - require.NoError(t, err) - assert.Empty(t, out.String()) - - const q = "SELECT id FROM tenants WHERE name = $1" - var tenantID string - err = dbConnectionPool.GetContext(ctx, &tenantID, q, tenantName) - require.NoError(t, err) - - entries := getEntries() - AssertEntriesContains(t, entries, "tenant irc added successfully") - AssertEntriesContains(t, entries, fmt.Sprintf("tenant ID: %s", tenantID)) - - // Connecting to the new schema - schemaName := fmt.Sprintf("sdp_%s", tenantName) - dataSourceName, err := dbConnectionPool.DSN(ctx) - require.NoError(t, err) - u, err := url.Parse(dataSourceName) - require.NoError(t, err) - uq := u.Query() - uq.Set("search_path", schemaName) - u.RawQuery = uq.Encode() - - tenantSchemaConnectionPool, err := db.OpenDBConnectionPool(u.String()) - require.NoError(t, err) - defer tenantSchemaConnectionPool.Close() - - expectedTablesAfterMigrationsApplied := []string{ - "assets", - "auth_migrations", - "auth_user_mfa_codes", - "auth_user_password_reset", - "auth_users", - "countries", - "disbursements", - "sdp_migrations", - "messages", - "organizations", - "payments", - "receiver_verifications", - "receiver_wallets", - "receivers", - "wallets", - "wallets_assets", - } - tenant.TenantSchemaMatchTablesFixture(t, ctx, tenantSchemaConnectionPool, schemaName, expectedTablesAfterMigrationsApplied) - tenant.AssertRegisteredAssetsFixture(t, ctx, tenantSchemaConnectionPool, []string{"USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", "XLM:"}) - tenant.AssertRegisteredWalletsFixture(t, ctx, tenantSchemaConnectionPool, []string{"Freedom Wallet", "Vibrant Assist RC", "Vibrant Assist"}) - tenant.AssertRegisteredUserFixture(t, ctx, tenantSchemaConnectionPool, userFirstName, userLastName, userEmail) - }) -} diff --git a/stellar-multitenant/pkg/cli/config_tenant.go b/stellar-multitenant/pkg/cli/config_tenant.go deleted file mode 100644 index 3aefabc66..000000000 --- a/stellar-multitenant/pkg/cli/config_tenant.go +++ /dev/null @@ -1,127 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "go/types" - - "github.com/spf13/cobra" - "github.com/stellar/go/support/config" - "github.com/stellar/go/support/log" - - cmdUtils "github.com/stellar/stellar-disbursement-platform-backend/cmd/utils" - "github.com/stellar/stellar-disbursement-platform-backend/db" - di "github.com/stellar/stellar-disbursement-platform-backend/internal/dependencyinjection" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/cli/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" -) - -type tenantOptions struct { - ID string - EmailSenderType *tenant.EmailSenderType - SMSSenderType *tenant.SMSSenderType - BaseURL *string - SDPUIBaseURL *string -} - -func ConfigTenantCmd() *cobra.Command { - to := tenantOptions{} - configOptions := config.ConfigOptions{ - { - Name: "tenant-id", - Usage: "The ID of the Tenant to configure.", - OptType: types.String, - ConfigKey: &to.ID, - Required: true, - }, - { - Name: "email-sender-type", - Usage: `The messenger type used to send invitations to new dashboard users. Options: "AWS_EMAIL", "DRY_RUN"`, - OptType: types.String, - CustomSetValue: utils.SetConfigOptionEmailSenderType, - ConfigKey: &to.EmailSenderType, - Required: false, - }, - { - Name: "sms-sender-type", - Usage: `SMS Sender Type. Options: "TWILIO_SMS", "AWS_SMS", "DRY_RUN"`, - OptType: types.String, - CustomSetValue: utils.SetConfigOptionSMSSenderType, - ConfigKey: &to.SMSSenderType, - Required: false, - }, - { - Name: "base-url", - Usage: "The SDP backend server's base URL.", - OptType: types.String, - CustomSetValue: utils.SetConfigOptionURLString, - ConfigKey: &to.BaseURL, - Required: false, - }, - { - Name: "sdp-ui-base-url", - Usage: "The SDP UI/dashboard Base URL.", - OptType: types.String, - CustomSetValue: utils.SetConfigOptionURLString, - ConfigKey: &to.SDPUIBaseURL, - Required: false, - }, - } - - var adminDBConnectionPool db.DBConnectionPool - cmd := cobra.Command{ - Use: "config-tenant", - Short: "Configure an existing tenant", - Long: "Configure an existing tenant by updating their existing configuration", - Aliases: []string{"ct"}, - PersistentPreRun: func(cmd *cobra.Command, args []string) { - cmdUtils.PropagatePersistentPreRun(cmd, args) - configOptions.Require() - err := configOptions.SetValues() - if err != nil { - log.Ctx(cmd.Context()).Fatalf("Error setting values of config options: %s", err.Error()) - } - }, - Run: func(cmd *cobra.Command, args []string) { - ctx := cmd.Context() - - var err error - // TODO: in SDP-874, make sure to add metrics to this DB options, like we do in cmd/serve.go - adminDBConnectionPool, err = di.NewAdminDBConnectionPool(ctx, di.DBConnectionPoolOptions{DatabaseURL: globalOptions.multitenantDbURL}) - if err != nil { - log.Ctx(ctx).Fatal("getting admin db connection pool", err) - } - - if err := executeConfigTenant(ctx, &to, adminDBConnectionPool); err != nil { - log.Ctx(ctx).Fatal(err) - } - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - di.CleanupInstanceByValue(cmd.Context(), adminDBConnectionPool) - }, - } - - if err := configOptions.Init(&cmd); err != nil { - log.Ctx(cmd.Context()).Fatalf("initializing ConfigTenantCmd config options: %v", err) - } - - return &cmd -} - -func executeConfigTenant(ctx context.Context, to *tenantOptions, dbConnectionPool db.DBConnectionPool) error { - m := tenant.NewManager(tenant.WithDatabase(dbConnectionPool)) - _, err := m.UpdateTenantConfig(ctx, &tenant.TenantUpdate{ - ID: to.ID, - EmailSenderType: to.EmailSenderType, - SMSSenderType: to.SMSSenderType, - BaseURL: to.BaseURL, - SDPUIBaseURL: to.SDPUIBaseURL, - }) - if err != nil { - return fmt.Errorf("updating tenant config: %w", err) - } - - log.Ctx(ctx).Infof("tenant ID %s configuration updated successfully", to.ID) - - return nil -} diff --git a/stellar-multitenant/pkg/cli/migrate.go b/stellar-multitenant/pkg/cli/migrate.go deleted file mode 100644 index 0cf8e8906..000000000 --- a/stellar-multitenant/pkg/cli/migrate.go +++ /dev/null @@ -1,26 +0,0 @@ -package cli - -import ( - "context" - - cmdDB "github.com/stellar/stellar-disbursement-platform-backend/cmd/db" - "github.com/stellar/stellar-disbursement-platform-backend/db" - adminMigrations "github.com/stellar/stellar-disbursement-platform-backend/db/migrations/admin-migrations" - - migrate "github.com/rubenv/sql-migrate" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func MigrateCmd(databaseFlagName string) *cobra.Command { - executeMigrationsFn := func(ctx context.Context, dir migrate.MigrationDirection, count int) error { - dbURL := globalOptions.multitenantDbURL - if globalOptions.multitenantDbURL == "" { - dbURL = viper.GetString(databaseFlagName) - } - - return cmdDB.ExecuteMigrations(context.Background(), dbURL, dir, count, adminMigrations.FS, db.StellarAdminMigrationsTableName) - } - - return cmdDB.MigrateCmd(context.Background(), executeMigrationsFn) -} diff --git a/stellar-multitenant/pkg/cli/migrate_test.go b/stellar-multitenant/pkg/cli/migrate_test.go deleted file mode 100644 index 2976fe70e..000000000 --- a/stellar-multitenant/pkg/cli/migrate_test.go +++ /dev/null @@ -1,219 +0,0 @@ -package cli - -import ( - "context" - "database/sql" - "fmt" - "strings" - "testing" - - migrate "github.com/rubenv/sql-migrate" - "github.com/spf13/cobra" - "github.com/spf13/viper" - stellardbtest "github.com/stellar/go/support/db/dbtest" - "github.com/stellar/go/support/log" - dbpkg "github.com/stellar/stellar-disbursement-platform-backend/db" - "github.com/stellar/stellar-disbursement-platform-backend/db/dbtest" - adminMigrations "github.com/stellar/stellar-disbursement-platform-backend/db/migrations/admin-migrations" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func getMigrationsApplied(t *testing.T, ctx context.Context, db *sql.DB) []string { - rows, err := db.QueryContext(ctx, fmt.Sprintf("SELECT id FROM %s", dbpkg.StellarAdminMigrationsTableName)) - require.NoError(t, err) - - defer rows.Close() - - ids := []string{} - for rows.Next() { - var id string - err := rows.Scan(&id) - require.NoError(t, err) - - ids = append(ids, id) - } - - require.NoError(t, rows.Err()) - - return ids -} - -func Test_MigrateCmd(t *testing.T) { - testCases := []struct { - name string - args []string - envVars map[string]string - expect string - expectError string - preRunFunc func(*testing.T, *stellardbtest.DB) - postRunFunc func(*sql.DB) - }{ - { - name: "test help command", - args: []string{"migrate", "--help"}, - expect: "Schema migration helpers", - }, - { - name: "test short help command", - args: []string{"migrate", "-h"}, - expect: "Schema migration helpers", - }, - { - name: "test migrate up successfully", - args: []string{"--multitenant-db-url", "", "migrate", "up", "1"}, - expect: "Successfully applied 1 migrations up.", - postRunFunc: func(db *sql.DB) { - ids := getMigrationsApplied(t, context.Background(), db) - assert.Equal(t, []string{"2023-10-16.0.add-tenants-table.sql"}, ids) - }, - }, - { - name: "test migrate up successfully when using the MULTITENANT_DB_URL env var", - args: []string{"migrate", "up", "1"}, - envVars: map[string]string{"MULTITENANT_DB_URL": ""}, - expect: "Successfully applied 1 migrations up.", - postRunFunc: func(db *sql.DB) { - ids := getMigrationsApplied(t, context.Background(), db) - assert.Equal(t, []string{"2023-10-16.0.add-tenants-table.sql"}, ids) - }, - }, - { - name: "test apply migrations when no number of migration is specified", - args: []string{"--multitenant-db-url", "", "migrate", "up"}, - expect: "Successfully applied", - expectError: "", - }, - { - name: "test migrate down usage", - args: []string{"migrate", "down"}, - expect: "Usage:\n mtn migrate down [count] [flags]\n\nFlags:\n -h, --help help for down\n\nGlobal Flags:\n --multitenant-db-url string Postgres DB URL (MULTITENANT_DB_URL) (default \"postgres://postgres:postgres@localhost:5432/sdp_main?sslmode=disable\")\n\n", - expectError: "accepts 1 arg(s), received 0", - }, - { - name: "test migrate down successfully", - args: []string{"--multitenant-db-url", "", "migrate", "down", "1"}, - expect: "Successfully applied 1 migrations down.", - preRunFunc: func(t *testing.T, db *stellardbtest.DB) { - _, err := dbpkg.Migrate(db.DSN, migrate.Up, 1, adminMigrations.FS, dbpkg.StellarAdminMigrationsTableName) - require.NoError(t, err) - - conn := db.Open() - defer conn.Close() - - ids := getMigrationsApplied(t, context.Background(), conn.DB) - assert.Equal(t, []string{"2023-10-16.0.add-tenants-table.sql"}, ids) - }, - postRunFunc: func(db *sql.DB) { - ids := getMigrationsApplied(t, context.Background(), db) - assert.Equal(t, []string{}, ids) - }, - }, - { - name: "test migrate up successfully when using the MULTITENANT_DB_URL env var", - args: []string{"migrate", "down", "1"}, - envVars: map[string]string{"MULTITENANT_DB_URL": ""}, - expect: "Successfully applied 1 migrations down.", - preRunFunc: func(t *testing.T, db *stellardbtest.DB) { - _, err := dbpkg.Migrate(db.DSN, migrate.Up, 1, adminMigrations.FS, dbpkg.StellarAdminMigrationsTableName) - require.NoError(t, err) - - conn := db.Open() - defer conn.Close() - - ids := getMigrationsApplied(t, context.Background(), conn.DB) - assert.Equal(t, []string{"2023-10-16.0.add-tenants-table.sql"}, ids) - }, - postRunFunc: func(db *sql.DB) { - ids := getMigrationsApplied(t, context.Background(), db) - assert.Equal(t, []string{}, ids) - }, - }, - } - - for _, tc := range testCases { - db := dbtest.OpenWithoutMigrations(t) - - if len(tc.args) >= 3 && tc.args[0] == "--multitenant-db-url" { - tc.args[1] = db.DSN - } - - t.Run(tc.name, func(t *testing.T) { - if tc.preRunFunc != nil { - tc.preRunFunc(t, db) - } - - for key, value := range tc.envVars { - if key == "MULTITENANT_DB_URL" { - value = db.DSN - } - t.Setenv(key, value) - } - - buf := new(strings.Builder) - log.DefaultLogger.SetLevel(log.DebugLevel) - log.DefaultLogger.SetOutput(buf) - - rootCmd := rootCmd() - rootCmd.SetOut(buf) - rootCmd.AddCommand(MigrateCmd("")) - rootCmd.SetArgs(tc.args) - - err := rootCmd.Execute() - if tc.expectError != "" { - assert.EqualError(t, err, tc.expectError) - } else { - require.NoError(t, err) - } - - output := buf.String() - if tc.expect != "" { - assert.Contains(t, output, tc.expect) - } - - if tc.postRunFunc != nil { - conn := db.Open() - tc.postRunFunc(conn.DB) - conn.Close() - } - }) - - db.Close() - } -} - -func Test_MigrateCmd_databaseFlagName(t *testing.T) { - globalOptions = globalOptionsType{} - - dbt := dbtest.OpenWithoutMigrations(t) - defer dbt.Close() - - testCmd := &cobra.Command{ - Use: "testcmd", - Run: func(cmd *cobra.Command, args []string) { - err := cmd.Help() - require.NoError(t, err) - }, - } - - testCmd.PersistentFlags().String("db-url", dbt.DSN, "") - - err := viper.BindPFlag("db-url", testCmd.PersistentFlags().Lookup("db-url")) - require.NoError(t, err) - - err = viper.BindEnv("DB_URL", dbt.DSN) - require.NoError(t, err) - - testCmd.AddCommand(MigrateCmd("db-url")) - testCmd.SetArgs([]string{"migrate", "up", "1"}) - - buf := new(strings.Builder) - log.DefaultLogger.SetOutput(buf) - log.DefaultLogger.SetLevel(log.InfoLevel) - testCmd.SetOut(buf) - - err = testCmd.Execute() - require.NoError(t, err) - - assert.Contains(t, buf.String(), "Successfully applied 1 migrations up.") -} diff --git a/stellar-multitenant/pkg/cli/root.go b/stellar-multitenant/pkg/cli/root.go deleted file mode 100644 index fd9ba4cba..000000000 --- a/stellar-multitenant/pkg/cli/root.go +++ /dev/null @@ -1,70 +0,0 @@ -package cli - -import ( - "go/types" - - "github.com/spf13/cobra" - "github.com/stellar/go/support/config" - "github.com/stellar/go/support/log" -) - -type globalOptionsType struct { - version string - gitCommit string - multitenantDbURL string -} - -var globalOptions globalOptionsType - -func rootCmd() *cobra.Command { - configOptions := config.ConfigOptions{ - { - Name: "multitenant-db-url", - Usage: "Postgres DB URL", - OptType: types.String, - FlagDefault: "postgres://postgres:postgres@localhost:5432/sdp_main?sslmode=disable", - ConfigKey: &globalOptions.multitenantDbURL, - Required: true, - }, - } - - cmd := &cobra.Command{ - Use: "mtn", - Short: "Stellar Disbursement Platform Multi-tenant Configuration.", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - ctx := cmd.Context() - configOptions.Require() - err := configOptions.SetValues() - if err != nil { - log.Ctx(ctx).Fatalf("Error setting values of config options: %s", err.Error()) - } - - log.Ctx(ctx).Info("Version: ", globalOptions.version) - log.Ctx(ctx).Info("GitCommit: ", globalOptions.gitCommit) - }, - Run: func(cmd *cobra.Command, args []string) { - if err := cmd.Help(); err != nil { - log.Ctx(cmd.Context()).Fatalf("Error calling help command: %s", err.Error()) - } - }, - } - - if err := configOptions.Init(cmd); err != nil { - log.Ctx(cmd.Context()).Fatalf("Error initializing a config option: %s", err.Error()) - } - - return cmd -} - -func SetupCLI(version, gitCommit string) *cobra.Command { - globalOptions.version = version - globalOptions.gitCommit = gitCommit - - cmd := rootCmd() - - cmd.AddCommand(MigrateCmd("")) - cmd.AddCommand(AddTenantsCmd()) - cmd.AddCommand(ConfigTenantCmd()) - - return cmd -} diff --git a/stellar-multitenant/pkg/cli/utils/custom_set_value.go b/stellar-multitenant/pkg/cli/utils/custom_set_value.go deleted file mode 100644 index 79456c145..000000000 --- a/stellar-multitenant/pkg/cli/utils/custom_set_value.go +++ /dev/null @@ -1,89 +0,0 @@ -package utils - -import ( - "fmt" - "net/url" - - "github.com/spf13/viper" - "github.com/stellar/go/support/config" - "github.com/stellar/stellar-disbursement-platform-backend/internal/message" - "github.com/stellar/stellar-disbursement-platform-backend/internal/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" -) - -func SetConfigOptionEmailSenderType(co *config.ConfigOption) error { - senderType := viper.GetString(co.Name) - if senderType == "" { - return nil - } - - esType, err := tenant.ParseEmailSenderType(senderType) - if err != nil { - return fmt.Errorf("couldn't parse messenger type: %w", err) - } - - *(co.ConfigKey.(**tenant.EmailSenderType)) = &esType - return nil -} - -func SetConfigOptionSMSSenderType(co *config.ConfigOption) error { - senderType := viper.GetString(co.Name) - if senderType == "" { - return nil - } - - smsSenderType, err := tenant.ParseSMSSenderType(senderType) - if err != nil { - return fmt.Errorf("couldn't parse messenger type: %w", err) - } - - *(co.ConfigKey.(**tenant.SMSSenderType)) = &smsSenderType - return nil -} - -func SetConfigOptionURLString(co *config.ConfigOption) error { - u := viper.GetString(co.Name) - if u == "" { - return nil - } - - _, err := url.ParseRequestURI(u) - if err != nil { - return fmt.Errorf("error parsing ui base url: %w", err) - } - - key, ok := co.ConfigKey.(**string) - if !ok { - return fmt.Errorf("the expected type for this config key is a string, but got a %T instead", co.ConfigKey) - } - *key = &u - - return nil -} - -func SetConfigOptionNetworkType(co *config.ConfigOption) error { - networkType := viper.GetString(co.Name) - value, err := utils.GetNetworkTypeFromString(networkType) - if err != nil { - return fmt.Errorf("getting network type from string: %w", err) - } - - key, ok := co.ConfigKey.(*string) - if !ok { - return fmt.Errorf("the expected type for this config key is a string, but got a %T instead", co.ConfigKey) - } - *key = string(value) - return nil -} - -func SetConfigOptionMessengerType(co *config.ConfigOption) error { - senderType := viper.GetString(co.Name) - - messengerType, err := message.ParseMessengerType(senderType) - if err != nil { - return fmt.Errorf("couldn't parse messenger type: %w", err) - } - - *(co.ConfigKey.(*message.MessengerType)) = messengerType - return nil -} diff --git a/stellar-multitenant/pkg/serve/serve.go b/stellar-multitenant/pkg/serve/serve.go index 5e292a9a1..bd92ee2d9 100644 --- a/stellar-multitenant/pkg/serve/serve.go +++ b/stellar-multitenant/pkg/serve/serve.go @@ -15,8 +15,8 @@ import ( "github.com/stellar/stellar-disbursement-platform-backend/internal/serve/middleware" "github.com/stellar/stellar-disbursement-platform-backend/internal/transactionsubmission/engine" "github.com/stellar/stellar-disbursement-platform-backend/internal/utils" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/httphandler" - "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/internal/provisioning" + "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/internal/httphandler" + "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/internal/provisioning" "github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant" )