Skip to content

Commit

Permalink
Refactor tenant resource to allow for empty fields
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiught committed Oct 7, 2022
1 parent d0bb7e3 commit 4f33623
Show file tree
Hide file tree
Showing 4 changed files with 305 additions and 131 deletions.
83 changes: 46 additions & 37 deletions internal/provider/resource_auth0_tenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"

internalValidation "github.com/auth0/terraform-provider-auth0/internal/validation"
"github.com/auth0/terraform-provider-auth0/internal/value"
)

func newTenant() *schema.Resource {
Expand Down Expand Up @@ -154,8 +155,8 @@ func newTenant() *schema.Resource {
"session_lifetime": {
Type: schema.TypeFloat,
Optional: true,
ValidateFunc: validation.FloatAtLeast(0.01),
Default: 168,
ValidateFunc: validation.FloatAtLeast(0.01),
Description: "Number of hours during which a session will stay valid.",
},
"idle_session_lifetime": {
Expand Down Expand Up @@ -402,24 +403,24 @@ func readTenant(ctx context.Context, d *schema.ResourceData, m interface{}) diag
}

result := multierror.Append(
d.Set("change_password", flattenTenantChangePassword(tenant.ChangePassword)),
d.Set("guardian_mfa_page", flattenTenantGuardianMFAPage(tenant.GuardianMFAPage)),
d.Set("default_audience", tenant.DefaultAudience),
d.Set("default_directory", tenant.DefaultDirectory),
d.Set("default_redirection_uri", tenant.DefaultRedirectionURI),
d.Set("friendly_name", tenant.FriendlyName),
d.Set("picture_url", tenant.PictureURL),
d.Set("support_email", tenant.SupportEmail),
d.Set("support_url", tenant.SupportURL),
d.Set("allowed_logout_urls", tenant.AllowedLogoutURLs),
d.Set("session_lifetime", tenant.SessionLifetime),
d.Set("idle_session_lifetime", tenant.IdleSessionLifetime),
d.Set("sandbox_version", tenant.SandboxVersion),
d.Set("enabled_locales", tenant.EnabledLocales),
d.Set("error_page", flattenTenantErrorPage(tenant.ErrorPage)),
d.Set("flags", flattenTenantFlags(tenant.Flags)),
d.Set("universal_login", flattenTenantUniversalLogin(tenant.UniversalLogin)),
d.Set("session_cookie", flattenTenantSessionCookie(tenant.SessionCookie)),
d.Set("change_password", flattenTenantChangePassword(tenant.GetChangePassword())),
d.Set("guardian_mfa_page", flattenTenantGuardianMFAPage(tenant.GetGuardianMFAPage())),
d.Set("default_audience", tenant.GetDefaultAudience()),
d.Set("default_directory", tenant.GetDefaultDirectory()),
d.Set("default_redirection_uri", tenant.GetDefaultRedirectionURI()),
d.Set("friendly_name", tenant.GetFriendlyName()),
d.Set("picture_url", tenant.GetPictureURL()),
d.Set("support_email", tenant.GetSupportEmail()),
d.Set("support_url", tenant.GetSupportURL()),
d.Set("allowed_logout_urls", tenant.GetAllowedLogoutURLs()),
d.Set("session_lifetime", tenant.GetSessionLifetime()),
d.Set("idle_session_lifetime", tenant.GetIdleSessionLifetime()),
d.Set("sandbox_version", tenant.GetSandboxVersion()),
d.Set("enabled_locales", tenant.GetEnabledLocales()),
d.Set("error_page", flattenTenantErrorPage(tenant.GetErrorPage())),
d.Set("flags", flattenTenantFlags(tenant.GetFlags())),
d.Set("universal_login", flattenTenantUniversalLogin(tenant.GetUniversalLogin())),
d.Set("session_cookie", flattenTenantSessionCookie(tenant.GetSessionCookie())),
)

return diag.FromErr(result.ErrorOrNil())
Expand All @@ -441,25 +442,33 @@ func deleteTenant(ctx context.Context, d *schema.ResourceData, m interface{}) di
}

func expandTenant(d *schema.ResourceData) *management.Tenant {
config := d.GetRawConfig()

sessionLifetime := d.Get("session_lifetime").(float64) // Handling separately to preserve default values not honored by `d.GetRawConfig()`
idleSessionLifetime := d.Get("idle_session_lifetime").(float64) // Handling separately to preserve default values not honored by `d.GetRawConfig()`

tenant := &management.Tenant{
DefaultAudience: String(d, "default_audience"),
DefaultDirectory: String(d, "default_directory"),
DefaultRedirectionURI: String(d, "default_redirection_uri"),
FriendlyName: String(d, "friendly_name"),
PictureURL: String(d, "picture_url"),
SupportEmail: String(d, "support_email"),
SupportURL: String(d, "support_url"),
AllowedLogoutURLs: Slice(d, "allowed_logout_urls"),
SessionLifetime: Float64(d, "session_lifetime"),
SandboxVersion: String(d, "sandbox_version"),
IdleSessionLifetime: Float64(d, "idle_session_lifetime", IsNewResource(), HasChange()),
EnabledLocales: List(d, "enabled_locales").List(),
ChangePassword: expandTenantChangePassword(d),
GuardianMFAPage: expandTenantGuardianMFAPage(d),
ErrorPage: expandTenantErrorPage(d),
Flags: expandTenantFlags(d.GetRawConfig().GetAttr("flags")),
UniversalLogin: expandTenantUniversalLogin(d),
SessionCookie: expandTenantSessionCookie(d),
DefaultAudience: value.String(config.GetAttr("default_audience")),
DefaultDirectory: value.String(config.GetAttr("default_directory")),
DefaultRedirectionURI: value.String(config.GetAttr("default_redirection_uri")),
FriendlyName: value.String(config.GetAttr("friendly_name")),
PictureURL: value.String(config.GetAttr("picture_url")),
SupportEmail: value.String(config.GetAttr("support_email")),
SupportURL: value.String(config.GetAttr("support_url")),
AllowedLogoutURLs: value.Strings(config.GetAttr("allowed_logout_urls")),
SessionLifetime: &sessionLifetime,
SandboxVersion: value.String(config.GetAttr("sandbox_version")),
EnabledLocales: value.Strings(config.GetAttr("enabled_locales")),
ChangePassword: expandTenantChangePassword(config.GetAttr("change_password")),
GuardianMFAPage: expandTenantGuardianMFAPage(config.GetAttr("guardian_mfa_page")),
ErrorPage: expandTenantErrorPage(config.GetAttr("error_page")),
Flags: expandTenantFlags(config.GetAttr("flags")),
UniversalLogin: expandTenantUniversalLogin(config.GetAttr("universal_login")),
SessionCookie: expandTenantSessionCookie(config.GetAttr("session_cookie")),
}

if d.IsNewResource() || d.HasChange("idle_session_lifetime") {
tenant.IdleSessionLifetime = &idleSessionLifetime
}

return tenant
Expand Down
49 changes: 28 additions & 21 deletions internal/provider/resource_auth0_tenant_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package provider

import (
"fmt"
"os"
"testing"

Expand All @@ -12,17 +13,24 @@ import (
func TestAccTenant(t *testing.T) {
httpRecorder := recorder.New(t)

domain := os.Getenv("AUTH0_DOMAIN")

resource.Test(t, resource.TestCase{
ProviderFactories: testProviders(httpRecorder),
Steps: []resource.TestStep{
{
Config: testAccTenantConfigCreate,
Config: testAccEmptyTenant,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "change_password.0.enabled", "true"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "change_password.0.html", "<html>Change Password</html>"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "guardian_mfa_page.0.enabled", "true"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "guardian_mfa_page.0.html", "<html>MFA</html>"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "default_audience", ""),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "session_lifetime", "168"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "idle_session_lifetime", "72"),
),
},
{
Config: fmt.Sprintf(testAccTenantConfigCreate, domain),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("auth0_tenant.my_tenant", "change_password.0.enabled"),
resource.TestCheckResourceAttrSet("auth0_tenant.my_tenant", "guardian_mfa_page.0.enabled"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "default_audience", fmt.Sprintf("https://%s/api/v2/", domain)),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "default_directory", ""),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "error_page.0.html", "<html>Error Page</html>"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "error_page.0.show_log_link", "false"),
Expand Down Expand Up @@ -53,15 +61,24 @@ func TestAccTenant(t *testing.T) {
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "enabled_locales.0", "de"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "enabled_locales.1", "fr"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "default_audience", ""),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.disable_clickjack_protection_headers", "false"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.enable_public_signup_user_exists_error", "true"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.use_scope_descriptions_for_consent", "false"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "allowed_logout_urls.#", "0"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "session_cookie.0.mode", "persistent"),
),
},
{
Config: `resource "auth0_tenant" "my_tenant" {}`,
Config: testAccEmptyTenant,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "enabled_locales.0", "de"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "enabled_locales.1", "fr"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "default_audience", ""),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.disable_clickjack_protection_headers", "false"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.enable_public_signup_user_exists_error", "true"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "flags.0.use_scope_descriptions_for_consent", "false"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "allowed_logout_urls.#", "0"),
resource.TestCheckResourceAttr("auth0_tenant.my_tenant", "session_cookie.0.mode", "persistent"),
),
},
Expand All @@ -71,15 +88,7 @@ func TestAccTenant(t *testing.T) {

const testAccTenantConfigCreate = `
resource "auth0_tenant" "my_tenant" {
change_password {
enabled = true
html = "<html>Change Password</html>"
}
guardian_mfa_page {
enabled = true
html = "<html>MFA</html>"
}
default_audience = ""
default_audience = "https://%s/api/v2/"
default_directory = ""
error_page {
html = "<html>Error Page</html>"
Expand Down Expand Up @@ -140,9 +149,7 @@ resource "auth0_tenant" "my_tenant" {
picture_url = "https://mycompany.org/logo.png"
support_email = "[email protected]"
support_url = "https://mycompany.org/support"
allowed_logout_urls = [
"https://mycompany.org/logoutCallback"
]
allowed_logout_urls = []
session_lifetime = 720
sandbox_version = "12"
idle_session_lifetime = 72
Expand All @@ -169,6 +176,8 @@ resource "auth0_tenant" "my_tenant" {
}
`

const testAccEmptyTenant = `resource "auth0_tenant" "my_tenant" {}`

func TestAccTenantDefaults(t *testing.T) {
if os.Getenv("AUTH0_DOMAIN") != recorder.RecordingsDomain {
// Only run with recorded HTTP requests because normal E2E tests will naturally configure the tenant
Expand Down Expand Up @@ -197,5 +206,3 @@ func TestAccTenantDefaults(t *testing.T) {
},
})
}

const testAccEmptyTenant = `resource "auth0_tenant" "my_tenant" {}`
104 changes: 59 additions & 45 deletions internal/provider/structure_auth0_tenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package provider
import (
"github.com/auth0/go-auth0/management"
"github.com/hashicorp/go-cty/cty"

"github.com/auth0/terraform-provider-auth0/internal/value"
)

func flattenTenantChangePassword(changePassword *management.TenantChangePassword) []interface{} {
Expand Down Expand Up @@ -100,67 +102,70 @@ func flattenTenantSessionCookie(sessionCookie *management.TenantSessionCookie) [
return []interface{}{m}
}

func expandTenantChangePassword(d ResourceData) *management.TenantChangePassword {
func expandTenantChangePassword(config cty.Value) *management.TenantChangePassword {
var changePassword management.TenantChangePassword

List(d, "change_password").Elem(func(d ResourceData) {
changePassword.Enabled = Bool(d, "enabled")
changePassword.HTML = String(d, "html")
config.ForEachElement(func(_ cty.Value, d cty.Value) (stop bool) {
changePassword.Enabled = value.Bool(d.GetAttr("enabled"))
changePassword.HTML = value.String(d.GetAttr("html"))
return stop
})

return &changePassword
}

func expandTenantGuardianMFAPage(d ResourceData) *management.TenantGuardianMFAPage {
func expandTenantGuardianMFAPage(config cty.Value) *management.TenantGuardianMFAPage {
var mfa management.TenantGuardianMFAPage

List(d, "guardian_mfa_page").Elem(func(d ResourceData) {
mfa.Enabled = Bool(d, "enabled")
mfa.HTML = String(d, "html")
config.ForEachElement(func(_ cty.Value, d cty.Value) (stop bool) {
mfa.Enabled = value.Bool(d.GetAttr("enabled"))
mfa.HTML = value.String(d.GetAttr("html"))
return stop
})

return &mfa
}

func expandTenantErrorPage(d ResourceData) *management.TenantErrorPage {
func expandTenantErrorPage(config cty.Value) *management.TenantErrorPage {
var errorPage management.TenantErrorPage

List(d, "error_page").Elem(func(d ResourceData) {
errorPage.HTML = String(d, "html")
errorPage.ShowLogLink = Bool(d, "show_log_link")
errorPage.URL = String(d, "url")
config.ForEachElement(func(_ cty.Value, d cty.Value) (stop bool) {
errorPage.HTML = value.String(d.GetAttr("html"))
errorPage.ShowLogLink = value.Bool(d.GetAttr("show_log_link"))
errorPage.URL = value.String(d.GetAttr("url"))
return stop
})

return &errorPage
}

func expandTenantFlags(flagsList cty.Value) *management.TenantFlags {
func expandTenantFlags(config cty.Value) *management.TenantFlags {
var tenantFlags *management.TenantFlags

flagsList.ForEachElement(func(_ cty.Value, flags cty.Value) (stop bool) {
config.ForEachElement(func(_ cty.Value, flags cty.Value) (stop bool) {
tenantFlags = &management.TenantFlags{
EnableClientConnections: Flag(flags, "enable_client_connections"),
EnableAPIsSection: Flag(flags, "enable_apis_section"),
EnablePipeline2: Flag(flags, "enable_pipeline2"),
EnableDynamicClientRegistration: Flag(flags, "enable_dynamic_client_registration"),
EnableCustomDomainInEmails: Flag(flags, "enable_custom_domain_in_emails"),
UniversalLogin: Flag(flags, "universal_login"),
EnableLegacyLogsSearchV2: Flag(flags, "enable_legacy_logs_search_v2"),
DisableClickjackProtectionHeaders: Flag(flags, "disable_clickjack_protection_headers"),
EnablePublicSignupUserExistsError: Flag(flags, "enable_public_signup_user_exists_error"),
UseScopeDescriptionsForConsent: Flag(flags, "use_scope_descriptions_for_consent"),
AllowLegacyDelegationGrantTypes: Flag(flags, "allow_legacy_delegation_grant_types"),
AllowLegacyROGrantTypes: Flag(flags, "allow_legacy_ro_grant_types"),
AllowLegacyTokenInfoEndpoint: Flag(flags, "allow_legacy_tokeninfo_endpoint"),
EnableLegacyProfile: Flag(flags, "enable_legacy_profile"),
EnableIDTokenAPI2: Flag(flags, "enable_idtoken_api2"),
NoDisclosureEnterpriseConnections: Flag(flags, "no_disclose_enterprise_connections"),
DisableManagementAPISMSObfuscation: Flag(flags, "disable_management_api_sms_obfuscation"),
EnableADFSWAADEmailVerification: Flag(flags, "enable_adfs_waad_email_verification"),
RevokeRefreshTokenGrant: Flag(flags, "revoke_refresh_token_grant"),
DashboardLogStreams: Flag(flags, "dashboard_log_streams_next"),
DashboardInsightsView: Flag(flags, "dashboard_insights_view"),
DisableFieldsMapFix: Flag(flags, "disable_fields_map_fix"),
EnableClientConnections: value.Bool(flags.GetAttr("enable_client_connections")),
EnableAPIsSection: value.Bool(flags.GetAttr("enable_apis_section")),
EnablePipeline2: value.Bool(flags.GetAttr("enable_pipeline2")),
EnableDynamicClientRegistration: value.Bool(flags.GetAttr("enable_dynamic_client_registration")),
EnableCustomDomainInEmails: value.Bool(flags.GetAttr("enable_custom_domain_in_emails")),
UniversalLogin: value.Bool(flags.GetAttr("universal_login")),
EnableLegacyLogsSearchV2: value.Bool(flags.GetAttr("enable_legacy_logs_search_v2")),
DisableClickjackProtectionHeaders: value.Bool(flags.GetAttr("disable_clickjack_protection_headers")),
EnablePublicSignupUserExistsError: value.Bool(flags.GetAttr("enable_public_signup_user_exists_error")),
UseScopeDescriptionsForConsent: value.Bool(flags.GetAttr("use_scope_descriptions_for_consent")),
AllowLegacyDelegationGrantTypes: value.Bool(flags.GetAttr("allow_legacy_delegation_grant_types")),
AllowLegacyROGrantTypes: value.Bool(flags.GetAttr("allow_legacy_ro_grant_types")),
AllowLegacyTokenInfoEndpoint: value.Bool(flags.GetAttr("allow_legacy_tokeninfo_endpoint")),
EnableLegacyProfile: value.Bool(flags.GetAttr("enable_legacy_profile")),
EnableIDTokenAPI2: value.Bool(flags.GetAttr("enable_idtoken_api2")),
NoDisclosureEnterpriseConnections: value.Bool(flags.GetAttr("no_disclose_enterprise_connections")),
DisableManagementAPISMSObfuscation: value.Bool(flags.GetAttr("disable_management_api_sms_obfuscation")),
EnableADFSWAADEmailVerification: value.Bool(flags.GetAttr("enable_adfs_waad_email_verification")),
RevokeRefreshTokenGrant: value.Bool(flags.GetAttr("revoke_refresh_token_grant")),
DashboardLogStreams: value.Bool(flags.GetAttr("dashboard_log_streams_next")),
DashboardInsightsView: value.Bool(flags.GetAttr("dashboard_insights_view")),
DisableFieldsMapFix: value.Bool(flags.GetAttr("disable_fields_map_fix")),
}

return stop
Expand All @@ -169,26 +174,35 @@ func expandTenantFlags(flagsList cty.Value) *management.TenantFlags {
return tenantFlags
}

func expandTenantUniversalLogin(d ResourceData) *management.TenantUniversalLogin {
func expandTenantUniversalLogin(config cty.Value) *management.TenantUniversalLogin {
var universalLogin management.TenantUniversalLogin

List(d, "universal_login").Elem(func(d ResourceData) {
List(d, "colors").Elem(func(d ResourceData) {
config.ForEachElement(func(_ cty.Value, d cty.Value) (stop bool) {
colors := d.GetAttr("colors")

colors.ForEachElement(func(_ cty.Value, color cty.Value) (stop bool) {
universalLogin.Colors = &management.TenantUniversalLoginColors{
Primary: String(d, "primary"),
PageBackground: String(d, "page_background"),
Primary: value.String(color.GetAttr("primary")),
PageBackground: value.String(color.GetAttr("page_background")),
}
return stop
})
return stop
})

return &universalLogin
}

func expandTenantSessionCookie(d ResourceData) *management.TenantSessionCookie {
func expandTenantSessionCookie(config cty.Value) *management.TenantSessionCookie {
var sessionCookie management.TenantSessionCookie

List(d, "session_cookie").Elem(func(d ResourceData) {
sessionCookie.Mode = String(d, "mode")
if config.LengthInt() == 0 {
return nil
}

config.ForEachElement(func(_ cty.Value, d cty.Value) (stop bool) {
sessionCookie.Mode = value.String(d.GetAttr("mode"))
return stop
})

return &sessionCookie
Expand Down
Loading

0 comments on commit 4f33623

Please sign in to comment.