Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Account v1 readiness #3236

Merged
merged 11 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 49 additions & 59 deletions pkg/acceptance/helpers/account_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/collections"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/snowflakeroles"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk"
"github.com/snowflakedb/gosnowflake"
Expand Down Expand Up @@ -52,38 +51,31 @@ func (c *AccountClient) GetAccountIdentifier(t *testing.T) sdk.AccountIdentifier
return sdk.AccountIdentifier{}
}

func (c *AccountClient) Create(t *testing.T) *sdk.Account {
func (c *AccountClient) Create(t *testing.T) (*sdk.Account, func()) {
t.Helper()
id := c.ids.RandomAccountObjectIdentifier()
name := c.ids.Alpha()
password := random.Password()
email := random.Email()
privateKey := random.GenerateRSAPrivateKey(t)
publicKey, _ := random.GenerateRSAPublicKeyFromPrivateKey(t, privateKey)

err := c.client().Create(context.Background(), id, &sdk.CreateAccountOptions{
AdminName: name,
AdminPassword: sdk.String(password),
Email: email,
Edition: sdk.EditionStandard,
return c.CreateWithRequest(t, id, &sdk.CreateAccountOptions{
AdminName: name,
AdminRSAPublicKey: sdk.String(publicKey),
Email: email,
Edition: sdk.EditionStandard,
})
require.NoError(t, err)
t.Cleanup(c.DropFunc(t, id))

account, err := c.client().ShowByID(context.Background(), id)
require.NoError(t, err)

return account
}

func (c *AccountClient) CreateWithRequest(t *testing.T, id sdk.AccountObjectIdentifier, opts *sdk.CreateAccountOptions) *sdk.Account {
func (c *AccountClient) CreateWithRequest(t *testing.T, id sdk.AccountObjectIdentifier, opts *sdk.CreateAccountOptions) (*sdk.Account, func()) {
t.Helper()
err := c.client().Create(context.Background(), id, opts)
require.NoError(t, err)
t.Cleanup(c.DropFunc(t, id))

account, err := c.client().ShowByID(context.Background(), id)
require.NoError(t, err)

return account
return account, c.DropFunc(t, id)
}

func (c *AccountClient) Alter(t *testing.T, opts *sdk.AlterAccountOptions) {
Expand All @@ -92,6 +84,32 @@ func (c *AccountClient) Alter(t *testing.T, opts *sdk.AlterAccountOptions) {
require.NoError(t, err)
}

func (c *AccountClient) UnsetPoliciesFunc(t *testing.T) func() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this method is dangerous because it can alter the "wrong" account. We should at least have some safeguards (for now).

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed SelfAlter tests for account are skipped. For now it's pointing to the general ticket (but mentioned it explicitly in the acc criteria).

t.Helper()
return func() {
_ = c.client().Alter(context.Background(), &sdk.AlterAccountOptions{
Unset: &sdk.AccountUnset{
PackagesPolicy: sdk.Bool(true),
},
})
_ = c.client().Alter(context.Background(), &sdk.AlterAccountOptions{
Unset: &sdk.AccountUnset{
PasswordPolicy: sdk.Bool(true),
},
})
_ = c.client().Alter(context.Background(), &sdk.AlterAccountOptions{
Unset: &sdk.AccountUnset{
SessionPolicy: sdk.Bool(true),
},
})
_ = c.client().Alter(context.Background(), &sdk.AlterAccountOptions{
Unset: &sdk.AccountUnset{
AuthenticationPolicy: sdk.Bool(true),
},
})
}
}

func (c *AccountClient) DropFunc(t *testing.T, id sdk.AccountObjectIdentifier) func() {
t.Helper()
return func() {
Expand All @@ -103,70 +121,42 @@ func (c *AccountClient) Drop(t *testing.T, id sdk.AccountObjectIdentifier) error
t.Helper()
ctx := context.Background()

if err := c.client().Drop(ctx, id, 3, &sdk.DropAccountOptions{IfExists: sdk.Bool(true)}); err != nil {
return err
}
return nil
return c.client().Drop(ctx, id, 3, &sdk.DropAccountOptions{IfExists: sdk.Bool(true)})
}

type Region struct {
SnowflakeRegion string
Cloud string
Region string
DisplayName string
SnowflakeRegion string `db:"snowflake_region"`
Cloud string `db:"cloud"`
Region string `db:"region"`
DisplayName string `db:"display_name"`
}

func (c *AccountClient) ShowRegions(t *testing.T) []Region {
t.Helper()

results, err := c.context.client.QueryUnsafe(context.Background(), "SHOW REGIONS")
var regions []Region
err := c.context.client.QueryForTests(context.Background(), &regions, "SHOW REGIONS")
require.NoError(t, err)

return collections.Map(results, func(result map[string]*any) Region {
require.NotNil(t, result["snowflake_region"])
require.NotEmpty(t, *result["snowflake_region"])

require.NotNil(t, result["cloud"])
require.NotEmpty(t, *result["cloud"])

require.NotNil(t, result["region"])
require.NotEmpty(t, *result["region"])

require.NotNil(t, result["display_name"])
require.NotEmpty(t, *result["display_name"])

return Region{
SnowflakeRegion: (*result["snowflake_region"]).(string),
Cloud: (*result["cloud"]).(string),
Region: (*result["region"]).(string),
DisplayName: (*result["display_name"]).(string),
}
})
return regions
}

func (c *AccountClient) CreateAndLogIn(t *testing.T) (*sdk.Account, *sdk.Client) {
func (c *AccountClient) CreateAndLogIn(t *testing.T) (*sdk.Account, *sdk.Client, func()) {
t.Helper()
id := c.ids.RandomAccountObjectIdentifier()
name := c.ids.Alpha()
privateKey := random.GenerateRSAPrivateKey(t)
publicKey, _ := random.GenerateRSAPublicKeyBasedOnPrivateKey(t, privateKey)
publicKey, _ := random.GenerateRSAPublicKeyFromPrivateKey(t, privateKey)
email := random.Email()

account := c.CreateWithRequest(t, id, &sdk.CreateAccountOptions{
account, accountCleanup := c.CreateWithRequest(t, id, &sdk.CreateAccountOptions{
AdminName: name,
AdminRSAPublicKey: sdk.String(publicKey),
AdminUserType: sdk.Pointer(sdk.UserTypeService),
Email: email,
Edition: sdk.EditionStandard,
})

c.Alter(t, &sdk.AlterAccountOptions{
SetIsOrgAdmin: &sdk.AccountSetIsOrgAdmin{
Name: id,
OrgAdmin: sdk.Bool(true),
},
})

var client *sdk.Client
require.Eventually(t, func() bool {
newClient, err := sdk.NewClient(&gosnowflake.Config{
Expand All @@ -175,11 +165,11 @@ func (c *AccountClient) CreateAndLogIn(t *testing.T) (*sdk.Account, *sdk.Client)
Host: strings.TrimPrefix(*account.AccountLocatorURL, `https://`),
Authenticator: gosnowflake.AuthTypeJwt,
PrivateKey: privateKey,
Role: snowflakeroles.Orgadmin.Name(),
Role: snowflakeroles.Accountadmin.Name(),
})
client = newClient
return err == nil
}, 2*time.Minute, time.Second*15)

return account, client
return account, client, accountCleanup
}
6 changes: 4 additions & 2 deletions pkg/acceptance/helpers/packages_policy_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ func NewPackagesPolicyClient(context *TestClientContext, idsGenerator *IdsGenera
func (c *PackagesPolicyClient) Create(t *testing.T) (sdk.SchemaObjectIdentifier, func()) {
t.Helper()

// TODO(SNOW-1348357): Replace raw SQL with SDK

id := c.ids.RandomSchemaObjectIdentifier()
sfc-gh-jmichalak marked this conversation as resolved.
Show resolved Hide resolved
_, err := c.context.client.ExecUnsafe(context.Background(), fmt.Sprintf("CREATE PACKAGES POLICY %s LANGUAGE PYTHON", id.FullyQualifiedName()))
_, err := c.context.client.ExecForTests(context.Background(), fmt.Sprintf("CREATE PACKAGES POLICY %s LANGUAGE PYTHON", id.FullyQualifiedName()))
require.NoError(t, err)

return id, func() {
_, err = c.context.client.ExecUnsafe(context.Background(), fmt.Sprintf("DROP PACKAGES POLICY IF EXISTS %s", id.FullyQualifiedName()))
_, err = c.context.client.ExecForTests(context.Background(), fmt.Sprintf("DROP PACKAGES POLICY IF EXISTS %s", id.FullyQualifiedName()))
require.NoError(t, err)
}
}
17 changes: 4 additions & 13 deletions pkg/acceptance/helpers/random/certs.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,11 @@ func GenerateRSAPublicKey(t *testing.T) (string, string) {
t.Helper()
key := GenerateRSAPrivateKey(t)

return generateRSAPublicKeyFromPrivateKey(t, key)
return GenerateRSAPublicKeyFromPrivateKey(t, key)
}

// GenerateRSAPublicKey returns an RSA public key without BEGIN and END markers, and key's hash.
func generateRSAPublicKeyFromPrivateKey(t *testing.T, key *rsa.PrivateKey) (string, string) {
t.Helper()

pub := key.Public()
b, err := x509.MarshalPKIXPublicKey(pub.(*rsa.PublicKey))
require.NoError(t, err)
return encode(t, "RSA PUBLIC KEY", b), hash(t, b)
}

func GenerateRSAPublicKeyBasedOnPrivateKey(t *testing.T, key *rsa.PrivateKey) (string, string) {
// GenerateRSAPublicKeyFromPrivateKey returns an RSA public key without BEGIN and END markers, and key's hash.
func GenerateRSAPublicKeyFromPrivateKey(t *testing.T, key *rsa.PrivateKey) (string, string) {
t.Helper()

pub := key.Public()
Expand Down Expand Up @@ -91,7 +82,7 @@ func GenerateRSAKeyPair(t *testing.T, pass string) (string, string, string, stri
unencrypted := string(pem.EncodeToMemory(&privBlock))
encrypted := encrypt(t, privateKey, pass)

publicKey, keyHash := generateRSAPublicKeyFromPrivateKey(t, privateKey)
publicKey, keyHash := GenerateRSAPublicKeyFromPrivateKey(t, privateKey)
return unencrypted, encrypted, publicKey, keyHash
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/sdk/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ type CreateAccountOptions struct {
Email string `ddl:"parameter,single_quotes" sql:"EMAIL"`
MustChangePassword *bool `ddl:"parameter" sql:"MUST_CHANGE_PASSWORD"`
Edition AccountEdition `ddl:"parameter" sql:"EDITION"`
RegionGroup *string `ddl:"parameter,single_quotes" sql:"REGION_GROUP"`
Region *string `ddl:"parameter,single_quotes" sql:"REGION"`
RegionGroup *string `ddl:"parameter" sql:"REGION_GROUP"`
Region *string `ddl:"parameter" sql:"REGION"`
Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"`
Polaris *bool `ddl:"parameter" sql:"POLARIS"`
}
Expand Down Expand Up @@ -230,7 +230,7 @@ func (opts *AccountUnset) validate() error {

type AccountSetIsOrgAdmin struct {
Name AccountObjectIdentifier `ddl:"identifier"`
OrgAdmin *bool `ddl:"parameter" sql:"SET IS_ORG_ADMIN"`
OrgAdmin bool `ddl:"parameter" sql:"SET IS_ORG_ADMIN"`
}

type AccountRename struct {
Expand Down
8 changes: 4 additions & 4 deletions pkg/sdk/accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestAccountCreate(t *testing.T) {
Comment: String("Test account"),
Polaris: Bool(true),
}
assertOptsValidAndSQLEquals(t, opts, `CREATE ACCOUNT %s ADMIN_NAME = 'someadmin' ADMIN_RSA_PUBLIC_KEY = '%s' ADMIN_USER_TYPE = SERVICE FIRST_NAME = 'Ad' LAST_NAME = 'Min' EMAIL = 'admin@example.com' MUST_CHANGE_PASSWORD = true EDITION = BUSINESS_CRITICAL REGION_GROUP = 'groupid' REGION = 'regionid' COMMENT = 'Test account' POLARIS = true`, id.FullyQualifiedName(), key)
assertOptsValidAndSQLEquals(t, opts, `CREATE ACCOUNT %s ADMIN_NAME = 'someadmin' ADMIN_RSA_PUBLIC_KEY = '%s' ADMIN_USER_TYPE = SERVICE FIRST_NAME = 'Ad' LAST_NAME = 'Min' EMAIL = 'admin@example.com' MUST_CHANGE_PASSWORD = true EDITION = BUSINESS_CRITICAL REGION_GROUP = groupid REGION = regionid COMMENT = 'Test account' POLARIS = true`, id.FullyQualifiedName(), key)
})

t.Run("static password", func(t *testing.T) {
Expand All @@ -58,7 +58,7 @@ func TestAccountCreate(t *testing.T) {
Region: String("regionid"),
Comment: String("Test account"),
}
assertOptsValidAndSQLEquals(t, opts, `CREATE ACCOUNT %s ADMIN_NAME = 'someadmin' ADMIN_PASSWORD = '%s' FIRST_NAME = 'Ad' LAST_NAME = 'Min' EMAIL = 'admin@example.com' MUST_CHANGE_PASSWORD = false EDITION = BUSINESS_CRITICAL REGION_GROUP = 'groupid' REGION = 'regionid' COMMENT = 'Test account'`, id.FullyQualifiedName(), password)
assertOptsValidAndSQLEquals(t, opts, `CREATE ACCOUNT %s ADMIN_NAME = 'someadmin' ADMIN_PASSWORD = '%s' FIRST_NAME = 'Ad' LAST_NAME = 'Min' EMAIL = 'admin@example.com' MUST_CHANGE_PASSWORD = false EDITION = BUSINESS_CRITICAL REGION_GROUP = groupid REGION = regionid COMMENT = 'Test account'`, id.FullyQualifiedName(), password)
})
}

Expand Down Expand Up @@ -289,7 +289,7 @@ func TestAccountAlter(t *testing.T) {
opts := &AlterAccountOptions{
SetIsOrgAdmin: &AccountSetIsOrgAdmin{
Name: id,
OrgAdmin: Bool(true),
OrgAdmin: true,
},
}
assertOptsValidAndSQLEquals(t, opts, `ALTER ACCOUNT %s SET IS_ORG_ADMIN = true`, id.FullyQualifiedName())
Expand Down Expand Up @@ -356,7 +356,7 @@ func TestAccountAlter(t *testing.T) {
func TestAccountDrop(t *testing.T) {
t.Run("validate: empty options", func(t *testing.T) {
opts := &DropAccountOptions{}
assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier, errNotSet("DropAccountOptions", "gracePeriodInDays"))
assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier)
})

t.Run("minimal", func(t *testing.T) {
Expand Down
Loading
Loading