diff --git a/go.mod b/go.mod index c44c9a34fba4..b089e6f5f192 100644 --- a/go.mod +++ b/go.mod @@ -17,8 +17,8 @@ require ( github.com/google/go-cmp v0.5.9 github.com/google/uuid v1.4.0 github.com/hashicorp/go-azure-helpers v0.67.0 - github.com/hashicorp/go-azure-sdk/resource-manager v0.20240409.1113035 - github.com/hashicorp/go-azure-sdk/sdk v0.20240409.1113035 + github.com/hashicorp/go-azure-sdk/resource-manager v0.20240411.1104331 + github.com/hashicorp/go-azure-sdk/sdk v0.20240411.1104331 github.com/hashicorp/go-hclog v1.5.0 github.com/hashicorp/go-multierror v1.1.1 github.com/hashicorp/go-uuid v1.0.3 diff --git a/go.sum b/go.sum index 9db169f9cf35..4e3813cb4b86 100644 --- a/go.sum +++ b/go.sum @@ -95,10 +95,10 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-azure-helpers v0.67.0 h1:0RY6mY3W3Ym2I+jExLtyLx96fh6p5n9vidqisAKGUSE= github.com/hashicorp/go-azure-helpers v0.67.0/go.mod h1:S4Bu66vyJvHA0trqHQB0YVGsISuF7HMH9tyEsMVlx8A= -github.com/hashicorp/go-azure-sdk/resource-manager v0.20240409.1113035 h1:Qd0g2XnvfXekdsjFHiSa/4tAcLpnJAYdiVY5xhO8Ad4= -github.com/hashicorp/go-azure-sdk/resource-manager v0.20240409.1113035/go.mod h1:Pc8LAwXacrZMdmrXh94BPhQww1GysHnHvHeWo9LfhJA= -github.com/hashicorp/go-azure-sdk/sdk v0.20240409.1113035 h1:EvMlT8eKPv0p7szyWHR9bt/tyBD7P92hzRLAXILwfdg= -github.com/hashicorp/go-azure-sdk/sdk v0.20240409.1113035/go.mod h1:POOjeoqNp+mvlLBuibJTziUAkBZ7FxXGeGestwemL/w= +github.com/hashicorp/go-azure-sdk/resource-manager v0.20240411.1104331 h1:B6CaXKPRlckMFv6olNDIiVEnM5igZgmTF/ycugEatJk= +github.com/hashicorp/go-azure-sdk/resource-manager v0.20240411.1104331/go.mod h1:JAEN43cznhbtPV1LJ3xhW5K6XigKVY8vhyZvlUsKub0= +github.com/hashicorp/go-azure-sdk/sdk v0.20240411.1104331 h1:LYQI0A1rWPjrMa0J8N8MA5ZjFfHNaVpoPY1vmzrS/C8= +github.com/hashicorp/go-azure-sdk/sdk v0.20240411.1104331/go.mod h1:POOjeoqNp+mvlLBuibJTziUAkBZ7FxXGeGestwemL/w= github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= diff --git a/internal/acceptance/testclient/client.go b/internal/acceptance/testclient/client.go index ba6b1c22578a..84367cc565f4 100644 --- a/internal/acceptance/testclient/client.go +++ b/internal/acceptance/testclient/client.go @@ -40,7 +40,7 @@ func Build() (*clients.Client, error) { } if metadataHost != "" { - if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost), envName); err != nil { + if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost)); err != nil { return nil, fmt.Errorf("building test client: %+v", err) } } else if env, err = environments.FromName(envName); err != nil { diff --git a/internal/acceptance/testing.go b/internal/acceptance/testing.go index 91913b5ad5c1..386ebea5e80a 100644 --- a/internal/acceptance/testing.go +++ b/internal/acceptance/testing.go @@ -68,7 +68,7 @@ func GetAuthConfig(t *testing.T) *auth.Credentials { ) if metadataHost != "" { - if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost), envName); err != nil { + if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost)); err != nil { t.Fatalf("building test client: %+v", err) return nil } diff --git a/internal/clients/builder.go b/internal/clients/builder.go index db2ef2e96ccc..49ba130d164a 100644 --- a/internal/clients/builder.go +++ b/internal/clients/builder.go @@ -135,6 +135,7 @@ func Build(ctx context.Context, builder ClientBuilder) (*Client, error) { AuthorizerFunc: authorizerFunc, }, + AuthConfig: builder.AuthConfig, Environment: builder.AuthConfig.Environment, Features: builder.Features, diff --git a/internal/common/client_options.go b/internal/common/client_options.go index be5e783620ad..3a7e72eeb7c4 100644 --- a/internal/common/client_options.go +++ b/internal/common/client_options.go @@ -35,6 +35,7 @@ type ApiAuthorizerFunc func(api environments.Api) (auth.Authorizer, error) type ClientOptions struct { Authorizers *Authorizers + AuthConfig *auth.Credentials Environment environments.Environment Features features.UserFeatures diff --git a/internal/provider/helpers.go b/internal/provider/helpers.go index b568f1efd873..eff65d16d594 100644 --- a/internal/provider/helpers.go +++ b/internal/provider/helpers.go @@ -6,12 +6,26 @@ package provider import ( "encoding/base64" "fmt" + "log" "os" "strings" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) +// logEntry avoids log entries showing up in test output +func logEntry(f string, v ...interface{}) { + if os.Getenv("TF_LOG") == "" { + return + } + + if os.Getenv("TF_ACC") != "" { + return + } + + log.Printf(f, v...) +} + func decodeCertificate(clientCertificate string) ([]byte, error) { var pfx []byte if clientCertificate != "" { @@ -25,7 +39,7 @@ func decodeCertificate(clientCertificate string) ([]byte, error) { return pfx, nil } -func getOidcToken(d *schema.ResourceData) (*string, error) { +func getOidcToken(d *pluginsdk.ResourceData) (*string, error) { idToken := strings.TrimSpace(d.Get("oidc_token").(string)) if path := d.Get("oidc_token_file_path").(string); path != "" { @@ -64,7 +78,7 @@ func getOidcToken(d *schema.ResourceData) (*string, error) { return &idToken, nil } -func getClientId(d *schema.ResourceData) (*string, error) { +func getClientId(d *pluginsdk.ResourceData) (*string, error) { clientId := strings.TrimSpace(d.Get("client_id").(string)) if path := d.Get("client_id_file_path").(string); path != "" { @@ -94,7 +108,7 @@ func getClientId(d *schema.ResourceData) (*string, error) { return &clientId, nil } -func getClientSecret(d *schema.ResourceData) (*string, error) { +func getClientSecret(d *pluginsdk.ResourceData) (*string, error) { clientSecret := strings.TrimSpace(d.Get("client_secret").(string)) if path := d.Get("client_secret_file_path").(string); path != "" { @@ -116,7 +130,7 @@ func getClientSecret(d *schema.ResourceData) (*string, error) { return &clientSecret, nil } -func getTenantId(d *schema.ResourceData) (*string, error) { +func getTenantId(d *pluginsdk.ResourceData) (*string, error) { tenantId := strings.TrimSpace(d.Get("tenant_id").(string)) if d.Get("use_aks_workload_identity").(bool) && os.Getenv("AZURE_TENANT_ID") != "" { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4c6fbac83948..f6ee270fc714 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -6,7 +6,6 @@ package provider import ( "context" "fmt" - "log" "os" "strings" "time" @@ -37,18 +36,6 @@ func ValidatePartnerID(i interface{}, k string) ([]string, []error) { // * a valid UUID prefixed with "pid-" // * a valid UUID prefixed with "pid-" and suffixed with "-partnercenter" - debugLog := func(f string, v ...interface{}) { - if os.Getenv("TF_LOG") == "" { - return - } - - if os.Getenv("TF_ACC") != "" { - return - } - - log.Printf(f, v...) - } - v, ok := i.(string) if !ok { return nil, []error{fmt.Errorf("expected type of %q to be string", k)} @@ -67,7 +54,7 @@ func ValidatePartnerID(i interface{}, k string) ([]string, []error) { return nil, []error{fmt.Errorf("expected %q to contain a valid UUID", v)} } - debugLog("[DEBUG] %q partner_id matches pid--partnercenter...", v) + logEntry("[DEBUG] %q partner_id matches pid--partnercenter...", v) return nil, nil } @@ -79,7 +66,7 @@ func ValidatePartnerID(i interface{}, k string) ([]string, []error) { return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)} } - debugLog("[DEBUG] %q partner_id matches pid-...", v) + logEntry("[DEBUG] %q partner_id matches pid-...", v) return nil, nil } @@ -87,31 +74,18 @@ func ValidatePartnerID(i interface{}, k string) ([]string, []error) { if _, err := validation.IsUUID(v, ""); err != nil { return nil, []error{fmt.Errorf("expected %q to be a valid UUID", k)} } else { - debugLog("[DEBUG] %q partner_id is an un-prefixed UUID...", v) + logEntry("[DEBUG] %q partner_id is an un-prefixed UUID...", v) return nil, nil } } func azureProvider(supportLegacyTestSuite bool) *schema.Provider { - // avoids this showing up in test output - debugLog := func(f string, v ...interface{}) { - if os.Getenv("TF_LOG") == "" { - return - } - - if os.Getenv("TF_ACC") != "" { - return - } - - log.Printf(f, v...) - } - dataSources := make(map[string]*schema.Resource) resources := make(map[string]*schema.Resource) // first handle the typed services for _, service := range SupportedTypedServices() { - debugLog("[DEBUG] Registering Data Sources for %q..", service.Name()) + logEntry("[DEBUG] Registering Data Sources for %q..", service.Name()) for _, ds := range service.DataSources() { key := ds.ResourceType() if existing := dataSources[key]; existing != nil { @@ -127,7 +101,7 @@ func azureProvider(supportLegacyTestSuite bool) *schema.Provider { dataSources[key] = dataSource } - debugLog("[DEBUG] Registering Resources for %q..", service.Name()) + logEntry("[DEBUG] Registering Resources for %q..", service.Name()) for _, r := range service.Resources() { key := r.ResourceType() if existing := resources[key]; existing != nil { @@ -145,7 +119,7 @@ func azureProvider(supportLegacyTestSuite bool) *schema.Provider { // then handle the untyped services for _, service := range SupportedUntypedServices() { - debugLog("[DEBUG] Registering Data Sources for %q..", service.Name()) + logEntry("[DEBUG] Registering Data Sources for %q..", service.Name()) for k, v := range service.SupportedDataSources() { if existing := dataSources[k]; existing != nil { panic(fmt.Sprintf("An existing Data Source exists for %q", k)) @@ -154,7 +128,7 @@ func azureProvider(supportLegacyTestSuite bool) *schema.Provider { dataSources[k] = v } - debugLog("[DEBUG] Registering Resources for %q..", service.Name()) + logEntry("[DEBUG] Registering Resources for %q..", service.Name()) for k, v := range service.SupportedResources() { if existing := resources[k]; existing != nil { panic(fmt.Sprintf("An existing Resource exists for %q", k)) @@ -207,7 +181,7 @@ func azureProvider(supportLegacyTestSuite bool) *schema.Provider { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"), - Description: "The Cloud Environment which should be used. Possible values are public, usgovernment, and china. Defaults to public.", + Description: "The Cloud Environment which should be used. Possible values are public, usgovernment, and china. Defaults to public. Not used and should not be specified when `metadata_host` is specified.", }, "metadata_host": { @@ -420,11 +394,15 @@ func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc { ) if metadataHost != "" { - if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost), envName); err != nil { + logEntry("[DEBUG] Configuring cloud environment from Metadata Service at %q", metadataHost) + if env, err = environments.FromEndpoint(ctx, fmt.Sprintf("https://%s", metadataHost)); err != nil { + return nil, diag.FromErr(err) + } + } else { + logEntry("[DEBUG] Configuring built-in cloud environment by name: %q", envName) + if env, err = environments.FromName(envName); err != nil { return nil, diag.FromErr(err) } - } else if env, err = environments.FromName(envName); err != nil { - return nil, diag.FromErr(err) } var ( diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go index 9955e8e6475f..21e83b39bd56 100644 --- a/internal/provider/provider_test.go +++ b/internal/provider/provider_test.go @@ -197,14 +197,24 @@ func TestAccProvider_clientCertificateAuth(t *testing.T) { } } + clientId, err := getClientId(d) + if err != nil { + return nil, diag.FromErr(err) + } + + tenantId, err := getTenantId(d) + if err != nil { + return nil, diag.FromErr(err) + } + authConfig := &auth.Credentials{ - Environment: *env, - TenantID: d.Get("tenant_id").(string), - ClientID: d.Get("client_id").(string), + Environment: *env, + TenantID: *tenantId, + ClientID: *clientId, + ClientCertificateData: certData, + ClientCertificatePath: d.Get("client_certificate_path").(string), + ClientCertificatePassword: d.Get("client_certificate_password").(string), EnableAuthenticatingUsingClientCertificate: true, - ClientCertificateData: certData, - ClientCertificatePath: d.Get("client_certificate_path").(string), - ClientCertificatePassword: d.Get("client_certificate_password").(string), } return buildClient(ctx, provider, d, authConfig) @@ -267,12 +277,17 @@ func testAccProvider_clientSecretAuthFromEnvironment(t *testing.T) { return nil, diag.FromErr(err) } + tenantId, err := getTenantId(d) + if err != nil { + return nil, diag.FromErr(err) + } + authConfig := &auth.Credentials{ Environment: *env, - TenantID: d.Get("tenant_id").(string), + TenantID: *tenantId, ClientID: *clientId, - EnableAuthenticatingUsingClientSecret: true, ClientSecret: *clientSecret, + EnableAuthenticatingUsingClientSecret: true, } return buildClient(ctx, provider, d, authConfig) @@ -330,12 +345,17 @@ func testAccProvider_clientSecretAuthFromFiles(t *testing.T) { return nil, diag.FromErr(err) } + tenantId, err := getTenantId(d) + if err != nil { + return nil, diag.FromErr(err) + } + authConfig := &auth.Credentials{ Environment: *env, - TenantID: d.Get("tenant_id").(string), + TenantID: *tenantId, ClientID: *clientId, - EnableAuthenticatingUsingClientSecret: true, ClientSecret: *clientSecret, + EnableAuthenticatingUsingClientSecret: true, } return buildClient(ctx, provider, d, authConfig) @@ -380,10 +400,20 @@ func TestAccProvider_genericOidcAuth(t *testing.T) { return nil, diag.FromErr(err) } + clientId, err := getClientId(d) + if err != nil { + return nil, diag.FromErr(err) + } + + tenantId, err := getTenantId(d) + if err != nil { + return nil, diag.FromErr(err) + } + authConfig := &auth.Credentials{ Environment: *env, - TenantID: d.Get("tenant_id").(string), - ClientID: d.Get("client_id").(string), + TenantID: *tenantId, + ClientID: *clientId, EnableAuthenticationUsingOIDC: true, OIDCAssertionToken: *oidcToken, } @@ -428,13 +458,23 @@ func TestAccProvider_githubOidcAuth(t *testing.T) { t.Fatalf("configuring environment %q: %v", envName, err) } + clientId, err := getClientId(d) + if err != nil { + return nil, diag.FromErr(err) + } + + tenantId, err := getTenantId(d) + if err != nil { + return nil, diag.FromErr(err) + } + authConfig := &auth.Credentials{ Environment: *env, - TenantID: d.Get("tenant_id").(string), - ClientID: d.Get("client_id").(string), - EnableAuthenticationUsingGitHubOIDC: true, + TenantID: *tenantId, + ClientID: *clientId, GitHubOIDCTokenRequestToken: d.Get("oidc_request_token").(string), GitHubOIDCTokenRequestURL: d.Get("oidc_request_url").(string), + EnableAuthenticationUsingGitHubOIDC: true, } return buildClient(ctx, provider, d, authConfig) @@ -499,8 +539,8 @@ func TestAccProvider_aksWorkloadIdentityAuth(t *testing.T) { Environment: *env, TenantID: *tenantId, ClientID: *clientId, - EnableAuthenticationUsingOIDC: true, OIDCAssertionToken: *oidcToken, + EnableAuthenticationUsingOIDC: true, } return buildClient(ctx, provider, d, authConfig) diff --git a/internal/services/attestation/client/client.go b/internal/services/attestation/client/client.go index 949471aec618..60065b4f0bda 100644 --- a/internal/services/attestation/client/client.go +++ b/internal/services/attestation/client/client.go @@ -67,7 +67,11 @@ func (c *Client) DataPlaneClientWithEndpoint(endpoint string) (*attestation.Poli segments = segments[2:] } authTokenUri := fmt.Sprintf("https://%s/", strings.Join(segments, ".")) - api := environments.AttestationAPI(authTokenUri) + domainSuffix, ok := c.o.Environment.Attestation.DomainSuffix() + if !ok { + return nil, fmt.Errorf("building Authorizer for %q: domain suffix for Attestation service could not be determined", endpoint) + } + api := environments.AttestationAPI(authTokenUri, *domainSuffix) auth, err := c.o.Authorizers.AuthorizerFunc(api) if err != nil { return nil, fmt.Errorf("building Authorizer for %q: %+v", endpoint, err) diff --git a/internal/services/containers/client/client.go b/internal/services/containers/client/client.go index c8268a991911..bc47d9fd866c 100644 --- a/internal/services/containers/client/client.go +++ b/internal/services/containers/client/client.go @@ -6,7 +6,6 @@ package client import ( "fmt" - "github.com/Azure/go-autorest/autorest/azure" "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2023-05-01/containerinstance" containerregistry_v2019_06_01_preview "github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2019-06-01-preview" containerregistry_v2021_08_01_preview "github.com/hashicorp/go-azure-sdk/resource-manager/containerregistry/2021-08-01-preview" @@ -20,6 +19,7 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/kubernetesconfiguration/2022-11-01/extensions" "github.com/hashicorp/go-azure-sdk/resource-manager/kubernetesconfiguration/2022-11-01/fluxconfiguration" "github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager" + "github.com/hashicorp/go-azure-sdk/sdk/environments" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) @@ -37,7 +37,7 @@ type Client struct { MaintenanceConfigurationsClient *maintenanceconfigurations.MaintenanceConfigurationsClient ServicesClient *containerservices.ContainerServicesClient SnapshotClient *snapshots.SnapshotsClient - Environment azure.Environment + Environment environments.Environment } func NewContainersClient(o *common.ClientOptions) (*Client, error) { @@ -129,6 +129,6 @@ func NewContainersClient(o *common.ClientOptions) (*Client, error) { MaintenanceConfigurationsClient: maintenanceConfigurationsClient, ServicesClient: servicesClient, SnapshotClient: snapshotClient, - Environment: o.AzureEnvironment, + Environment: o.Environment, }, nil } diff --git a/internal/services/containers/kubernetes_addons.go b/internal/services/containers/kubernetes_addons.go index 40a7aebe2e94..1c553fbd97f8 100644 --- a/internal/services/containers/kubernetes_addons.go +++ b/internal/services/containers/kubernetes_addons.go @@ -7,11 +7,11 @@ import ( "fmt" "strings" - "github.com/Azure/go-autorest/autorest/azure" "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/containerservice/2023-06-02-preview/managedclusters" "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" + "github.com/hashicorp/go-azure-sdk/sdk/environments" commonValidate "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" containerValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/validate" applicationGatewayValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" @@ -37,11 +37,11 @@ const ( // the list of unsupported addons in the defined region - e.g. by being // omitted from this list an addon/environment combination will be supported var unsupportedAddonsForEnvironment = map[string][]string{ - azure.ChinaCloud.Name: { + environments.AzureChinaCloud: { aciConnectorKey, // https://github.com/hashicorp/terraform-provider-azurerm/issues/5510 httpApplicationRoutingKey, // https://github.com/hashicorp/terraform-provider-azurerm/issues/5960 }, - azure.USGovernmentCloud.Name: { + environments.AzureUSGovernmentCloud: { httpApplicationRoutingKey, // https://github.com/hashicorp/terraform-provider-azurerm/issues/5960 }, } @@ -282,7 +282,7 @@ func schemaKubernetesAddOns() map[string]*pluginsdk.Schema { return out } -func expandKubernetesAddOns(d *pluginsdk.ResourceData, input map[string]interface{}, env azure.Environment) (*map[string]managedclusters.ManagedClusterAddonProfile, error) { +func expandKubernetesAddOns(d *pluginsdk.ResourceData, input map[string]interface{}, env environments.Environment) (*map[string]managedclusters.ManagedClusterAddonProfile, error) { disabled := managedclusters.ManagedClusterAddonProfile{ Enabled: false, } @@ -421,7 +421,7 @@ func expandKubernetesAddOns(d *pluginsdk.ResourceData, input map[string]interfac return filterUnsupportedKubernetesAddOns(addonProfiles, env) } -func filterUnsupportedKubernetesAddOns(input map[string]managedclusters.ManagedClusterAddonProfile, env azure.Environment) (*map[string]managedclusters.ManagedClusterAddonProfile, error) { +func filterUnsupportedKubernetesAddOns(input map[string]managedclusters.ManagedClusterAddonProfile, env environments.Environment) (*map[string]managedclusters.ManagedClusterAddonProfile, error) { filter := func(input map[string]managedclusters.ManagedClusterAddonProfile, key string) (map[string]managedclusters.ManagedClusterAddonProfile, error) { output := input if v, ok := output[key]; ok { diff --git a/internal/services/storage/client/client.go b/internal/services/storage/client/client.go index 3328f7851aca..3c3c231f1286 100644 --- a/internal/services/storage/client/client.go +++ b/internal/services/storage/client/client.go @@ -34,7 +34,7 @@ type Client struct { BlobServicesClient *storage.BlobServicesClient FileServicesClient *storage.FileServicesClient - authorizerForAad auth.Authorizer + authConfigForAzureAD *auth.Credentials } func NewClient(o *common.ClientOptions) (*Client, error) { @@ -95,7 +95,7 @@ func NewClient(o *common.ClientOptions) (*Client, error) { } if o.StorageUseAzureAD { - client.authorizerForAad = o.Authorizers.Storage + client.authConfigForAzureAD = o.AuthConfig } return &client, nil diff --git a/internal/services/storage/client/data_plane.go b/internal/services/storage/client/data_plane.go index 01539a17326b..4e0a4305dea5 100644 --- a/internal/services/storage/client/data_plane.go +++ b/internal/services/storage/client/data_plane.go @@ -44,9 +44,15 @@ func (Client) DataPlaneOperationSupportingOnlySharedKeyAuth() DataPlaneOperation } } -func (c Client) configureDataPlane(ctx context.Context, clientName string, baseClient client.BaseClient, account accountDetails, operation DataPlaneOperation) error { - if operation.SupportsAadAuthentication && c.authorizerForAad != nil { - baseClient.SetAuthorizer(c.authorizerForAad) +func (c Client) configureDataPlane(ctx context.Context, clientName, resourceIdentifier string, baseClient client.BaseClient, account accountDetails, operation DataPlaneOperation) error { + if operation.SupportsAadAuthentication && c.authConfigForAzureAD != nil { + api := c.authConfigForAzureAD.Environment.Storage.WithResourceIdentifier(resourceIdentifier) + storageAuth, err := auth.NewAuthorizerFromCredentials(ctx, *c.authConfigForAzureAD, api) + if err != nil { + return fmt.Errorf("unable to build authorizer for Storage API: %+v", err) + } + + baseClient.SetAuthorizer(storageAuth) return nil } @@ -82,7 +88,7 @@ func (c Client) AccountsDataPlaneClient(ctx context.Context, account accountDeta return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -104,7 +110,7 @@ func (c Client) BlobsDataPlaneClient(ctx context.Context, account accountDetails return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -126,7 +132,7 @@ func (c Client) ContainersDataPlaneClient(ctx context.Context, account accountDe return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -148,7 +154,7 @@ func (c Client) DataLakeFilesystemsDataPlaneClient(ctx context.Context, account return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -170,7 +176,7 @@ func (c Client) DataLakePathsDataPlaneClient(ctx context.Context, account accoun return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -192,7 +198,7 @@ func (c Client) FileShareDirectoriesDataPlaneClient(ctx context.Context, account return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -214,7 +220,7 @@ func (c Client) FileShareFilesDataPlaneClient(ctx context.Context, account accou return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -236,7 +242,7 @@ func (c Client) FileSharesDataPlaneClient(ctx context.Context, account accountDe return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -258,7 +264,7 @@ func (c Client) QueuesDataPlaneClient(ctx context.Context, account accountDetail return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -280,7 +286,7 @@ func (c Client) TableEntityDataPlaneClient(ctx context.Context, account accountD return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } @@ -302,7 +308,7 @@ func (c Client) TablesDataPlaneClient(ctx context.Context, account accountDetail return nil, fmt.Errorf("building %s client: %+v", clientName, err) } - err = c.configureDataPlane(ctx, clientName, apiClient.Client, account, operation) + err = c.configureDataPlane(ctx, clientName, *baseUri, apiClient.Client, account, operation) if err != nil { return nil, err } diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index ac928a323bf4..e3acc874e647 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -23,7 +23,6 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2023-01-01/storageaccounts" - "github.com/hashicorp/go-azure-sdk/sdk/environments" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -1304,7 +1303,6 @@ func resourceStorageAccount() *pluginsdk.Resource { } func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) error { - envName := meta.(*clients.Client).Account.Environment.Name tenantId := meta.(*clients.Client).Account.TenantId client := meta.(*clients.Client).Storage.AccountsClient storageClient := meta.(*clients.Client).Storage @@ -1353,25 +1351,27 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e parameters := storage.AccountCreateParameters{ ExtendedLocation: expandEdgeZone(d.Get("edge_zone").(string)), + Kind: accountKind, Location: &location, Sku: &storage.Sku{ Name: storage.SkuName(storageType), }, Tags: tags.Expand(t), - Kind: accountKind, AccountPropertiesCreateParameters: &storage.AccountPropertiesCreateParameters{ - PublicNetworkAccess: publicNetworkAccess, - EnableHTTPSTrafficOnly: &enableHTTPSTrafficOnly, - NetworkRuleSet: expandStorageAccountNetworkRules(d, tenantId), - IsHnsEnabled: &isHnsEnabled, - EnableNfsV3: &nfsV3Enabled, + AllowBlobPublicAccess: &allowBlobPublicAccess, + AllowCrossTenantReplication: &crossTenantReplication, AllowSharedKeyAccess: &allowSharedKeyAccess, + DNSEndpointType: storage.DNSEndpointType(dnsEndpointType), DefaultToOAuthAuthentication: &defaultToOAuthAuthentication, - AllowCrossTenantReplication: &crossTenantReplication, - SasPolicy: expandStorageAccountSASPolicy(d.Get("sas_policy").([]interface{})), - IsSftpEnabled: &isSftpEnabled, + EnableHTTPSTrafficOnly: &enableHTTPSTrafficOnly, + EnableNfsV3: &nfsV3Enabled, + IsHnsEnabled: &isHnsEnabled, IsLocalUserEnabled: pointer.To(d.Get("local_user_enabled").(bool)), - DNSEndpointType: storage.DNSEndpointType(dnsEndpointType), + IsSftpEnabled: &isSftpEnabled, + MinimumTLSVersion: storage.MinimumTLSVersion(minimumTLSVersion), + NetworkRuleSet: expandStorageAccountNetworkRules(d, tenantId), + PublicNetworkAccess: publicNetworkAccess, + SasPolicy: expandStorageAccountSASPolicy(d.Get("sas_policy").([]interface{})), }, } @@ -1379,20 +1379,6 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e parameters.AccountPropertiesCreateParameters.AllowedCopyScope = storage.AllowedCopyScope(v) } - // For all Clouds except Public, China, and USGovernmentCloud, don't specify "allow_blob_public_access" and "min_tls_version" in request body. - // https://github.com/hashicorp/terraform-provider-azurerm/issues/7812 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/8083 - // USGovernmentCloud allow_blob_public_access and min_tls_version allowed as of issue 9128 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/9128 - if envName != environments.AzurePublicCloud && envName != environments.AzureUSGovernmentCloud && envName != environments.AzureChinaCloud { - if allowBlobPublicAccess || minimumTLSVersion != string(storage.MinimumTLSVersionTLS10) { - return fmt.Errorf(`"allow_nested_items_to_be_public" and "min_tls_version" are not supported for a Storage Account located in %q`, envName) - } - } else { - parameters.AccountPropertiesCreateParameters.AllowBlobPublicAccess = &allowBlobPublicAccess - parameters.AccountPropertiesCreateParameters.MinimumTLSVersion = storage.MinimumTLSVersion(minimumTLSVersion) - } - storageAccountIdentity, err := expandAzureRmStorageAccountIdentity(d.Get("identity").([]interface{})) if err != nil { return err @@ -1681,7 +1667,6 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e } func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - envName := meta.(*clients.Client).Account.Environment.Name tenantId := meta.(*clients.Client).Account.TenantId client := meta.(*clients.Client).Storage.AccountsClient keyVaultClient := meta.(*clients.Client).KeyVault @@ -1826,35 +1811,11 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e } if d.HasChange("min_tls_version") { - minimumTLSVersion := d.Get("min_tls_version").(string) - - // For all Clouds except Public, China, and USGovernmentCloud, don't specify "min_tls_version" in request body. - // https://github.com/hashicorp/terraform-provider-azurerm/issues/8083 - // USGovernmentCloud "min_tls_version" allowed as of issue 9128 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/9128 - if envName != environments.AzurePublicCloud && envName != environments.AzureUSGovernmentCloud && envName != environments.AzureChinaCloud { - if minimumTLSVersion != string(storage.MinimumTLSVersionTLS10) { - return fmt.Errorf(`"min_tls_version" is not supported for a Storage Account located in %q`, envName) - } - } else { - props.MinimumTLSVersion = storage.MinimumTLSVersion(minimumTLSVersion) - } + props.MinimumTLSVersion = storage.MinimumTLSVersion(d.Get("min_tls_version").(string)) } if d.HasChange("allow_nested_items_to_be_public") { - allowBlobPublicAccess := d.Get("allow_nested_items_to_be_public").(bool) - - // For all Clouds except Public, China, and USGovernmentCloud, don't specify "allow_blob_public_access" in request body. - // https://github.com/hashicorp/terraform-provider-azurerm/issues/7812 - // USGovernmentCloud "allow_blob_public_access" allowed as of issue 9128 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/9128 - if envName != environments.AzurePublicCloud && envName != environments.AzureUSGovernmentCloud && envName != environments.AzureChinaCloud { - if allowBlobPublicAccess { - return fmt.Errorf("allow_nested_items_to_be_public is not supported for a Storage Account located in %q", envName) - } - } else { - props.AllowBlobPublicAccess = pointer.To(allowBlobPublicAccess) - } + props.AllowBlobPublicAccess = pointer.To(d.Get("allow_nested_items_to_be_public").(bool)) } if d.HasChange("public_network_access_enabled") { @@ -2142,22 +2103,12 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err // lintignore:R001 d.Set("allow_nested_items_to_be_public", allowBlobPublicAccess) - // For all Clouds except Public, China, and USGovernmentCloud, "min_tls_version" is not returned from Azure so always persist the default values for "min_tls_version". - // https://github.com/hashicorp/terraform-provider-azurerm/issues/7812 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/8083 - // USGovernmentCloud "min_tls_version" allowed as of issue 9128 - // https://github.com/hashicorp/terraform-provider-azurerm/issues/9128 - envName := meta.(*clients.Client).Account.Environment.Name - if envName != environments.AzurePublicCloud && envName != environments.AzureUSGovernmentCloud && envName != environments.AzureChinaCloud { - d.Set("min_tls_version", string(storage.MinimumTLSVersionTLS10)) - } else { - // For storage account created using old API, the response of GET call will not return "min_tls_version", either. - minTlsVersion := string(storage.MinimumTLSVersionTLS10) - if props.MinimumTLSVersion != "" { - minTlsVersion = string(props.MinimumTLSVersion) - } - d.Set("min_tls_version", minTlsVersion) + // For storage account created using old API, the response of GET call will not return "min_tls_version" + minTlsVersion := string(storage.MinimumTLSVersionTLS10) + if props.MinimumTLSVersion != "" { + minTlsVersion = string(props.MinimumTLSVersion) } + d.Set("min_tls_version", minTlsVersion) if err := d.Set("custom_domain", flattenStorageAccountCustomDomain(props.CustomDomain)); err != nil { return fmt.Errorf("setting `custom_domain`: %+v", err) diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_china.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_china.go index 423288aa5fe8..056ef77b62f8 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_china.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_china.go @@ -17,32 +17,27 @@ func AzureChina() *Environment { LoginEndpoint: "https://login.chinacloudapi.cn", Tenant: "common", } - env.ResourceManager = ResourceManagerAPI("https://management.chinacloudapi.cn").withResourceIdentifier("https://management.chinacloudapi.cn") - env.MicrosoftGraph = MicrosoftGraphAPI("https://microsoftgraph.chinacloudapi.cn").withResourceIdentifier("https://microsoftgraph.chinacloudapi.cn") + env.ResourceManager = ResourceManagerAPI("https://management.chinacloudapi.cn") + env.MicrosoftGraph = MicrosoftGraphAPI("https://microsoftgraph.chinacloudapi.cn") - // DataLake, ManagedHSM and OperationalInsights are not available env.ApiManagement = ApiManagementAPI("azure-api.cn") env.AppConfiguration = AppConfigurationAPI("azconfig.azure.cn") - env.Batch = BatchAPI("https://batch.chinacloudapi.cn").withResourceIdentifier("https://batch.chinacloudapi.cn") + env.Batch = BatchAPI("https://batch.chinacloudapi.cn") env.ContainerRegistry = ContainerRegistryAPI("azurecr.cn") env.CosmosDB = CosmosDBAPI("documents.azure.cn") - env.KeyVault = KeyVaultAPI("vault.azure.cn").withResourceIdentifier("https://vault.azure.cn") - env.MariaDB = MariaDBAPI("mariadb.database.chinacloudapi.cn").withResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") - env.MySql = MySqlAPI("mysql.database.chinacloudapi.cn").withResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") - env.OperationalInsights = OperationalInsightsAPI().withResourceIdentifier("https://api.loganalytics.azure.cn") - env.Postgresql = PostgresqlAPI("postgres.database.chinacloudapi.cn").withResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") - env.ServiceBus = ServiceBusAPI("https://servicebus.chinacloudapi.cn", "servicebus.chinacloudapi.cn") - env.Sql = SqlAPI("database.chinacloudapi.cn").withResourceIdentifier("https://database.chinacloudapi.cn") - env.Storage = StorageAPI("core.chinacloudapi.cn").withResourceIdentifier("https://storage.azure.com") - env.Synapse = SynapseAPI("dev.azuresynapse.azure.cn") + env.KeyVault = KeyVaultAPI("vault.azure.cn").WithResourceIdentifier("https://vault.azure.cn") + env.ManagedHSM = ManagedHSMAPI("https://managedhsm.azure.cn", "managedhsm.azure.cn") + env.MariaDB = MariaDBAPI("mariadb.database.chinacloudapi.cn").WithResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") + env.MySql = MySqlAPI("mysql.database.chinacloudapi.cn").WithResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") + env.OperationalInsights = OperationalInsightsAPI().WithResourceIdentifier("https://api.loganalytics.azure.cn") + env.Postgresql = PostgresqlAPI("postgres.database.chinacloudapi.cn").WithResourceIdentifier("https://ossrdbms-aad.database.chinacloudapi.cn") + env.ServiceBus = ServiceBusAPI("https://servicebus.chinacloudapi.cn", "servicebus.chinacloudapi.cn").WithResourceIdentifier("https://servicebus.chinacloudapi.cn") + env.Sql = SqlAPI("database.chinacloudapi.cn").WithResourceIdentifier("https://database.chinacloudapi.cn") + env.Storage = StorageAPI("core.chinacloudapi.cn").WithResourceIdentifier("https://storage.azure.com") + env.Synapse = SynapseAPI("dev.azuresynapse.azure.cn").WithResourceIdentifier("https://dev.azuresynapse.azure.cn") env.TrafficManager = TrafficManagerAPI("trafficmanager.cn") - // @tombuildsstuff: DataLake doesn't appear to be available? - - // Managed HSM expected "H2 2023" per: - // https://azure.microsoft.com/en-gb/explore/global-infrastructure/products-by-region/?regions=china-non-regional,china-east,china-east-2,china-east-3,china-north,china-north-2,china-north-3&products=all - // presumably this'll be - // env.ManagedHSM = ManagedHSMAPI("https://managedhsm.azure.cn", "managedhsm.azure.cn") + // Services not currently available: Attestation, CDNFrontDoor, DataLake, IOTCentral return &env } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_gov.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_gov.go index ef4d02c049d5..2331705e81ab 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_gov.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_gov.go @@ -17,28 +17,27 @@ func AzureUSGovernment() *Environment { LoginEndpoint: "https://login.microsoftonline.us", Tenant: "common", } - env.ResourceManager = ResourceManagerAPI("https://management.usgovcloudapi.net").withResourceIdentifier("https://management.usgovcloudapi.net") - env.MicrosoftGraph = MicrosoftGraphAPI("https://graph.microsoft.us").withResourceIdentifier("https://graph.microsoft.us") + env.ResourceManager = ResourceManagerAPI("https://management.usgovcloudapi.net") + env.MicrosoftGraph = MicrosoftGraphAPI("https://graph.microsoft.us") env.ApiManagement = ApiManagementAPI("azure-api.us") env.AppConfiguration = AppConfigurationAPI("azconfig.azure.us") - env.Batch = BatchAPI("https://batch.core.usgovcloudapi.net").withResourceIdentifier("https://batch.core.usgovcloudapi.net") + env.Batch = BatchAPI("https://batch.core.usgovcloudapi.net") env.ContainerRegistry = ContainerRegistryAPI("azurecr.us") env.CosmosDB = CosmosDBAPI("documents.azure.us") - env.KeyVault = KeyVaultAPI("vault.usgovcloudapi.net").withResourceIdentifier("https://vault.usgovcloudapi.net") + env.KeyVault = KeyVaultAPI("vault.usgovcloudapi.net").WithResourceIdentifier("https://vault.usgovcloudapi.net") env.ManagedHSM = ManagedHSMAPI("https://managedhsm.usgovcloudapi.net", "managedhsm.usgovcloudapi.net") - env.MariaDB = MariaDBAPI("mariadb.database.usgovcloudapi.net").withResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") - env.MySql = MySqlAPI("mysql.database.usgovcloudapi.net").withResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") - env.OperationalInsights = OperationalInsightsAPI().withResourceIdentifier("https://api.loganalytics.us") - env.Postgresql = PostgresqlAPI("postgres.database.usgovcloudapi.net").withResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") - env.ServiceBus = ServiceBusAPI("https://servicebus.usgovcloudapi.net", "servicebus.usgovcloudapi.net") - env.Sql = SqlAPI("database.usgovcloudapi.net").withResourceIdentifier("https://database.usgovcloudapi.net") + env.MariaDB = MariaDBAPI("mariadb.database.usgovcloudapi.net").WithResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") + env.MySql = MySqlAPI("mysql.database.usgovcloudapi.net").WithResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") + env.OperationalInsights = OperationalInsightsAPI().WithResourceIdentifier("https://api.loganalytics.us") + env.Postgresql = PostgresqlAPI("postgres.database.usgovcloudapi.net").WithResourceIdentifier("https://ossrdbms-aad.database.usgovcloudapi.net") + env.ServiceBus = ServiceBusAPI("https://servicebus.usgovcloudapi.net", "servicebus.usgovcloudapi.net").WithResourceIdentifier("https://servicebus.usgovcloudapi.net") + env.Sql = SqlAPI("database.usgovcloudapi.net").WithResourceIdentifier("https://database.usgovcloudapi.net") env.Storage = StorageAPI("core.usgovcloudapi.net") - env.Synapse = SynapseAPI("dev.azuresynapse.usgovcloudapi.net").withResourceIdentifier("https://dev.azuresynapse.usgovcloudapi.net") + env.Synapse = SynapseAPI("dev.azuresynapse.usgovcloudapi.net").WithResourceIdentifier("https://dev.azuresynapse.usgovcloudapi.net") env.TrafficManager = TrafficManagerAPI("usgovtrafficmanager.net") - // CDNFrontDoor doesn't appear to be available - // DataLake doesn't appear to be available + // Services not currently available: Attestation, CDNFrontDoor, DataLake, IOTCentral return &env } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public.go index 23dafb3b9fb2..737fbdb2684d 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public.go @@ -22,23 +22,23 @@ func AzurePublic() *Environment { env.ApiManagement = ApiManagementAPI("azure-api.net") env.AppConfiguration = AppConfigurationAPI("azconfig.io") - env.Attestation = AttestationAPI("https://attest.azure.net") + env.Attestation = AttestationAPI("https://attest.azure.net", "attest.azure.net") env.Batch = BatchAPI("https://batch.core.windows.net") env.CDNFrontDoor = CDNFrontDoorAPI("azurefd.net") env.ContainerRegistry = ContainerRegistryAPI("azurecr.io") - env.CosmosDB = CosmosDBAPI("documents.azure.com") - env.DataLake = DataLakeAPI("azuredatalakestore.net") - env.IoTCentral = IoTCentral("azureiotcentral.com") - env.KeyVault = KeyVaultAPI("vault.azure.net") + env.CosmosDB = CosmosDBAPI("documents.azure.com").WithResourceIdentifier("https://cosmos.azure.com") + env.DataLake = DataLakeAPI("azuredatalakestore.net").WithResourceIdentifier("https://datalake.azure.net") + env.IoTCentral = IoTCentral("azureiotcentral.com").WithResourceIdentifier("https://apps.azureiotcentral.com") + env.KeyVault = KeyVaultAPI("vault.azure.net").WithResourceIdentifier("https://vault.azure.net") env.ManagedHSM = ManagedHSMAPI("https://managedhsm.azure.net", "managedhsm.azure.net") - env.MariaDB = MariaDBAPI("mariadb.database.azure.com") - env.MySql = MySqlAPI("mysql.database.azure.com") - env.OperationalInsights = OperationalInsightsAPI() - env.Postgresql = PostgresqlAPI("postgres.database.azure.com") - env.ServiceBus = ServiceBusAPI("https://servicebus.windows.net", "servicebus.windows.net") - env.Sql = SqlAPI("database.windows.net") + env.MariaDB = MariaDBAPI("mariadb.database.azure.com").WithResourceIdentifier("https://ossrdbms-aad.database.windows.net") + env.MySql = MySqlAPI("mysql.database.azure.com").WithResourceIdentifier("https://ossrdbms-aad.database.windows.net") + env.OperationalInsights = OperationalInsightsAPI().WithResourceIdentifier("https://api.loganalytics.io") + env.Postgresql = PostgresqlAPI("postgres.database.azure.com").WithResourceIdentifier("https://ossrdbms-aad.database.windows.net") + env.ServiceBus = ServiceBusAPI("https://servicebus.windows.net", "servicebus.windows.net").WithResourceIdentifier("https://servicebus.azure.net") + env.Sql = SqlAPI("database.windows.net").WithResourceIdentifier("https://database.windows.net") env.Storage = StorageAPI("core.windows.net") - env.Synapse = SynapseAPI("dev.azuresynapse.net") + env.Synapse = SynapseAPI("dev.azuresynapse.net").WithResourceIdentifier("https://dev.azuresynapse.net") env.TrafficManager = TrafficManagerAPI("trafficmanager.net") return &env diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public_canary.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public_canary.go index 475a656384bf..7cd5cc7d9490 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public_canary.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/azure_public_canary.go @@ -7,6 +7,6 @@ func AzurePublicCanary() *Environment { // Canary is Azure Public with a different Microsoft Graph endpoint env := AzurePublic() env.Name = "Canary" - env.MicrosoftGraph = MicrosoftGraphAPI("https://canary.graph.microsoft.com").withResourceIdentifier("https://canary.graph.microsoft.com") + env.MicrosoftGraph = MicrosoftGraphAPI("https://canary.graph.microsoft.com").WithResourceIdentifier("https://canary.graph.microsoft.com") return env } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/endpoint_refresh.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/endpoint_refresh.go index a0a7fc9ac033..d4f2314c0f28 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/endpoint_refresh.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/endpoint_refresh.go @@ -17,7 +17,7 @@ func (e *Environment) RefreshMetaDataFromEndpoint(ctx context.Context) error { } client := metadata.NewClientWithEndpoint(*endpoint) - config, err := client.GetMetaData(ctx, e.Name) + config, err := client.GetMetaData(ctx) if err != nil { return fmt.Errorf("retrieving MetaData from endpoint: %+v", err) } @@ -30,7 +30,14 @@ func (e *Environment) RefreshMetaDataFromEndpoint(ctx context.Context) error { } func (e *Environment) updateFromMetaData(config *metadata.MetaData) error { - // Auth Endpoints + // The following supported services are missing from metadata and cannot be configured: + // - API Management (domain suffix is missing) + // - App Configuration (domain suffix and resource identifier are missing) + // - CosmosDB (domain suffix is missing) + // - IOT Central (domain suffix and resource identifier are missing) + // - Service Bus (domain suffix and resource identifier are missing) + // - Traffic Manager (domain suffix is missing) + if e.Authorization == nil { e.Authorization = &Authorization{} } @@ -46,34 +53,52 @@ func (e *Environment) updateFromMetaData(config *metadata.MetaData) error { if config.Authentication.Tenant != "" { e.Authorization.Tenant = config.Authentication.Tenant } - if config.ResourceManagerEndpoint != "" { - e.ResourceManager = ResourceManagerAPI(config.ResourceManagerEndpoint) + + if config.DnsSuffixes.Attestation != "" && config.ResourceIdentifiers.Attestation != "" { + e.Attestation = AttestationAPI(config.ResourceIdentifiers.Attestation, config.DnsSuffixes.Attestation) } - if config.ResourceIdentifiers.MicrosoftGraph != "" { - e.MicrosoftGraph = MicrosoftGraphAPI(config.ResourceIdentifiers.MicrosoftGraph) + if config.ResourceIdentifiers.Batch != "" { + e.Batch = BatchAPI(config.ResourceIdentifiers.Batch) } - - // Dns Suffixes if config.DnsSuffixes.FrontDoor != "" { e.CDNFrontDoor = CDNFrontDoorAPI(config.DnsSuffixes.FrontDoor) } + if config.DnsSuffixes.ContainerRegistry != "" { + e.ContainerRegistry = ContainerRegistryAPI(config.DnsSuffixes.ContainerRegistry) + } + if config.DnsSuffixes.DataLakeStore != "" && config.ResourceIdentifiers.DataLake != "" { + e.DataLake = DataLakeAPI(config.DnsSuffixes.DataLakeStore).WithResourceIdentifier(config.ResourceIdentifiers.DataLake) + } if config.DnsSuffixes.KeyVault != "" { - e.KeyVault = KeyVaultAPI(config.DnsSuffixes.KeyVault) + // Key Vault resource ID is missing in metadata, so make a best-effort guess from the domain suffix + e.KeyVault = KeyVaultAPI(config.DnsSuffixes.KeyVault).WithResourceIdentifier(fmt.Sprintf("https://%s", config.DnsSuffixes.KeyVault)) } if config.DnsSuffixes.ManagedHSM != "" { - e.ManagedHSM = ManagedHSMAPI(fmt.Sprintf("https://%s", config.DnsSuffixes.ManagedHSM), config.DnsSuffixes.ManagedHSM) + // Managed HSM resource ID is missing in metadata, so make a best-effort guess from the domain suffix + mHsmEndpoint := fmt.Sprintf("https://%s", config.DnsSuffixes.ManagedHSM) + e.ManagedHSM = ManagedHSMAPI(mHsmEndpoint, config.DnsSuffixes.ManagedHSM).WithResourceIdentifier(mHsmEndpoint) + } + if config.DnsSuffixes.MariaDB != "" && config.ResourceIdentifiers.OSSRDBMS != "" { + e.MariaDB = MariaDBAPI(config.DnsSuffixes.MariaDB).WithResourceIdentifier(config.ResourceIdentifiers.OSSRDBMS) + } + if config.ResourceIdentifiers.MicrosoftGraph != "" { + e.MicrosoftGraph = MicrosoftGraphAPI(config.ResourceIdentifiers.MicrosoftGraph) + } + if config.DnsSuffixes.MySql != "" && config.ResourceIdentifiers.OSSRDBMS != "" { + e.MySql = MySqlAPI(config.DnsSuffixes.MySql).WithResourceIdentifier(config.ResourceIdentifiers.OSSRDBMS) } - if config.DnsSuffixes.MariaDB != "" { - e.MariaDB = MariaDBAPI(config.DnsSuffixes.MariaDB) + if config.ResourceIdentifiers.LogAnalytics != "" { + e.OperationalInsights = OperationalInsightsAPI().WithResourceIdentifier(config.ResourceIdentifiers.LogAnalytics) } - if config.DnsSuffixes.MySql != "" { - e.MySql = MySqlAPI(config.DnsSuffixes.MySql) + if config.DnsSuffixes.Postgresql != "" && config.ResourceIdentifiers.OSSRDBMS != "" { + e.Postgresql = PostgresqlAPI(config.DnsSuffixes.Postgresql).WithResourceIdentifier(config.ResourceIdentifiers.OSSRDBMS) } - if config.DnsSuffixes.Postgresql != "" { - e.Postgresql = PostgresqlAPI(config.DnsSuffixes.Postgresql) + if config.ResourceManagerEndpoint != "" { + e.ResourceManager = ResourceManagerAPI(config.ResourceManagerEndpoint) } if config.DnsSuffixes.SqlServer != "" { - e.Sql = SqlAPI(config.DnsSuffixes.SqlServer) + // SQL resource ID is missing in metadata, so make a best-effort guess from the domain suffix + e.Sql = SqlAPI(config.DnsSuffixes.SqlServer).WithResourceIdentifier(fmt.Sprintf("https://%s", config.DnsSuffixes.SqlServer)) } if config.DnsSuffixes.Storage != "" { e.Storage = StorageAPI(config.DnsSuffixes.Storage) @@ -81,8 +106,8 @@ func (e *Environment) updateFromMetaData(config *metadata.MetaData) error { if config.DnsSuffixes.StorageSync != "" { e.StorageSync = StorageSyncAPI(config.DnsSuffixes.StorageSync) } - if config.DnsSuffixes.Synapse != "" { - e.Synapse = SynapseAPI(config.DnsSuffixes.Synapse) + if config.DnsSuffixes.Synapse != "" && config.ResourceIdentifiers.Synapse != "" { + e.Synapse = SynapseAPI(config.DnsSuffixes.Synapse).WithResourceIdentifier(config.ResourceIdentifiers.Synapse) } return nil diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/environment.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/environment.go index 3c33b9b4c141..95ee694aa766 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/environment.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/environment.go @@ -160,9 +160,10 @@ func NewApiEndpoint(name, endpoint string, appId *string) *ApiEndpoint { } } -func (e *ApiEndpoint) withResourceIdentifier(identifier string) *ApiEndpoint { - e.resourceIdentifier = pointer.To(identifier) - return e +func (e *ApiEndpoint) WithResourceIdentifier(identifier string) Api { + newApi := *e + newApi.resourceIdentifier = pointer.To(identifier) + return &newApi } func (e *ApiEndpoint) Available() bool { diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/from_endpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/from_endpoint.go index 1d0debe5dd58..e6efd39b8702 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/from_endpoint.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/from_endpoint.go @@ -11,11 +11,11 @@ import ( ) // FromEndpoint attempts to load an environment from the given Endpoint. -func FromEndpoint(ctx context.Context, endpoint, name string) (*Environment, error) { +func FromEndpoint(ctx context.Context, endpoint string) (*Environment, error) { env := baseEnvironmentWithName("FromEnvironment") client := metadata.NewClientWithEndpoint(endpoint) - config, err := client.GetMetaData(ctx, name) + config, err := client.GetMetaData(ctx) if err != nil { return nil, fmt.Errorf("retrieving metadata from endpoint %q: %+v", endpoint, err) } @@ -35,7 +35,7 @@ func FromEndpoint(ctx context.Context, endpoint, name string) (*Environment, err } env.MicrosoftGraph = MicrosoftGraphAPI(config.ResourceIdentifiers.MicrosoftGraph) - if err := env.updateFromMetaData(config); err != nil { + if err = env.updateFromMetaData(config); err != nil { return nil, fmt.Errorf("updating Environment from MetaData: %+v", err) } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/helpers.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/helpers.go index 81cf19d57b52..64ed4bd111c2 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/helpers.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/helpers.go @@ -5,7 +5,7 @@ package environments import "github.com/hashicorp/go-azure-helpers/lang/pointer" -func applicationIdOnly(name, applicationId string) Api { +func applicationIdOnly(name, applicationId string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: nil, endpoint: nil, @@ -15,7 +15,7 @@ func applicationIdOnly(name, applicationId string) Api { } } -func ApiManagementAPI(domainSuffix string) Api { +func ApiManagementAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, @@ -25,7 +25,7 @@ func ApiManagementAPI(domainSuffix string) Api { } } -func AppConfigurationAPI(domainSuffix string) Api { +func AppConfigurationAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, @@ -35,27 +35,29 @@ func AppConfigurationAPI(domainSuffix string) Api { } } -func AttestationAPI(endpoint string) Api { +func AttestationAPI(endpoint, domainSuffix string) *ApiEndpoint { + // endpoint and resource ID are the same, only the resource ID is returned in metadata return &ApiEndpoint{ - domainSuffix: nil, + domainSuffix: pointer.To(domainSuffix), endpoint: pointer.To(endpoint), appId: pointer.To(attestationServiceAppId), name: "AttestationService", - resourceIdentifier: nil, + resourceIdentifier: pointer.To(endpoint), } } -func BatchAPI(endpoint string) *ApiEndpoint { +func BatchAPI(resourceId string) *ApiEndpoint { + // endpoint and resource ID are the same, only the resource ID is returned in metadata return &ApiEndpoint{ domainSuffix: nil, - endpoint: pointer.To(endpoint), + endpoint: pointer.To(resourceId), appId: pointer.To(batchAppId), name: "Batch", - resourceIdentifier: pointer.To(endpoint), + resourceIdentifier: pointer.To(resourceId), } } -func CDNFrontDoorAPI(domainSuffix string) Api { +func CDNFrontDoorAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, @@ -65,7 +67,7 @@ func CDNFrontDoorAPI(domainSuffix string) Api { } } -func ContainerRegistryAPI(domainSuffix string) Api { +func ContainerRegistryAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, @@ -75,33 +77,33 @@ func ContainerRegistryAPI(domainSuffix string) Api { } } -func CosmosDBAPI(domainSuffix string) Api { +func CosmosDBAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, appId: pointer.To(cosmosDBAppId), name: "AzureCosmosDb", - resourceIdentifier: pointer.To("https://cosmos.azure.com"), + resourceIdentifier: nil, } } -func DataLakeAPI(domainSuffix string) Api { +func DataLakeAPI(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, appId: pointer.To(dataLakeAppId), name: "DataLake", - resourceIdentifier: pointer.To("https://datalake.azure.net"), + resourceIdentifier: nil, } } -func IoTCentral(domainSuffix string) Api { +func IoTCentral(domainSuffix string) *ApiEndpoint { return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, appId: pointer.To(iotCentralAppId), name: "IoTCentral", - resourceIdentifier: pointer.To("https://apps.azureiotcentral.com"), + resourceIdentifier: nil, } } @@ -111,11 +113,12 @@ func KeyVaultAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(keyVaultAppId), name: "AzureKeyVault", - resourceIdentifier: pointer.To("https://vault.azure.net"), + resourceIdentifier: nil, } } -func ManagedHSMAPI(endpoint, domainSuffix string) Api { +func ManagedHSMAPI(endpoint, domainSuffix string) *ApiEndpoint { + // endpoint and resource ID are the same, only the domainSuffix is returned in metadata return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: pointer.To(endpoint), @@ -131,17 +134,17 @@ func MariaDBAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(ossRDBMSAppId), name: "OssRdbms", - resourceIdentifier: pointer.To("https://ossrdbms-aad.database.windows.net"), + resourceIdentifier: nil, } } -func MicrosoftGraphAPI(endpoint string) *ApiEndpoint { +func MicrosoftGraphAPI(resourceId string) *ApiEndpoint { + // endpoint and resource ID are the same, only the resource ID is returned in metadata return &ApiEndpoint{ - domainSuffix: nil, - endpoint: pointer.To(endpoint), + endpoint: pointer.To(resourceId), appId: pointer.To(microsoftGraphAppId), name: "MicrosoftGraph", - resourceIdentifier: pointer.To(endpoint), + resourceIdentifier: pointer.To(resourceId), } } @@ -151,7 +154,7 @@ func MySqlAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(ossRDBMSAppId), name: "OssRdbms", - resourceIdentifier: pointer.To("https://ossrdbms-aad.database.windows.net"), + resourceIdentifier: nil, } } @@ -161,7 +164,7 @@ func OperationalInsightsAPI() *ApiEndpoint { endpoint: nil, appId: pointer.To(logAnalyticsAppId), name: "OperationalInsights", - resourceIdentifier: pointer.To("https://api.loganalytics.io"), + resourceIdentifier: nil, } } @@ -171,11 +174,12 @@ func PostgresqlAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(ossRDBMSAppId), name: "OssRdbms", - resourceIdentifier: pointer.To("https://ossrdbms-aad.database.windows.net"), + resourceIdentifier: nil, } } func ResourceManagerAPI(endpoint string) *ApiEndpoint { + // endpoint and resource ID are the same, only the endpoint is returned in metadata return &ApiEndpoint{ domainSuffix: nil, endpoint: pointer.To(endpoint), @@ -191,7 +195,7 @@ func ServiceBusAPI(endpoint, domainSuffix string) Api { endpoint: pointer.To(endpoint), appId: pointer.To(serviceBusAppId), name: "ServiceBus", - resourceIdentifier: pointer.To(endpoint), + resourceIdentifier: nil, } } @@ -201,11 +205,14 @@ func SqlAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(sqlDatabaseAppId), name: "AzureSqlDatabase", - resourceIdentifier: pointer.To("https://database.windows.net"), + resourceIdentifier: nil, } } func StorageAPI(domainSuffix string) *ApiEndpoint { + // The default resource identifier for Azure Storage is the same for all public and sovereign clouds. This can be + // changed to scope the token for authorizing against a single storage account. + // https://learn.microsoft.com/en-us/azure/storage/blobs/authorize-access-azure-active-directory#microsoft-authentication-library-msal return &ApiEndpoint{ domainSuffix: pointer.To(domainSuffix), endpoint: nil, @@ -231,7 +238,7 @@ func SynapseAPI(domainSuffix string) *ApiEndpoint { endpoint: nil, appId: pointer.To(synapseAppId), name: "Synapse", - resourceIdentifier: pointer.To("https://dev.azuresynapse.net"), + resourceIdentifier: nil, } } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/interfaces.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/interfaces.go index 58e5e50bb4aa..599759eef9a2 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/interfaces.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/environments/interfaces.go @@ -4,10 +4,25 @@ package environments type Api interface { + // AppId is a GUID that identifies the application/API in the cloud environment AppId() (*string, bool) + + // Available returns whether the application/API is supported in the cloud environment Available() bool + + // DomainSuffix is the specific domain suffix for constructing endpoints for a data plane API in the cloud environment DomainSuffix() (*string, bool) + + // Endpoint is the common endpoint for the application/API in the cloud environment Endpoint() (*string, bool) + + // Name returns the name of the application/API Name() string + + // ResourceIdentifier is a URI that identifies the application/API in the cloud environment and + // is used for constructing scopes/roles when authorizing connections. ResourceIdentifier() (*string, bool) + + // WithResourceIdentifier overrides the default resource ID for the API and is useful for APIs that offer multiple authorization scopes + WithResourceIdentifier(string) Api } diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/client.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/client.go index 3c80fa11da3f..c9bc16f72263 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/client.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/client.go @@ -30,55 +30,9 @@ func NewClientWithEndpoint(endpoint string) *Client { } // GetMetaData connects to the ARM metadata service at the configured endpoint, to retrieve information about the -// current environment. Sometimes an endpoint will not support the latest schema, in such cases it will not be -// possible to configure all services but a best effort will be made to request and parse an earlier schema version. -// `name` is used when falling back to an earlier schema version where multiple environments are returned and the -// desired one must be matched by name. -func (c *Client) GetMetaData(ctx context.Context, name string) (*MetaData, error) { - metadata, err := c.getMetaDataFrom2022API(ctx, name) - if err != nil { - log.Printf("[DEBUG] Falling back to ARM Metadata version 2019-05-01 for %s", c.endpoint) - metadata, err = c.getMetaDataFrom2019API(ctx, name) - if err != nil { - return nil, fmt.Errorf("retrieving metadata from the 2022-09-01 and 2019-05-01 APIs: %+v", err) - } - } - - return &MetaData{ - Authentication: Authentication{ - Audiences: metadata.Authentication.Audiences, - LoginEndpoint: metadata.Authentication.LoginEndpoint, - IdentityProvider: metadata.Authentication.IdentityProvider, - Tenant: metadata.Authentication.Tenant, - }, - DnsSuffixes: DnsSuffixes{ - Attestation: metadata.Suffixes.AttestationEndpoint, - FrontDoor: metadata.Suffixes.AzureFrontDoorEndpointSuffix, - KeyVault: metadata.Suffixes.KeyVaultDns, - ManagedHSM: metadata.Suffixes.MhsmDns, - MariaDB: metadata.Suffixes.MariadbServerEndpoint, - MySql: metadata.Suffixes.MysqlServerEndpoint, - Postgresql: metadata.Suffixes.PostgresqlServerEndpoint, - SqlServer: metadata.Suffixes.SqlServerHostname, - Storage: metadata.Suffixes.Storage, - StorageSync: metadata.Suffixes.StorageSyncEndpointSuffix, - Synapse: metadata.Suffixes.SynapseAnalytics, - }, - Name: metadata.Name, - ResourceIdentifiers: ResourceIdentifiers{ - Attestation: normalizeResourceId(metadata.AttestationResourceId), - Batch: normalizeResourceId(metadata.Batch), - LogAnalytics: normalizeResourceId(metadata.LogAnalyticsResourceId), - Media: normalizeResourceId(metadata.Media), - MicrosoftGraph: normalizeResourceId(metadata.MicrosoftGraphResourceId), - OSSRDBMS: normalizeResourceId(metadata.OssrDbmsResourceId), - Synapse: normalizeResourceId(metadata.SynapseAnalyticsResourceId), - }, - ResourceManagerEndpoint: metadata.ResourceManager, - }, nil -} - -func (c *Client) getMetaDataFrom2022API(ctx context.Context, name string) (*metaDataResponse, error) { +// current environment. We currently only support the 2019-05-01 metadata schema, since earlier versions do not +// reference some mandatory services, notably Microsoft Graph. +func (c *Client) GetMetaData(ctx context.Context) (*MetaData, error) { tlsConfig := tls.Config{ MinVersion: tls.VersionTLS12, } @@ -122,78 +76,47 @@ func (c *Client) getMetaDataFrom2022API(ctx context.Context, name string) (*meta // Trim away a BOM if present respBody = bytes.TrimPrefix(respBody, []byte("\xef\xbb\xbf")) - var model *metaDataResponse - if err := json.Unmarshal(respBody, &model); err != nil { + var metadata *metaDataResponse + if err := json.Unmarshal(respBody, &metadata); err != nil { log.Printf("[DEBUG] Unrecognised metadata response for %s: %s", uri, respBody) return nil, fmt.Errorf("unmarshaling response: %+v", err) } - return model, nil -} - -func (c *Client) getMetaDataFrom2019API(ctx context.Context, name string) (*metaDataResponse, error) { - tlsConfig := tls.Config{ - MinVersion: tls.VersionTLS12, - } - client := &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - d := &net.Dialer{Resolver: &net.Resolver{}} - return d.DialContext(ctx, network, addr) - }, - TLSClientConfig: &tlsConfig, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - ForceAttemptHTTP2: true, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, + return &MetaData{ + Authentication: Authentication{ + Audiences: metadata.Authentication.Audiences, + LoginEndpoint: metadata.Authentication.LoginEndpoint, + IdentityProvider: metadata.Authentication.IdentityProvider, + Tenant: metadata.Authentication.Tenant, }, - } - uri := fmt.Sprintf("%s/metadata/endpoints?api-version=2019-05-01", c.endpoint) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, fmt.Errorf("preparing request: %+v", err) - } - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("performing request: %+v", err) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("performing request: expected 200 OK but got %d %s", resp.StatusCode, resp.Status) - } - - respBody, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("parsing response body: %+v", err) - } - resp.Body.Close() - - // Trim away a BOM if present - respBody = bytes.TrimPrefix(respBody, []byte("\xef\xbb\xbf")) - - var model *[]metaDataResponse - if err := json.Unmarshal(respBody, &model); err != nil { - log.Printf("[DEBUG] Unrecognised metadata response for %s: %s", uri, respBody) - return nil, fmt.Errorf("unmarshaling response: %+v", err) - } - - if model == nil { - return nil, fmt.Errorf("unmarshaling response: no environments returned") - } - - // This version returns an array of environments, we are only interested in one - var env metaDataResponse - for _, e := range *model { - if name == "" || e.Name == name { - env = e - break - } - } - return &env, nil + DnsSuffixes: DnsSuffixes{ + Attestation: metadata.Suffixes.AttestationEndpoint, + ContainerRegistry: metadata.Suffixes.AcrLoginServer, + DataLakeStore: metadata.Suffixes.AzureDataLakeStoreFileSystem, + FrontDoor: metadata.Suffixes.AzureFrontDoorEndpointSuffix, + KeyVault: metadata.Suffixes.KeyVaultDns, + ManagedHSM: metadata.Suffixes.MhsmDns, + MariaDB: metadata.Suffixes.MariadbServerEndpoint, + MySql: metadata.Suffixes.MysqlServerEndpoint, + Postgresql: metadata.Suffixes.PostgresqlServerEndpoint, + SqlServer: metadata.Suffixes.SqlServerHostname, + Storage: metadata.Suffixes.Storage, + StorageSync: metadata.Suffixes.StorageSyncEndpointSuffix, + Synapse: metadata.Suffixes.SynapseAnalytics, + }, + Name: metadata.Name, + ResourceIdentifiers: ResourceIdentifiers{ + Attestation: normalizeResourceId(metadata.AttestationResourceId), + Batch: normalizeResourceId(metadata.Batch), + DataLake: normalizeResourceId(metadata.ActiveDirectoryDataLake), + LogAnalytics: normalizeResourceId(metadata.LogAnalyticsResourceId), + Media: normalizeResourceId(metadata.Media), + MicrosoftGraph: normalizeResourceId(metadata.MicrosoftGraphResourceId), + OSSRDBMS: normalizeResourceId(metadata.OssrDbmsResourceId), + Synapse: normalizeResourceId(metadata.SynapseAnalyticsResourceId), + }, + ResourceManagerEndpoint: metadata.ResourceManager, + }, nil } type metaDataResponse struct { diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/models.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/models.go index ebad1ceb90b8..b6120a759f2b 100644 --- a/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/models.go +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/internal/metadata/models.go @@ -19,22 +19,25 @@ type Authentication struct { } type DnsSuffixes struct { - Attestation string - FrontDoor string - KeyVault string - ManagedHSM string - MariaDB string - MySql string - Postgresql string - SqlServer string - Storage string - StorageSync string - Synapse string + Attestation string + ContainerRegistry string + DataLakeStore string + FrontDoor string + KeyVault string + ManagedHSM string + MariaDB string + MySql string + Postgresql string + SqlServer string + Storage string + StorageSync string + Synapse string } type ResourceIdentifiers struct { Attestation string Batch string + DataLake string LogAnalytics string Media string MicrosoftGraph string diff --git a/vendor/modules.txt b/vendor/modules.txt index 377df1c3664e..4a7c1c351169 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -151,7 +151,7 @@ github.com/hashicorp/go-azure-helpers/resourcemanager/tags github.com/hashicorp/go-azure-helpers/resourcemanager/zones github.com/hashicorp/go-azure-helpers/sender github.com/hashicorp/go-azure-helpers/storage -# github.com/hashicorp/go-azure-sdk/resource-manager v0.20240409.1113035 +# github.com/hashicorp/go-azure-sdk/resource-manager v0.20240411.1104331 ## explicit; go 1.21 github.com/hashicorp/go-azure-sdk/resource-manager/aad/2021-05-01/domainservices github.com/hashicorp/go-azure-sdk/resource-manager/aadb2c/2021-04-01-preview @@ -1078,7 +1078,7 @@ github.com/hashicorp/go-azure-sdk/resource-manager/workloads/2023-04-01/saplands github.com/hashicorp/go-azure-sdk/resource-manager/workloads/2023-04-01/saprecommendations github.com/hashicorp/go-azure-sdk/resource-manager/workloads/2023-04-01/sapsupportedsku github.com/hashicorp/go-azure-sdk/resource-manager/workloads/2023-04-01/sapvirtualinstances -# github.com/hashicorp/go-azure-sdk/sdk v0.20240409.1113035 +# github.com/hashicorp/go-azure-sdk/sdk v0.20240411.1104331 ## explicit; go 1.21 github.com/hashicorp/go-azure-sdk/sdk/auth github.com/hashicorp/go-azure-sdk/sdk/auth/autorest diff --git a/website/docs/index.html.markdown b/website/docs/index.html.markdown index 8a9f14886329..5a2b71572ace 100644 --- a/website/docs/index.html.markdown +++ b/website/docs/index.html.markdown @@ -107,7 +107,7 @@ The following arguments are supported: * `client_id_file_path` (Optional) The path to a file containing the Client ID which should be used. This can also be sourced from the `ARM_CLIENT_ID_FILE_PATH` Environment Variable. -* `environment` - (Optional) The Cloud Environment which should be used. Possible values are `public`, `usgovernment`, `german`, and `china`. Defaults to `public`. This can also be sourced from the `ARM_ENVIRONMENT` Environment Variable. +* `environment` - (Optional) The Cloud Environment which should be used. Possible values are `public`, `usgovernment`, `german`, and `china`. Defaults to `public`. This can also be sourced from the `ARM_ENVIRONMENT` Environment Variable. Not used when `metadata_host` is specified. * `subscription_id` - (Optional) The Subscription ID which should be used. This can also be sourced from the `ARM_SUBSCRIPTION_ID` Environment Variable.