diff --git a/backend/remote-state/azure/arm_client.go b/backend/remote-state/azure/arm_client.go index bcc511a44..7316b254c 100644 --- a/backend/remote-state/azure/arm_client.go +++ b/backend/remote-state/azure/arm_client.go @@ -13,9 +13,9 @@ import ( armStorage "github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage" "github.com/Azure/azure-sdk-for-go/storage" "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/hashicorp/go-azure-helpers/authentication" + "github.com/hashicorp/go-azure-helpers/sender" "github.com/hashicorp/terraform/httpclient" ) @@ -75,12 +75,12 @@ func buildArmClient(config BackendConfig) (*ArmClient, error) { return nil, fmt.Errorf("Error building ARM Config: %+v", err) } - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, armConfig.TenantID) + oauthConfig, err := armConfig.BuildOAuthConfig(env.ActiveDirectoryEndpoint) if err != nil { return nil, err } - auth, err := armConfig.GetAuthorizationToken(oauthConfig, env.TokenAudience) + auth, err := armConfig.GetAuthorizationToken(sender.BuildSender("backend/remote-state/azure"), oauthConfig, env.TokenAudience) if err != nil { return nil, err } diff --git a/go.mod b/go.mod index f0a464812..aa7d2056a 100644 --- a/go.mod +++ b/go.mod @@ -2,8 +2,9 @@ module github.com/hashicorp/terraform require ( cloud.google.com/go v0.45.1 - github.com/Azure/azure-sdk-for-go v21.3.0+incompatible - github.com/Azure/go-autorest v10.15.4+incompatible + github.com/Azure/azure-sdk-for-go v36.2.0+incompatible + github.com/Azure/go-autorest/autorest v0.9.2 + github.com/Azure/go-autorest/autorest/adal v0.8.1-0.20191028180845-3492b2aff503 github.com/Unknwon/com v0.0.0-20151008135407-28b053d5a292 // indirect github.com/abdullin/seq v0.0.0-20160510034733-d5467c17e7af // indirect github.com/agext/levenshtein v1.2.2 @@ -52,7 +53,7 @@ require ( github.com/hashicorp/aws-sdk-go-base v0.4.0 github.com/hashicorp/consul v0.0.0-20171026175957-610f3c86a089 github.com/hashicorp/errwrap v1.0.0 - github.com/hashicorp/go-azure-helpers v0.0.0-20190129193224-166dfd221bb2 + github.com/hashicorp/go-azure-helpers v0.10.0 github.com/hashicorp/go-checkpoint v0.5.0 github.com/hashicorp/go-cleanhttp v0.5.1 github.com/hashicorp/go-getter v1.4.0 diff --git a/go.sum b/go.sum index eade89027..4508c7352 100644 --- a/go.sum +++ b/go.sum @@ -9,8 +9,36 @@ cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbf cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= github.com/Azure/azure-sdk-for-go v21.3.0+incompatible h1:YFvAka2WKAl2xnJkYV1e1b7E2z88AgFszDzWU18ejMY= github.com/Azure/azure-sdk-for-go v21.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go v35.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go v36.2.0+incompatible h1:09cv2WoH0g6jl6m2iT+R9qcIPZKhXEL0sbmLhxP895s= +github.com/Azure/azure-sdk-for-go v36.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-autorest v10.15.4+incompatible h1:q+DRrRdbCnkY7f2WxQBx58TwCGkEdMAK/hkZ10g0Pzk= github.com/Azure/go-autorest v10.15.4+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest v13.3.0+incompatible h1:8Ix0VdeOllBx9jEcZ2Wb1uqWUpE1awmJiaHztwaJCPk= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest v0.9.2 h1:6AWuh3uWrsZJcNoCHrCF/+g4aKPCU39kaMO6/qrnK/4= +github.com/Azure/go-autorest/autorest v0.9.2/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/adal v0.8.1-0.20191028180845-3492b2aff503 h1:Hxqlh1uAA8aGpa1dFhDNhll7U/rkWtG8ZItFvRMr7l0= +github.com/Azure/go-autorest/autorest/adal v0.8.1-0.20191028180845-3492b2aff503/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= +github.com/Azure/go-autorest/autorest/azure/cli v0.2.0 h1:pSwNMF0qotgehbQNllUWwJ4V3vnrLKOzHrwDLEZK904= +github.com/Azure/go-autorest/autorest/azure/cli v0.2.0/go.mod h1:WWTbGPvkAg3I4ms2j2s+Zr5xCGwGqTQh+6M2ZqOczkE= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/date v0.2.0 h1:yW+Zlqf26583pE43KhfnhFcdmSWlm5Ew6bxipnr/tbM= +github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= +github.com/Azure/go-autorest/autorest/to v0.3.0 h1:zebkZaadz7+wIQYgC7GXaz3Wb28yKYfVkkBKwc38VF8= +github.com/Azure/go-autorest/autorest/to v0.3.0/go.mod h1:MgwOyqaIuKdG4TL/2ywSsIWKAfJfgHDo8ObuUk3t5sA= +github.com/Azure/go-autorest/autorest/validation v0.2.0 h1:15vMO4y76dehZSq7pAaOLQxC6dZYsSrj2GQpflyM/L4= +github.com/Azure/go-autorest/autorest/validation v0.2.0/go.mod h1:3EEqHnBxQGHXRYq3HT1WyXAvT7LLY3tl70hw6tQIbjI= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= github.com/Azure/go-ntlmssp v0.0.0-20180810175552-4a21cbd618b4 h1:pSm8mp0T2OH2CPmPDPtwHPr3VAQaOwVF/JbllOPP4xA= github.com/Azure/go-ntlmssp v0.0.0-20180810175552-4a21cbd618b4/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -95,6 +123,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumC github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dimchansky/utfbom v1.0.0 h1:fGC2kkf4qOoKqZ4q7iIh+Vef4ubC1c38UDsEyZynZPc= github.com/dimchansky/utfbom v1.0.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= +github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4= +github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= github.com/dnaeon/go-vcr v0.0.0-20180920040454-5637cf3d8a31 h1:Dzuw9GtbmllUqEcoHfScT9YpKFUssSiZ5PgZkIGf/YQ= github.com/dnaeon/go-vcr v0.0.0-20180920040454-5637cf3d8a31/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= github.com/dylanmei/iso8601 v0.1.0 h1:812NGQDBcqquTfH5Yeo7lwR0nzx/cKdsmf3qMjPURUI= @@ -171,6 +201,8 @@ github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/U github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-azure-helpers v0.0.0-20190129193224-166dfd221bb2 h1:VBRx+yPYUZaobnn5ANBcOUf4hhWpTHSQgftG4TcDkhI= github.com/hashicorp/go-azure-helpers v0.0.0-20190129193224-166dfd221bb2/go.mod h1:lu62V//auUow6k0IykxLK2DCNW8qTmpm8KqhYVWattA= +github.com/hashicorp/go-azure-helpers v0.10.0 h1:KhjDnQhCqEMKlt4yH00MCevJQPJ6LkHFdSveXINO6vE= +github.com/hashicorp/go-azure-helpers v0.10.0/go.mod h1:YuAtHxm2v74s+IjQwUG88dHBJPd5jL+cXr5BGVzSKhE= 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 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources/models.go b/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources/models.go index c1e080fbd..94a1a8b8e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources/models.go @@ -1,6 +1,6 @@ // +build go1.9 -// Copyright 2018 Microsoft Corporation +// Copyright 2019 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,16 +19,16 @@ package resources -import original "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources" +import ( + "context" + + original "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources" +) const ( DefaultBaseURI = original.DefaultBaseURI ) -type BaseClient = original.BaseClient -type DeploymentOperationsClient = original.DeploymentOperationsClient -type DeploymentsClient = original.DeploymentsClient -type GroupsClient = original.GroupsClient type DeploymentMode = original.DeploymentMode const ( @@ -44,7 +44,10 @@ const ( type AliasPathType = original.AliasPathType type AliasType = original.AliasType +type BaseClient = original.BaseClient type BasicDependency = original.BasicDependency +type Client = original.Client +type CloudError = original.CloudError type DebugSetting = original.DebugSetting type Dependency = original.Dependency type Deployment = original.Deployment @@ -56,14 +59,18 @@ type DeploymentListResultIterator = original.DeploymentListResultIterator type DeploymentListResultPage = original.DeploymentListResultPage type DeploymentOperation = original.DeploymentOperation type DeploymentOperationProperties = original.DeploymentOperationProperties +type DeploymentOperationsClient = original.DeploymentOperationsClient type DeploymentOperationsListResult = original.DeploymentOperationsListResult type DeploymentOperationsListResultIterator = original.DeploymentOperationsListResultIterator type DeploymentOperationsListResultPage = original.DeploymentOperationsListResultPage type DeploymentProperties = original.DeploymentProperties type DeploymentPropertiesExtended = original.DeploymentPropertiesExtended +type DeploymentValidateResult = original.DeploymentValidateResult +type DeploymentsClient = original.DeploymentsClient type DeploymentsCreateOrUpdateFuture = original.DeploymentsCreateOrUpdateFuture type DeploymentsDeleteFuture = original.DeploymentsDeleteFuture -type DeploymentValidateResult = original.DeploymentValidateResult +type ErrorAdditionalInfo = original.ErrorAdditionalInfo +type ErrorResponse = original.ErrorResponse type ExportTemplateRequest = original.ExportTemplateRequest type GenericResource = original.GenericResource type GenericResourceFilter = original.GenericResourceFilter @@ -74,6 +81,7 @@ type GroupListResult = original.GroupListResult type GroupListResultIterator = original.GroupListResultIterator type GroupListResultPage = original.GroupListResultPage type GroupProperties = original.GroupProperties +type GroupsClient = original.GroupsClient type GroupsDeleteFuture = original.GroupsDeleteFuture type HTTPMessage = original.HTTPMessage type Identity = original.Identity @@ -91,70 +99,106 @@ type ProviderListResultIterator = original.ProviderListResultIterator type ProviderListResultPage = original.ProviderListResultPage type ProviderOperationDisplayProperties = original.ProviderOperationDisplayProperties type ProviderResourceType = original.ProviderResourceType +type ProvidersClient = original.ProvidersClient type Resource = original.Resource type Sku = original.Sku type SubResource = original.SubResource type TagCount = original.TagCount type TagDetails = original.TagDetails +type TagValue = original.TagValue +type TagsClient = original.TagsClient type TagsListResult = original.TagsListResult type TagsListResultIterator = original.TagsListResultIterator type TagsListResultPage = original.TagsListResultPage -type TagValue = original.TagValue type TargetResource = original.TargetResource +type TemplateHashResult = original.TemplateHashResult type TemplateLink = original.TemplateLink type UpdateFuture = original.UpdateFuture -type ProvidersClient = original.ProvidersClient -type Client = original.Client -type TagsClient = original.TagsClient func New(subscriptionID string) BaseClient { return original.New(subscriptionID) } -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return original.NewWithBaseURI(baseURI, subscriptionID) -} -func NewDeploymentOperationsClient(subscriptionID string) DeploymentOperationsClient { - return original.NewDeploymentOperationsClient(subscriptionID) -} -func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentOperationsClient { - return original.NewDeploymentOperationsClientWithBaseURI(baseURI, subscriptionID) -} -func NewDeploymentsClient(subscriptionID string) DeploymentsClient { - return original.NewDeploymentsClient(subscriptionID) -} -func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentsClient { - return original.NewDeploymentsClientWithBaseURI(baseURI, subscriptionID) -} -func NewGroupsClient(subscriptionID string) GroupsClient { - return original.NewGroupsClient(subscriptionID) -} -func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient { - return original.NewGroupsClientWithBaseURI(baseURI, subscriptionID) -} -func PossibleDeploymentModeValues() []DeploymentMode { - return original.PossibleDeploymentModeValues() -} -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return original.PossibleResourceIdentityTypeValues() -} -func NewProvidersClient(subscriptionID string) ProvidersClient { - return original.NewProvidersClient(subscriptionID) -} -func NewProvidersClientWithBaseURI(baseURI string, subscriptionID string) ProvidersClient { - return original.NewProvidersClientWithBaseURI(baseURI, subscriptionID) -} func NewClient(subscriptionID string) Client { return original.NewClient(subscriptionID) } func NewClientWithBaseURI(baseURI string, subscriptionID string) Client { return original.NewClientWithBaseURI(baseURI, subscriptionID) } +func NewDeploymentListResultIterator(page DeploymentListResultPage) DeploymentListResultIterator { + return original.NewDeploymentListResultIterator(page) +} +func NewDeploymentListResultPage(getNextPage func(context.Context, DeploymentListResult) (DeploymentListResult, error)) DeploymentListResultPage { + return original.NewDeploymentListResultPage(getNextPage) +} +func NewDeploymentOperationsClient(subscriptionID string) DeploymentOperationsClient { + return original.NewDeploymentOperationsClient(subscriptionID) +} +func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentOperationsClient { + return original.NewDeploymentOperationsClientWithBaseURI(baseURI, subscriptionID) +} +func NewDeploymentOperationsListResultIterator(page DeploymentOperationsListResultPage) DeploymentOperationsListResultIterator { + return original.NewDeploymentOperationsListResultIterator(page) +} +func NewDeploymentOperationsListResultPage(getNextPage func(context.Context, DeploymentOperationsListResult) (DeploymentOperationsListResult, error)) DeploymentOperationsListResultPage { + return original.NewDeploymentOperationsListResultPage(getNextPage) +} +func NewDeploymentsClient(subscriptionID string) DeploymentsClient { + return original.NewDeploymentsClient(subscriptionID) +} +func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentsClient { + return original.NewDeploymentsClientWithBaseURI(baseURI, subscriptionID) +} +func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator { + return original.NewGroupListResultIterator(page) +} +func NewGroupListResultPage(getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage { + return original.NewGroupListResultPage(getNextPage) +} +func NewGroupsClient(subscriptionID string) GroupsClient { + return original.NewGroupsClient(subscriptionID) +} +func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient { + return original.NewGroupsClientWithBaseURI(baseURI, subscriptionID) +} +func NewListResultIterator(page ListResultPage) ListResultIterator { + return original.NewListResultIterator(page) +} +func NewListResultPage(getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage { + return original.NewListResultPage(getNextPage) +} +func NewProviderListResultIterator(page ProviderListResultPage) ProviderListResultIterator { + return original.NewProviderListResultIterator(page) +} +func NewProviderListResultPage(getNextPage func(context.Context, ProviderListResult) (ProviderListResult, error)) ProviderListResultPage { + return original.NewProviderListResultPage(getNextPage) +} +func NewProvidersClient(subscriptionID string) ProvidersClient { + return original.NewProvidersClient(subscriptionID) +} +func NewProvidersClientWithBaseURI(baseURI string, subscriptionID string) ProvidersClient { + return original.NewProvidersClientWithBaseURI(baseURI, subscriptionID) +} func NewTagsClient(subscriptionID string) TagsClient { return original.NewTagsClient(subscriptionID) } func NewTagsClientWithBaseURI(baseURI string, subscriptionID string) TagsClient { return original.NewTagsClientWithBaseURI(baseURI, subscriptionID) } +func NewTagsListResultIterator(page TagsListResultPage) TagsListResultIterator { + return original.NewTagsListResultIterator(page) +} +func NewTagsListResultPage(getNextPage func(context.Context, TagsListResult) (TagsListResult, error)) TagsListResultPage { + return original.NewTagsListResultPage(getNextPage) +} +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return original.NewWithBaseURI(baseURI, subscriptionID) +} +func PossibleDeploymentModeValues() []DeploymentMode { + return original.PossibleDeploymentModeValues() +} +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return original.PossibleResourceIdentityTypeValues() +} func UserAgent() string { return original.UserAgent() + " profiles/2017-03-09" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage/models.go b/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage/models.go index d638c2a81..1af1d6eb0 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage/models.go @@ -1,6 +1,6 @@ // +build go1.9 -// Copyright 2018 Microsoft Corporation +// Copyright 2019 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,13 +21,10 @@ package storage import original "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage" -type AccountsClient = original.AccountsClient - const ( DefaultBaseURI = original.DefaultBaseURI ) -type BaseClient = original.BaseClient type AccessTier = original.AccessTier const ( @@ -109,8 +106,10 @@ type AccountProperties = original.AccountProperties type AccountPropertiesCreateParameters = original.AccountPropertiesCreateParameters type AccountPropertiesUpdateParameters = original.AccountPropertiesUpdateParameters type AccountRegenerateKeyParameters = original.AccountRegenerateKeyParameters -type AccountsCreateFuture = original.AccountsCreateFuture type AccountUpdateParameters = original.AccountUpdateParameters +type AccountsClient = original.AccountsClient +type AccountsCreateFuture = original.AccountsCreateFuture +type BaseClient = original.BaseClient type CheckNameAvailabilityResult = original.CheckNameAvailabilityResult type CustomDomain = original.CustomDomain type Encryption = original.Encryption @@ -120,18 +119,24 @@ type Endpoints = original.Endpoints type Resource = original.Resource type Sku = original.Sku type Usage = original.Usage +type UsageClient = original.UsageClient type UsageListResult = original.UsageListResult type UsageName = original.UsageName -type UsageClient = original.UsageClient +func New(subscriptionID string) BaseClient { + return original.New(subscriptionID) +} func NewAccountsClient(subscriptionID string) AccountsClient { return original.NewAccountsClient(subscriptionID) } func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) AccountsClient { return original.NewAccountsClientWithBaseURI(baseURI, subscriptionID) } -func New(subscriptionID string) BaseClient { - return original.New(subscriptionID) +func NewUsageClient(subscriptionID string) UsageClient { + return original.NewUsageClient(subscriptionID) +} +func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient { + return original.NewUsageClientWithBaseURI(baseURI, subscriptionID) } func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { return original.NewWithBaseURI(baseURI, subscriptionID) @@ -163,12 +168,6 @@ func PossibleSkuTierValues() []SkuTier { func PossibleUsageUnitValues() []UsageUnit { return original.PossibleUsageUnitValues() } -func NewUsageClient(subscriptionID string) UsageClient { - return original.NewUsageClient(subscriptionID) -} -func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient { - return original.NewUsageClientWithBaseURI(baseURI, subscriptionID) -} func UserAgent() string { return original.UserAgent() + " profiles/2017-03-09" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/applications.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/applications.go new file mode 100644 index 000000000..fab7676fa --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/applications.go @@ -0,0 +1,1177 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ApplicationsClient is the the Graph RBAC Management Client +type ApplicationsClient struct { + BaseClient +} + +// NewApplicationsClient creates an instance of the ApplicationsClient client. +func NewApplicationsClient(tenantID string) ApplicationsClient { + return NewApplicationsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewApplicationsClientWithBaseURI creates an instance of the ApplicationsClient client. +func NewApplicationsClientWithBaseURI(baseURI string, tenantID string) ApplicationsClient { + return ApplicationsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// AddOwner add an owner to an application. +// Parameters: +// applicationObjectID - the object ID of the application to which to add the owner. +// parameters - the URL of the owner object, such as +// https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd. +func (client ApplicationsClient) AddOwner(ctx context.Context, applicationObjectID string, parameters AddOwnerParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.AddOwner") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.ApplicationsClient", "AddOwner", err.Error()) + } + + req, err := client.AddOwnerPreparer(ctx, applicationObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "AddOwner", nil, "Failure preparing request") + return + } + + resp, err := client.AddOwnerSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "AddOwner", resp, "Failure sending request") + return + } + + result, err = client.AddOwnerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "AddOwner", resp, "Failure responding to request") + } + + return +} + +// AddOwnerPreparer prepares the AddOwner request. +func (client ApplicationsClient) AddOwnerPreparer(ctx context.Context, applicationObjectID string, parameters AddOwnerParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/$links/owners", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddOwnerSender sends the AddOwner request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) AddOwnerSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// AddOwnerResponder handles the response to the AddOwner request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) AddOwnerResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Create create a new application. +// Parameters: +// parameters - the parameters for creating an application. +func (client ApplicationsClient) Create(ctx context.Context, parameters ApplicationCreateParameters) (result Application, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.Create") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.DisplayName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.ApplicationsClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationsClient) CreatePreparer(ctx context.Context, parameters ApplicationCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) CreateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) CreateResponder(resp *http.Response) (result Application, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete an application. +// Parameters: +// applicationObjectID - application object ID. +func (client ApplicationsClient) Delete(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationsClient) DeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) DeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get an application by object ID. +// Parameters: +// applicationObjectID - application object ID. +func (client ApplicationsClient) Get(ctx context.Context, applicationObjectID string) (result Application, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationsClient) GetPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) GetResponder(resp *http.Response) (result Application, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetServicePrincipalsIDByAppID gets an object id for a given application id from the current tenant. +// Parameters: +// applicationID - the application ID. +func (client ApplicationsClient) GetServicePrincipalsIDByAppID(ctx context.Context, applicationID string) (result ServicePrincipalObjectResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.GetServicePrincipalsIDByAppID") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetServicePrincipalsIDByAppIDPreparer(ctx, applicationID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "GetServicePrincipalsIDByAppID", nil, "Failure preparing request") + return + } + + resp, err := client.GetServicePrincipalsIDByAppIDSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "GetServicePrincipalsIDByAppID", resp, "Failure sending request") + return + } + + result, err = client.GetServicePrincipalsIDByAppIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "GetServicePrincipalsIDByAppID", resp, "Failure responding to request") + } + + return +} + +// GetServicePrincipalsIDByAppIDPreparer prepares the GetServicePrincipalsIDByAppID request. +func (client ApplicationsClient) GetServicePrincipalsIDByAppIDPreparer(ctx context.Context, applicationID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationID": autorest.Encode("path", applicationID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipalsByAppId/{applicationID}/objectId", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetServicePrincipalsIDByAppIDSender sends the GetServicePrincipalsIDByAppID request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) GetServicePrincipalsIDByAppIDSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetServicePrincipalsIDByAppIDResponder handles the response to the GetServicePrincipalsIDByAppID request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) GetServicePrincipalsIDByAppIDResponder(resp *http.Response) (result ServicePrincipalObjectResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists applications by filter parameters. +// Parameters: +// filter - the filters to apply to the operation. +func (client ApplicationsClient) List(ctx context.Context, filter string) (result ApplicationListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.List") + defer func() { + sc := -1 + if result.alr.Response.Response != nil { + sc = result.alr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult ApplicationListResult) (ApplicationListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return ApplicationListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.alr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "List", resp, "Failure sending request") + return + } + + result.alr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListResponder(resp *http.Response) (result ApplicationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ApplicationsClient) ListComplete(ctx context.Context, filter string) (result ApplicationListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListKeyCredentials get the keyCredentials associated with an application. +// Parameters: +// applicationObjectID - application object ID. +func (client ApplicationsClient) ListKeyCredentials(ctx context.Context, applicationObjectID string) (result KeyCredentialListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.ListKeyCredentials") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListKeyCredentialsPreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListKeyCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeyCredentialsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListKeyCredentials", resp, "Failure sending request") + return + } + + result, err = client.ListKeyCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListKeyCredentials", resp, "Failure responding to request") + } + + return +} + +// ListKeyCredentialsPreparer prepares the ListKeyCredentials request. +func (client ApplicationsClient) ListKeyCredentialsPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/keyCredentials", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeyCredentialsSender sends the ListKeyCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) ListKeyCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListKeyCredentialsResponder handles the response to the ListKeyCredentials request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListKeyCredentialsResponder(resp *http.Response) (result KeyCredentialListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNext gets a list of applications from the current tenant. +// Parameters: +// nextLink - next link for the list operation. +func (client ApplicationsClient) ListNext(ctx context.Context, nextLink string) (result ApplicationListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client ApplicationsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListNextResponder(resp *http.Response) (result ApplicationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOwners the owners are a set of non-admin users who are allowed to modify this object. +// Parameters: +// applicationObjectID - the object ID of the application for which to get owners. +func (client ApplicationsClient) ListOwners(ctx context.Context, applicationObjectID string) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.ListOwners") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listOwnersNextResults + req, err := client.ListOwnersPreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListOwners", nil, "Failure preparing request") + return + } + + resp, err := client.ListOwnersSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListOwners", resp, "Failure sending request") + return + } + + result.dolr, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListOwners", resp, "Failure responding to request") + } + + return +} + +// ListOwnersPreparer prepares the ListOwners request. +func (client ApplicationsClient) ListOwnersPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/owners", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOwnersSender sends the ListOwners request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) ListOwnersSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListOwnersResponder handles the response to the ListOwners request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListOwnersResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listOwnersNextResults retrieves the next set of results, if any. +func (client ApplicationsClient) listOwnersNextResults(ctx context.Context, lastResults DirectoryObjectListResult) (result DirectoryObjectListResult, err error) { + req, err := lastResults.directoryObjectListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "listOwnersNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListOwnersSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "listOwnersNextResults", resp, "Failure sending next results request") + } + result, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "listOwnersNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListOwnersComplete enumerates all values, automatically crossing page boundaries as required. +func (client ApplicationsClient) ListOwnersComplete(ctx context.Context, applicationObjectID string) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.ListOwners") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListOwners(ctx, applicationObjectID) + return +} + +// ListPasswordCredentials get the passwordCredentials associated with an application. +// Parameters: +// applicationObjectID - application object ID. +func (client ApplicationsClient) ListPasswordCredentials(ctx context.Context, applicationObjectID string) (result PasswordCredentialListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.ListPasswordCredentials") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPasswordCredentialsPreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListPasswordCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.ListPasswordCredentialsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListPasswordCredentials", resp, "Failure sending request") + return + } + + result, err = client.ListPasswordCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "ListPasswordCredentials", resp, "Failure responding to request") + } + + return +} + +// ListPasswordCredentialsPreparer prepares the ListPasswordCredentials request. +func (client ApplicationsClient) ListPasswordCredentialsPreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/passwordCredentials", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListPasswordCredentialsSender sends the ListPasswordCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) ListPasswordCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListPasswordCredentialsResponder handles the response to the ListPasswordCredentials request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListPasswordCredentialsResponder(resp *http.Response) (result PasswordCredentialListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Patch update an existing application. +// Parameters: +// applicationObjectID - application object ID. +// parameters - parameters to update an existing application. +func (client ApplicationsClient) Patch(ctx context.Context, applicationObjectID string, parameters ApplicationUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.Patch") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.PatchPreparer(ctx, applicationObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Patch", nil, "Failure preparing request") + return + } + + resp, err := client.PatchSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Patch", resp, "Failure sending request") + return + } + + result, err = client.PatchResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "Patch", resp, "Failure responding to request") + } + + return +} + +// PatchPreparer prepares the Patch request. +func (client ApplicationsClient) PatchPreparer(ctx context.Context, applicationObjectID string, parameters ApplicationUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// PatchSender sends the Patch request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) PatchSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// PatchResponder handles the response to the Patch request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) PatchResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// RemoveOwner remove a member from owners. +// Parameters: +// applicationObjectID - the object ID of the application from which to remove the owner. +// ownerObjectID - owner object id +func (client ApplicationsClient) RemoveOwner(ctx context.Context, applicationObjectID string, ownerObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.RemoveOwner") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RemoveOwnerPreparer(ctx, applicationObjectID, ownerObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "RemoveOwner", nil, "Failure preparing request") + return + } + + resp, err := client.RemoveOwnerSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "RemoveOwner", resp, "Failure sending request") + return + } + + result, err = client.RemoveOwnerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "RemoveOwner", resp, "Failure responding to request") + } + + return +} + +// RemoveOwnerPreparer prepares the RemoveOwner request. +func (client ApplicationsClient) RemoveOwnerPreparer(ctx context.Context, applicationObjectID string, ownerObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "ownerObjectId": autorest.Encode("path", ownerObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/$links/owners/{ownerObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RemoveOwnerSender sends the RemoveOwner request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) RemoveOwnerSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// RemoveOwnerResponder handles the response to the RemoveOwner request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) RemoveOwnerResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// UpdateKeyCredentials update the keyCredentials associated with an application. +// Parameters: +// applicationObjectID - application object ID. +// parameters - parameters to update the keyCredentials of an existing application. +func (client ApplicationsClient) UpdateKeyCredentials(ctx context.Context, applicationObjectID string, parameters KeyCredentialsUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.UpdateKeyCredentials") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdateKeyCredentialsPreparer(ctx, applicationObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdateKeyCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateKeyCredentialsSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdateKeyCredentials", resp, "Failure sending request") + return + } + + result, err = client.UpdateKeyCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdateKeyCredentials", resp, "Failure responding to request") + } + + return +} + +// UpdateKeyCredentialsPreparer prepares the UpdateKeyCredentials request. +func (client ApplicationsClient) UpdateKeyCredentialsPreparer(ctx context.Context, applicationObjectID string, parameters KeyCredentialsUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/keyCredentials", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateKeyCredentialsSender sends the UpdateKeyCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) UpdateKeyCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdateKeyCredentialsResponder handles the response to the UpdateKeyCredentials request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) UpdateKeyCredentialsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// UpdatePasswordCredentials update passwordCredentials associated with an application. +// Parameters: +// applicationObjectID - application object ID. +// parameters - parameters to update passwordCredentials of an existing application. +func (client ApplicationsClient) UpdatePasswordCredentials(ctx context.Context, applicationObjectID string, parameters PasswordCredentialsUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationsClient.UpdatePasswordCredentials") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePasswordCredentialsPreparer(ctx, applicationObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdatePasswordCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.UpdatePasswordCredentialsSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdatePasswordCredentials", resp, "Failure sending request") + return + } + + result, err = client.UpdatePasswordCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ApplicationsClient", "UpdatePasswordCredentials", resp, "Failure responding to request") + } + + return +} + +// UpdatePasswordCredentialsPreparer prepares the UpdatePasswordCredentials request. +func (client ApplicationsClient) UpdatePasswordCredentialsPreparer(ctx context.Context, applicationObjectID string, parameters PasswordCredentialsUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/applications/{applicationObjectId}/passwordCredentials", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePasswordCredentialsSender sends the UpdatePasswordCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationsClient) UpdatePasswordCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdatePasswordCredentialsResponder handles the response to the UpdatePasswordCredentials request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) UpdatePasswordCredentialsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/client.go new file mode 100644 index 000000000..6f46fe18b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/client.go @@ -0,0 +1,51 @@ +// Package graphrbac implements the Azure ARM Graphrbac service API version 1.6. +// +// The Graph RBAC Management Client +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Graphrbac + DefaultBaseURI = "https://graph.windows.net" +) + +// BaseClient is the base client for Graphrbac. +type BaseClient struct { + autorest.Client + BaseURI string + TenantID string +} + +// New creates an instance of the BaseClient client. +func New(tenantID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, tenantID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + TenantID: tenantID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/deletedapplications.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/deletedapplications.go new file mode 100644 index 000000000..fe3b2da5d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/deletedapplications.go @@ -0,0 +1,365 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DeletedApplicationsClient is the the Graph RBAC Management Client +type DeletedApplicationsClient struct { + BaseClient +} + +// NewDeletedApplicationsClient creates an instance of the DeletedApplicationsClient client. +func NewDeletedApplicationsClient(tenantID string) DeletedApplicationsClient { + return NewDeletedApplicationsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewDeletedApplicationsClientWithBaseURI creates an instance of the DeletedApplicationsClient client. +func NewDeletedApplicationsClientWithBaseURI(baseURI string, tenantID string) DeletedApplicationsClient { + return DeletedApplicationsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// HardDelete hard-delete an application. +// Parameters: +// applicationObjectID - application object ID. +func (client DeletedApplicationsClient) HardDelete(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeletedApplicationsClient.HardDelete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.HardDeletePreparer(ctx, applicationObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "HardDelete", nil, "Failure preparing request") + return + } + + resp, err := client.HardDeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "HardDelete", resp, "Failure sending request") + return + } + + result, err = client.HardDeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "HardDelete", resp, "Failure responding to request") + } + + return +} + +// HardDeletePreparer prepares the HardDelete request. +func (client DeletedApplicationsClient) HardDeletePreparer(ctx context.Context, applicationObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationObjectId": autorest.Encode("path", applicationObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/deletedApplications/{applicationObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// HardDeleteSender sends the HardDelete request. The method will close the +// http.Response Body if it receives an error. +func (client DeletedApplicationsClient) HardDeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// HardDeleteResponder handles the response to the HardDelete request. The method always +// closes the http.Response Body. +func (client DeletedApplicationsClient) HardDeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// List gets a list of deleted applications in the directory. +// Parameters: +// filter - the filter to apply to the operation. +func (client DeletedApplicationsClient) List(ctx context.Context, filter string) (result ApplicationListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeletedApplicationsClient.List") + defer func() { + sc := -1 + if result.alr.Response.Response != nil { + sc = result.alr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult ApplicationListResult) (ApplicationListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return ApplicationListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.alr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "List", resp, "Failure sending request") + return + } + + result.alr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DeletedApplicationsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/deletedApplications", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client DeletedApplicationsClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DeletedApplicationsClient) ListResponder(resp *http.Response) (result ApplicationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client DeletedApplicationsClient) ListComplete(ctx context.Context, filter string) (result ApplicationListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeletedApplicationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListNext gets a list of deleted applications in the directory. +// Parameters: +// nextLink - next link for the list operation. +func (client DeletedApplicationsClient) ListNext(ctx context.Context, nextLink string) (result ApplicationListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeletedApplicationsClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client DeletedApplicationsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client DeletedApplicationsClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client DeletedApplicationsClient) ListNextResponder(resp *http.Response) (result ApplicationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Restore restores the deleted application in the directory. +// Parameters: +// objectID - application object ID. +func (client DeletedApplicationsClient) Restore(ctx context.Context, objectID string) (result Application, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeletedApplicationsClient.Restore") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RestorePreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "Restore", nil, "Failure preparing request") + return + } + + resp, err := client.RestoreSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "Restore", resp, "Failure sending request") + return + } + + result, err = client.RestoreResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DeletedApplicationsClient", "Restore", resp, "Failure responding to request") + } + + return +} + +// RestorePreparer prepares the Restore request. +func (client DeletedApplicationsClient) RestorePreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/deletedApplications/{objectId}/restore", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RestoreSender sends the Restore request. The method will close the +// http.Response Body if it receives an error. +func (client DeletedApplicationsClient) RestoreSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// RestoreResponder handles the response to the Restore request. The method always +// closes the http.Response Body. +func (client DeletedApplicationsClient) RestoreResponder(resp *http.Response) (result Application, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/domains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/domains.go new file mode 100644 index 000000000..93c6cac1e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/domains.go @@ -0,0 +1,193 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DomainsClient is the the Graph RBAC Management Client +type DomainsClient struct { + BaseClient +} + +// NewDomainsClient creates an instance of the DomainsClient client. +func NewDomainsClient(tenantID string) DomainsClient { + return NewDomainsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewDomainsClientWithBaseURI creates an instance of the DomainsClient client. +func NewDomainsClientWithBaseURI(baseURI string, tenantID string) DomainsClient { + return DomainsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// Get gets a specific domain in the current tenant. +// Parameters: +// domainName - name of the domain. +func (client DomainsClient) Get(ctx context.Context, domainName string) (result Domain, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DomainsClient) GetPreparer(ctx context.Context, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/domains/{domainName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DomainsClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DomainsClient) GetResponder(resp *http.Response) (result Domain, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets a list of domains for the current tenant. +// Parameters: +// filter - the filter to apply to the operation. +func (client DomainsClient) List(ctx context.Context, filter string) (result DomainListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.DomainsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DomainsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/domains", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client DomainsClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DomainsClient) ListResponder(resp *http.Response) (result DomainListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/groups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/groups.go new file mode 100644 index 000000000..4ed37e94f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/groups.go @@ -0,0 +1,1224 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// GroupsClient is the the Graph RBAC Management Client +type GroupsClient struct { + BaseClient +} + +// NewGroupsClient creates an instance of the GroupsClient client. +func NewGroupsClient(tenantID string) GroupsClient { + return NewGroupsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewGroupsClientWithBaseURI creates an instance of the GroupsClient client. +func NewGroupsClientWithBaseURI(baseURI string, tenantID string) GroupsClient { + return GroupsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// AddMember add a member to a group. +// Parameters: +// groupObjectID - the object ID of the group to which to add the member. +// parameters - the URL of the member object, such as +// https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd. +func (client GroupsClient) AddMember(ctx context.Context, groupObjectID string, parameters GroupAddMemberParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.AddMember") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.GroupsClient", "AddMember", err.Error()) + } + + req, err := client.AddMemberPreparer(ctx, groupObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddMember", nil, "Failure preparing request") + return + } + + resp, err := client.AddMemberSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddMember", resp, "Failure sending request") + return + } + + result, err = client.AddMemberResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddMember", resp, "Failure responding to request") + } + + return +} + +// AddMemberPreparer prepares the AddMember request. +func (client GroupsClient) AddMemberPreparer(ctx context.Context, groupObjectID string, parameters GroupAddMemberParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "groupObjectId": autorest.Encode("path", groupObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{groupObjectId}/$links/members", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddMemberSender sends the AddMember request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) AddMemberSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// AddMemberResponder handles the response to the AddMember request. The method always +// closes the http.Response Body. +func (client GroupsClient) AddMemberResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// AddOwner add an owner to a group. +// Parameters: +// objectID - the object ID of the application to which to add the owner. +// parameters - the URL of the owner object, such as +// https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd. +func (client GroupsClient) AddOwner(ctx context.Context, objectID string, parameters AddOwnerParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.AddOwner") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.URL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.GroupsClient", "AddOwner", err.Error()) + } + + req, err := client.AddOwnerPreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddOwner", nil, "Failure preparing request") + return + } + + resp, err := client.AddOwnerSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddOwner", resp, "Failure sending request") + return + } + + result, err = client.AddOwnerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "AddOwner", resp, "Failure responding to request") + } + + return +} + +// AddOwnerPreparer prepares the AddOwner request. +func (client GroupsClient) AddOwnerPreparer(ctx context.Context, objectID string, parameters AddOwnerParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}/$links/owners", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddOwnerSender sends the AddOwner request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) AddOwnerSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// AddOwnerResponder handles the response to the AddOwner request. The method always +// closes the http.Response Body. +func (client GroupsClient) AddOwnerResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Create create a group in the directory. +// Parameters: +// parameters - the parameters for the group to create. +func (client GroupsClient) Create(ctx context.Context, parameters GroupCreateParameters) (result ADGroup, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Create") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.DisplayName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.MailEnabled", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.MailNickname", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.SecurityEnabled", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.GroupsClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client GroupsClient) CreatePreparer(ctx context.Context, parameters GroupCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) CreateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client GroupsClient) CreateResponder(resp *http.Response) (result ADGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a group from the directory. +// Parameters: +// objectID - the object ID of the group to delete. +func (client GroupsClient) Delete(ctx context.Context, objectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GroupsClient) DeletePreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) DeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets group information from the directory. +// Parameters: +// objectID - the object ID of the user for which to get group information. +func (client GroupsClient) Get(ctx context.Context, objectID string) (result ADGroup, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client GroupsClient) GetPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GroupsClient) GetResponder(resp *http.Response) (result ADGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetGroupMembers gets the members of a group. +// Parameters: +// objectID - the object ID of the group whose members should be retrieved. +func (client GroupsClient) GetGroupMembers(ctx context.Context, objectID string) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.GetGroupMembers") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult DirectoryObjectListResult) (DirectoryObjectListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return DirectoryObjectListResult{}, nil + } + return client.GetGroupMembersNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.GetGroupMembersPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembers", nil, "Failure preparing request") + return + } + + resp, err := client.GetGroupMembersSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembers", resp, "Failure sending request") + return + } + + result.dolr, err = client.GetGroupMembersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembers", resp, "Failure responding to request") + } + + return +} + +// GetGroupMembersPreparer prepares the GetGroupMembers request. +func (client GroupsClient) GetGroupMembersPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}/members", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetGroupMembersSender sends the GetGroupMembers request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) GetGroupMembersSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetGroupMembersResponder handles the response to the GetGroupMembers request. The method always +// closes the http.Response Body. +func (client GroupsClient) GetGroupMembersResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetGroupMembersComplete enumerates all values, automatically crossing page boundaries as required. +func (client GroupsClient) GetGroupMembersComplete(ctx context.Context, objectID string) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.GetGroupMembers") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.GetGroupMembers(ctx, objectID) + return +} + +// GetGroupMembersNext gets the members of a group. +// Parameters: +// nextLink - next link for the list operation. +func (client GroupsClient) GetGroupMembersNext(ctx context.Context, nextLink string) (result DirectoryObjectListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.GetGroupMembersNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetGroupMembersNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembersNext", nil, "Failure preparing request") + return + } + + resp, err := client.GetGroupMembersNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembersNext", resp, "Failure sending request") + return + } + + result, err = client.GetGroupMembersNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetGroupMembersNext", resp, "Failure responding to request") + } + + return +} + +// GetGroupMembersNextPreparer prepares the GetGroupMembersNext request. +func (client GroupsClient) GetGroupMembersNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetGroupMembersNextSender sends the GetGroupMembersNext request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) GetGroupMembersNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetGroupMembersNextResponder handles the response to the GetGroupMembersNext request. The method always +// closes the http.Response Body. +func (client GroupsClient) GetGroupMembersNextResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetMemberGroups gets a collection of object IDs of groups of which the specified group is a member. +// Parameters: +// objectID - the object ID of the group for which to get group membership. +// parameters - group filtering parameters. +func (client GroupsClient) GetMemberGroups(ctx context.Context, objectID string, parameters GroupGetMemberGroupsParameters) (result GroupGetMemberGroupsResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.GetMemberGroups") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SecurityEnabledOnly", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.GroupsClient", "GetMemberGroups", err.Error()) + } + + req, err := client.GetMemberGroupsPreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetMemberGroups", nil, "Failure preparing request") + return + } + + resp, err := client.GetMemberGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetMemberGroups", resp, "Failure sending request") + return + } + + result, err = client.GetMemberGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "GetMemberGroups", resp, "Failure responding to request") + } + + return +} + +// GetMemberGroupsPreparer prepares the GetMemberGroups request. +func (client GroupsClient) GetMemberGroupsPreparer(ctx context.Context, objectID string, parameters GroupGetMemberGroupsParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}/getMemberGroups", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetMemberGroupsSender sends the GetMemberGroups request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) GetMemberGroupsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetMemberGroupsResponder handles the response to the GetMemberGroups request. The method always +// closes the http.Response Body. +func (client GroupsClient) GetMemberGroupsResponder(resp *http.Response) (result GroupGetMemberGroupsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// IsMemberOf checks whether the specified user, group, contact, or service principal is a direct or transitive member +// of the specified group. +// Parameters: +// parameters - the check group membership parameters. +func (client GroupsClient) IsMemberOf(ctx context.Context, parameters CheckGroupMembershipParameters) (result CheckGroupMembershipResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.IsMemberOf") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.GroupID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.MemberID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.GroupsClient", "IsMemberOf", err.Error()) + } + + req, err := client.IsMemberOfPreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "IsMemberOf", nil, "Failure preparing request") + return + } + + resp, err := client.IsMemberOfSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "IsMemberOf", resp, "Failure sending request") + return + } + + result, err = client.IsMemberOfResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "IsMemberOf", resp, "Failure responding to request") + } + + return +} + +// IsMemberOfPreparer prepares the IsMemberOf request. +func (client GroupsClient) IsMemberOfPreparer(ctx context.Context, parameters CheckGroupMembershipParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/isMemberOf", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// IsMemberOfSender sends the IsMemberOf request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) IsMemberOfSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// IsMemberOfResponder handles the response to the IsMemberOf request. The method always +// closes the http.Response Body. +func (client GroupsClient) IsMemberOfResponder(resp *http.Response) (result CheckGroupMembershipResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets list of groups for the current tenant. +// Parameters: +// filter - the filter to apply to the operation. +func (client GroupsClient) List(ctx context.Context, filter string) (result GroupListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.glr.Response.Response != nil { + sc = result.glr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult GroupListResult) (GroupListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return GroupListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.glr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "List", resp, "Failure sending request") + return + } + + result.glr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client GroupsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GroupsClient) ListResponder(resp *http.Response) (result GroupListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GroupsClient) ListComplete(ctx context.Context, filter string) (result GroupListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListNext gets a list of groups for the current tenant. +// Parameters: +// nextLink - next link for the list operation. +func (client GroupsClient) ListNext(ctx context.Context, nextLink string) (result GroupListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client GroupsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client GroupsClient) ListNextResponder(resp *http.Response) (result GroupListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOwners the owners are a set of non-admin users who are allowed to modify this object. +// Parameters: +// objectID - the object ID of the group for which to get owners. +func (client GroupsClient) ListOwners(ctx context.Context, objectID string) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListOwners") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listOwnersNextResults + req, err := client.ListOwnersPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListOwners", nil, "Failure preparing request") + return + } + + resp, err := client.ListOwnersSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListOwners", resp, "Failure sending request") + return + } + + result.dolr, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "ListOwners", resp, "Failure responding to request") + } + + return +} + +// ListOwnersPreparer prepares the ListOwners request. +func (client GroupsClient) ListOwnersPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}/owners", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOwnersSender sends the ListOwners request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) ListOwnersSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListOwnersResponder handles the response to the ListOwners request. The method always +// closes the http.Response Body. +func (client GroupsClient) ListOwnersResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listOwnersNextResults retrieves the next set of results, if any. +func (client GroupsClient) listOwnersNextResults(ctx context.Context, lastResults DirectoryObjectListResult) (result DirectoryObjectListResult, err error) { + req, err := lastResults.directoryObjectListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "listOwnersNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListOwnersSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "listOwnersNextResults", resp, "Failure sending next results request") + } + result, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "listOwnersNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListOwnersComplete enumerates all values, automatically crossing page boundaries as required. +func (client GroupsClient) ListOwnersComplete(ctx context.Context, objectID string) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListOwners") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListOwners(ctx, objectID) + return +} + +// RemoveMember remove a member from a group. +// Parameters: +// groupObjectID - the object ID of the group from which to remove the member. +// memberObjectID - member object id +func (client GroupsClient) RemoveMember(ctx context.Context, groupObjectID string, memberObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.RemoveMember") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RemoveMemberPreparer(ctx, groupObjectID, memberObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveMember", nil, "Failure preparing request") + return + } + + resp, err := client.RemoveMemberSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveMember", resp, "Failure sending request") + return + } + + result, err = client.RemoveMemberResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveMember", resp, "Failure responding to request") + } + + return +} + +// RemoveMemberPreparer prepares the RemoveMember request. +func (client GroupsClient) RemoveMemberPreparer(ctx context.Context, groupObjectID string, memberObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "groupObjectId": autorest.Encode("path", groupObjectID), + "memberObjectId": autorest.Encode("path", memberObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{groupObjectId}/$links/members/{memberObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RemoveMemberSender sends the RemoveMember request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) RemoveMemberSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// RemoveMemberResponder handles the response to the RemoveMember request. The method always +// closes the http.Response Body. +func (client GroupsClient) RemoveMemberResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// RemoveOwner remove a member from owners. +// Parameters: +// objectID - the object ID of the group from which to remove the owner. +// ownerObjectID - owner object id +func (client GroupsClient) RemoveOwner(ctx context.Context, objectID string, ownerObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.RemoveOwner") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RemoveOwnerPreparer(ctx, objectID, ownerObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveOwner", nil, "Failure preparing request") + return + } + + resp, err := client.RemoveOwnerSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveOwner", resp, "Failure sending request") + return + } + + result, err = client.RemoveOwnerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.GroupsClient", "RemoveOwner", resp, "Failure responding to request") + } + + return +} + +// RemoveOwnerPreparer prepares the RemoveOwner request. +func (client GroupsClient) RemoveOwnerPreparer(ctx context.Context, objectID string, ownerObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "ownerObjectId": autorest.Encode("path", ownerObjectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/groups/{objectId}/$links/owners/{ownerObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RemoveOwnerSender sends the RemoveOwner request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) RemoveOwnerSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// RemoveOwnerResponder handles the response to the RemoveOwner request. The method always +// closes the http.Response Body. +func (client GroupsClient) RemoveOwnerResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/models.go new file mode 100644 index 000000000..e6b583d96 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/models.go @@ -0,0 +1,4662 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + +// ConsentType enumerates the values for consent type. +type ConsentType string + +const ( + // AllPrincipals ... + AllPrincipals ConsentType = "AllPrincipals" + // Principal ... + Principal ConsentType = "Principal" +) + +// PossibleConsentTypeValues returns an array of possible values for the ConsentType const type. +func PossibleConsentTypeValues() []ConsentType { + return []ConsentType{AllPrincipals, Principal} +} + +// ObjectType enumerates the values for object type. +type ObjectType string + +const ( + // ObjectTypeApplication ... + ObjectTypeApplication ObjectType = "Application" + // ObjectTypeDirectoryObject ... + ObjectTypeDirectoryObject ObjectType = "DirectoryObject" + // ObjectTypeGroup ... + ObjectTypeGroup ObjectType = "Group" + // ObjectTypeServicePrincipal ... + ObjectTypeServicePrincipal ObjectType = "ServicePrincipal" + // ObjectTypeUser ... + ObjectTypeUser ObjectType = "User" +) + +// PossibleObjectTypeValues returns an array of possible values for the ObjectType const type. +func PossibleObjectTypeValues() []ObjectType { + return []ObjectType{ObjectTypeApplication, ObjectTypeDirectoryObject, ObjectTypeGroup, ObjectTypeServicePrincipal, ObjectTypeUser} +} + +// UserType enumerates the values for user type. +type UserType string + +const ( + // Guest ... + Guest UserType = "Guest" + // Member ... + Member UserType = "Member" +) + +// PossibleUserTypeValues returns an array of possible values for the UserType const type. +func PossibleUserTypeValues() []UserType { + return []UserType{Guest, Member} +} + +// AddOwnerParameters request parameters for adding a owner to an application. +type AddOwnerParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // URL - A owner object URL, such as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the owner (user, application, servicePrincipal, group) to be added. + URL *string `json:"url,omitempty"` +} + +// MarshalJSON is the custom marshaler for AddOwnerParameters. +func (aop AddOwnerParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if aop.URL != nil { + objectMap["url"] = aop.URL + } + for k, v := range aop.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for AddOwnerParameters struct. +func (aop *AddOwnerParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if aop.AdditionalProperties == nil { + aop.AdditionalProperties = make(map[string]interface{}) + } + aop.AdditionalProperties[k] = additionalProperties + } + case "url": + if v != nil { + var URL string + err = json.Unmarshal(*v, &URL) + if err != nil { + return err + } + aop.URL = &URL + } + } + } + + return nil +} + +// ADGroup active Directory group information. +type ADGroup struct { + autorest.Response `json:"-"` + // DisplayName - The display name of the group. + DisplayName *string `json:"displayName,omitempty"` + // MailEnabled - Whether the group is mail-enabled. Must be false. This is because only pure security groups can be created using the Graph API. + MailEnabled *bool `json:"mailEnabled,omitempty"` + // MailNickname - The mail alias for the group. + MailNickname *string `json:"mailNickname,omitempty"` + // SecurityEnabled - Whether the group is security-enable. + SecurityEnabled *bool `json:"securityEnabled,omitempty"` + // Mail - The primary email address of the group. + Mail *string `json:"mail,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectID - READ-ONLY; The object ID. + ObjectID *string `json:"objectId,omitempty"` + // DeletionTimestamp - READ-ONLY; The time at which the directory object was deleted. + DeletionTimestamp *date.Time `json:"deletionTimestamp,omitempty"` + // ObjectType - Possible values include: 'ObjectTypeDirectoryObject', 'ObjectTypeApplication', 'ObjectTypeGroup', 'ObjectTypeServicePrincipal', 'ObjectTypeUser' + ObjectType ObjectType `json:"objectType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ADGroup. +func (ag ADGroup) MarshalJSON() ([]byte, error) { + ag.ObjectType = ObjectTypeGroup + objectMap := make(map[string]interface{}) + if ag.DisplayName != nil { + objectMap["displayName"] = ag.DisplayName + } + if ag.MailEnabled != nil { + objectMap["mailEnabled"] = ag.MailEnabled + } + if ag.MailNickname != nil { + objectMap["mailNickname"] = ag.MailNickname + } + if ag.SecurityEnabled != nil { + objectMap["securityEnabled"] = ag.SecurityEnabled + } + if ag.Mail != nil { + objectMap["mail"] = ag.Mail + } + if ag.ObjectType != "" { + objectMap["objectType"] = ag.ObjectType + } + for k, v := range ag.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// AsApplication is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsApplication() (*Application, bool) { + return nil, false +} + +// AsADGroup is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsADGroup() (*ADGroup, bool) { + return &ag, true +} + +// AsServicePrincipal is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsServicePrincipal() (*ServicePrincipal, bool) { + return nil, false +} + +// AsUser is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsUser() (*User, bool) { + return nil, false +} + +// AsDirectoryObject is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsDirectoryObject() (*DirectoryObject, bool) { + return nil, false +} + +// AsBasicDirectoryObject is the BasicDirectoryObject implementation for ADGroup. +func (ag ADGroup) AsBasicDirectoryObject() (BasicDirectoryObject, bool) { + return &ag, true +} + +// UnmarshalJSON is the custom unmarshaler for ADGroup struct. +func (ag *ADGroup) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + ag.DisplayName = &displayName + } + case "mailEnabled": + if v != nil { + var mailEnabled bool + err = json.Unmarshal(*v, &mailEnabled) + if err != nil { + return err + } + ag.MailEnabled = &mailEnabled + } + case "mailNickname": + if v != nil { + var mailNickname string + err = json.Unmarshal(*v, &mailNickname) + if err != nil { + return err + } + ag.MailNickname = &mailNickname + } + case "securityEnabled": + if v != nil { + var securityEnabled bool + err = json.Unmarshal(*v, &securityEnabled) + if err != nil { + return err + } + ag.SecurityEnabled = &securityEnabled + } + case "mail": + if v != nil { + var mailVar string + err = json.Unmarshal(*v, &mailVar) + if err != nil { + return err + } + ag.Mail = &mailVar + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ag.AdditionalProperties == nil { + ag.AdditionalProperties = make(map[string]interface{}) + } + ag.AdditionalProperties[k] = additionalProperties + } + case "objectId": + if v != nil { + var objectID string + err = json.Unmarshal(*v, &objectID) + if err != nil { + return err + } + ag.ObjectID = &objectID + } + case "deletionTimestamp": + if v != nil { + var deletionTimestamp date.Time + err = json.Unmarshal(*v, &deletionTimestamp) + if err != nil { + return err + } + ag.DeletionTimestamp = &deletionTimestamp + } + case "objectType": + if v != nil { + var objectType ObjectType + err = json.Unmarshal(*v, &objectType) + if err != nil { + return err + } + ag.ObjectType = objectType + } + } + } + + return nil +} + +// Application active Directory application information. +type Application struct { + autorest.Response `json:"-"` + // AppID - The application ID. + AppID *string `json:"appId,omitempty"` + // AllowGuestsSignIn - A property on the application to indicate if the application accepts other IDPs or not or partially accepts. + AllowGuestsSignIn *bool `json:"allowGuestsSignIn,omitempty"` + // AllowPassthroughUsers - Indicates that the application supports pass through users who have no presence in the resource tenant. + AllowPassthroughUsers *bool `json:"allowPassthroughUsers,omitempty"` + // AppLogoURL - The url for the application logo image stored in a CDN. + AppLogoURL *string `json:"appLogoUrl,omitempty"` + // AppRoles - The collection of application roles that an application may declare. These roles can be assigned to users, groups or service principals. + AppRoles *[]AppRole `json:"appRoles,omitempty"` + // AppPermissions - The application permissions. + AppPermissions *[]string `json:"appPermissions,omitempty"` + // AvailableToOtherTenants - Whether the application is available to other tenants. + AvailableToOtherTenants *bool `json:"availableToOtherTenants,omitempty"` + // DisplayName - The display name of the application. + DisplayName *string `json:"displayName,omitempty"` + // ErrorURL - A URL provided by the author of the application to report errors when using the application. + ErrorURL *string `json:"errorUrl,omitempty"` + // GroupMembershipClaims - Configures the groups claim issued in a user or OAuth 2.0 access token that the app expects. + GroupMembershipClaims interface{} `json:"groupMembershipClaims,omitempty"` + // Homepage - The home page of the application. + Homepage *string `json:"homepage,omitempty"` + // IdentifierUris - A collection of URIs for the application. + IdentifierUris *[]string `json:"identifierUris,omitempty"` + // InformationalUrls - URLs with more information about the application. + InformationalUrls *InformationalURL `json:"informationalUrls,omitempty"` + // IsDeviceOnlyAuthSupported - Specifies whether this application supports device authentication without a user. The default is false. + IsDeviceOnlyAuthSupported *bool `json:"isDeviceOnlyAuthSupported,omitempty"` + // KeyCredentials - A collection of KeyCredential objects. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // KnownClientApplications - Client applications that are tied to this resource application. Consent to any of the known client applications will result in implicit consent to the resource application through a combined consent dialog (showing the OAuth permission scopes required by the client and the resource). + KnownClientApplications *[]string `json:"knownClientApplications,omitempty"` + // LogoutURL - the url of the logout page + LogoutURL *string `json:"logoutUrl,omitempty"` + // Oauth2AllowImplicitFlow - Whether to allow implicit grant flow for OAuth2 + Oauth2AllowImplicitFlow *bool `json:"oauth2AllowImplicitFlow,omitempty"` + // Oauth2AllowURLPathMatching - Specifies whether during a token Request Azure AD will allow path matching of the redirect URI against the applications collection of replyURLs. The default is false. + Oauth2AllowURLPathMatching *bool `json:"oauth2AllowUrlPathMatching,omitempty"` + // Oauth2Permissions - The collection of OAuth 2.0 permission scopes that the web API (resource) application exposes to client applications. These permission scopes may be granted to client applications during consent. + Oauth2Permissions *[]OAuth2Permission `json:"oauth2Permissions,omitempty"` + // Oauth2RequirePostResponse - Specifies whether, as part of OAuth 2.0 token requests, Azure AD will allow POST requests, as opposed to GET requests. The default is false, which specifies that only GET requests will be allowed. + Oauth2RequirePostResponse *bool `json:"oauth2RequirePostResponse,omitempty"` + // OrgRestrictions - A list of tenants allowed to access application. + OrgRestrictions *[]string `json:"orgRestrictions,omitempty"` + OptionalClaims *OptionalClaims `json:"optionalClaims,omitempty"` + // PasswordCredentials - A collection of PasswordCredential objects + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // PreAuthorizedApplications - list of pre-authorized applications. + PreAuthorizedApplications *[]PreAuthorizedApplication `json:"preAuthorizedApplications,omitempty"` + // PublicClient - Specifies whether this application is a public client (such as an installed application running on a mobile device). Default is false. + PublicClient *bool `json:"publicClient,omitempty"` + // PublisherDomain - Reliable domain which can be used to identify an application. + PublisherDomain *string `json:"publisherDomain,omitempty"` + // ReplyUrls - A collection of reply URLs for the application. + ReplyUrls *[]string `json:"replyUrls,omitempty"` + // RequiredResourceAccess - Specifies resources that this application requires access to and the set of OAuth permission scopes and application roles that it needs under each of those resources. This pre-configuration of required resource access drives the consent experience. + RequiredResourceAccess *[]RequiredResourceAccess `json:"requiredResourceAccess,omitempty"` + // SamlMetadataURL - The URL to the SAML metadata for the application. + SamlMetadataURL *string `json:"samlMetadataUrl,omitempty"` + // SignInAudience - Audience for signing in to the application (AzureADMyOrganization, AzureADAllOrganizations, AzureADAndMicrosoftAccounts). + SignInAudience *string `json:"signInAudience,omitempty"` + // WwwHomepage - The primary Web page. + WwwHomepage *string `json:"wwwHomepage,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectID - READ-ONLY; The object ID. + ObjectID *string `json:"objectId,omitempty"` + // DeletionTimestamp - READ-ONLY; The time at which the directory object was deleted. + DeletionTimestamp *date.Time `json:"deletionTimestamp,omitempty"` + // ObjectType - Possible values include: 'ObjectTypeDirectoryObject', 'ObjectTypeApplication', 'ObjectTypeGroup', 'ObjectTypeServicePrincipal', 'ObjectTypeUser' + ObjectType ObjectType `json:"objectType,omitempty"` +} + +// MarshalJSON is the custom marshaler for Application. +func (a Application) MarshalJSON() ([]byte, error) { + a.ObjectType = ObjectTypeApplication + objectMap := make(map[string]interface{}) + if a.AppID != nil { + objectMap["appId"] = a.AppID + } + if a.AllowGuestsSignIn != nil { + objectMap["allowGuestsSignIn"] = a.AllowGuestsSignIn + } + if a.AllowPassthroughUsers != nil { + objectMap["allowPassthroughUsers"] = a.AllowPassthroughUsers + } + if a.AppLogoURL != nil { + objectMap["appLogoUrl"] = a.AppLogoURL + } + if a.AppRoles != nil { + objectMap["appRoles"] = a.AppRoles + } + if a.AppPermissions != nil { + objectMap["appPermissions"] = a.AppPermissions + } + if a.AvailableToOtherTenants != nil { + objectMap["availableToOtherTenants"] = a.AvailableToOtherTenants + } + if a.DisplayName != nil { + objectMap["displayName"] = a.DisplayName + } + if a.ErrorURL != nil { + objectMap["errorUrl"] = a.ErrorURL + } + if a.GroupMembershipClaims != nil { + objectMap["groupMembershipClaims"] = a.GroupMembershipClaims + } + if a.Homepage != nil { + objectMap["homepage"] = a.Homepage + } + if a.IdentifierUris != nil { + objectMap["identifierUris"] = a.IdentifierUris + } + if a.InformationalUrls != nil { + objectMap["informationalUrls"] = a.InformationalUrls + } + if a.IsDeviceOnlyAuthSupported != nil { + objectMap["isDeviceOnlyAuthSupported"] = a.IsDeviceOnlyAuthSupported + } + if a.KeyCredentials != nil { + objectMap["keyCredentials"] = a.KeyCredentials + } + if a.KnownClientApplications != nil { + objectMap["knownClientApplications"] = a.KnownClientApplications + } + if a.LogoutURL != nil { + objectMap["logoutUrl"] = a.LogoutURL + } + if a.Oauth2AllowImplicitFlow != nil { + objectMap["oauth2AllowImplicitFlow"] = a.Oauth2AllowImplicitFlow + } + if a.Oauth2AllowURLPathMatching != nil { + objectMap["oauth2AllowUrlPathMatching"] = a.Oauth2AllowURLPathMatching + } + if a.Oauth2Permissions != nil { + objectMap["oauth2Permissions"] = a.Oauth2Permissions + } + if a.Oauth2RequirePostResponse != nil { + objectMap["oauth2RequirePostResponse"] = a.Oauth2RequirePostResponse + } + if a.OrgRestrictions != nil { + objectMap["orgRestrictions"] = a.OrgRestrictions + } + if a.OptionalClaims != nil { + objectMap["optionalClaims"] = a.OptionalClaims + } + if a.PasswordCredentials != nil { + objectMap["passwordCredentials"] = a.PasswordCredentials + } + if a.PreAuthorizedApplications != nil { + objectMap["preAuthorizedApplications"] = a.PreAuthorizedApplications + } + if a.PublicClient != nil { + objectMap["publicClient"] = a.PublicClient + } + if a.PublisherDomain != nil { + objectMap["publisherDomain"] = a.PublisherDomain + } + if a.ReplyUrls != nil { + objectMap["replyUrls"] = a.ReplyUrls + } + if a.RequiredResourceAccess != nil { + objectMap["requiredResourceAccess"] = a.RequiredResourceAccess + } + if a.SamlMetadataURL != nil { + objectMap["samlMetadataUrl"] = a.SamlMetadataURL + } + if a.SignInAudience != nil { + objectMap["signInAudience"] = a.SignInAudience + } + if a.WwwHomepage != nil { + objectMap["wwwHomepage"] = a.WwwHomepage + } + if a.ObjectType != "" { + objectMap["objectType"] = a.ObjectType + } + for k, v := range a.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// AsApplication is the BasicDirectoryObject implementation for Application. +func (a Application) AsApplication() (*Application, bool) { + return &a, true +} + +// AsADGroup is the BasicDirectoryObject implementation for Application. +func (a Application) AsADGroup() (*ADGroup, bool) { + return nil, false +} + +// AsServicePrincipal is the BasicDirectoryObject implementation for Application. +func (a Application) AsServicePrincipal() (*ServicePrincipal, bool) { + return nil, false +} + +// AsUser is the BasicDirectoryObject implementation for Application. +func (a Application) AsUser() (*User, bool) { + return nil, false +} + +// AsDirectoryObject is the BasicDirectoryObject implementation for Application. +func (a Application) AsDirectoryObject() (*DirectoryObject, bool) { + return nil, false +} + +// AsBasicDirectoryObject is the BasicDirectoryObject implementation for Application. +func (a Application) AsBasicDirectoryObject() (BasicDirectoryObject, bool) { + return &a, true +} + +// UnmarshalJSON is the custom unmarshaler for Application struct. +func (a *Application) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "appId": + if v != nil { + var appID string + err = json.Unmarshal(*v, &appID) + if err != nil { + return err + } + a.AppID = &appID + } + case "allowGuestsSignIn": + if v != nil { + var allowGuestsSignIn bool + err = json.Unmarshal(*v, &allowGuestsSignIn) + if err != nil { + return err + } + a.AllowGuestsSignIn = &allowGuestsSignIn + } + case "allowPassthroughUsers": + if v != nil { + var allowPassthroughUsers bool + err = json.Unmarshal(*v, &allowPassthroughUsers) + if err != nil { + return err + } + a.AllowPassthroughUsers = &allowPassthroughUsers + } + case "appLogoUrl": + if v != nil { + var appLogoURL string + err = json.Unmarshal(*v, &appLogoURL) + if err != nil { + return err + } + a.AppLogoURL = &appLogoURL + } + case "appRoles": + if v != nil { + var appRoles []AppRole + err = json.Unmarshal(*v, &appRoles) + if err != nil { + return err + } + a.AppRoles = &appRoles + } + case "appPermissions": + if v != nil { + var appPermissions []string + err = json.Unmarshal(*v, &appPermissions) + if err != nil { + return err + } + a.AppPermissions = &appPermissions + } + case "availableToOtherTenants": + if v != nil { + var availableToOtherTenants bool + err = json.Unmarshal(*v, &availableToOtherTenants) + if err != nil { + return err + } + a.AvailableToOtherTenants = &availableToOtherTenants + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + a.DisplayName = &displayName + } + case "errorUrl": + if v != nil { + var errorURL string + err = json.Unmarshal(*v, &errorURL) + if err != nil { + return err + } + a.ErrorURL = &errorURL + } + case "groupMembershipClaims": + if v != nil { + var groupMembershipClaims interface{} + err = json.Unmarshal(*v, &groupMembershipClaims) + if err != nil { + return err + } + a.GroupMembershipClaims = groupMembershipClaims + } + case "homepage": + if v != nil { + var homepage string + err = json.Unmarshal(*v, &homepage) + if err != nil { + return err + } + a.Homepage = &homepage + } + case "identifierUris": + if v != nil { + var identifierUris []string + err = json.Unmarshal(*v, &identifierUris) + if err != nil { + return err + } + a.IdentifierUris = &identifierUris + } + case "informationalUrls": + if v != nil { + var informationalUrls InformationalURL + err = json.Unmarshal(*v, &informationalUrls) + if err != nil { + return err + } + a.InformationalUrls = &informationalUrls + } + case "isDeviceOnlyAuthSupported": + if v != nil { + var isDeviceOnlyAuthSupported bool + err = json.Unmarshal(*v, &isDeviceOnlyAuthSupported) + if err != nil { + return err + } + a.IsDeviceOnlyAuthSupported = &isDeviceOnlyAuthSupported + } + case "keyCredentials": + if v != nil { + var keyCredentials []KeyCredential + err = json.Unmarshal(*v, &keyCredentials) + if err != nil { + return err + } + a.KeyCredentials = &keyCredentials + } + case "knownClientApplications": + if v != nil { + var knownClientApplications []string + err = json.Unmarshal(*v, &knownClientApplications) + if err != nil { + return err + } + a.KnownClientApplications = &knownClientApplications + } + case "logoutUrl": + if v != nil { + var logoutURL string + err = json.Unmarshal(*v, &logoutURL) + if err != nil { + return err + } + a.LogoutURL = &logoutURL + } + case "oauth2AllowImplicitFlow": + if v != nil { + var oauth2AllowImplicitFlow bool + err = json.Unmarshal(*v, &oauth2AllowImplicitFlow) + if err != nil { + return err + } + a.Oauth2AllowImplicitFlow = &oauth2AllowImplicitFlow + } + case "oauth2AllowUrlPathMatching": + if v != nil { + var oauth2AllowURLPathMatching bool + err = json.Unmarshal(*v, &oauth2AllowURLPathMatching) + if err != nil { + return err + } + a.Oauth2AllowURLPathMatching = &oauth2AllowURLPathMatching + } + case "oauth2Permissions": + if v != nil { + var oauth2Permissions []OAuth2Permission + err = json.Unmarshal(*v, &oauth2Permissions) + if err != nil { + return err + } + a.Oauth2Permissions = &oauth2Permissions + } + case "oauth2RequirePostResponse": + if v != nil { + var oauth2RequirePostResponse bool + err = json.Unmarshal(*v, &oauth2RequirePostResponse) + if err != nil { + return err + } + a.Oauth2RequirePostResponse = &oauth2RequirePostResponse + } + case "orgRestrictions": + if v != nil { + var orgRestrictions []string + err = json.Unmarshal(*v, &orgRestrictions) + if err != nil { + return err + } + a.OrgRestrictions = &orgRestrictions + } + case "optionalClaims": + if v != nil { + var optionalClaims OptionalClaims + err = json.Unmarshal(*v, &optionalClaims) + if err != nil { + return err + } + a.OptionalClaims = &optionalClaims + } + case "passwordCredentials": + if v != nil { + var passwordCredentials []PasswordCredential + err = json.Unmarshal(*v, &passwordCredentials) + if err != nil { + return err + } + a.PasswordCredentials = &passwordCredentials + } + case "preAuthorizedApplications": + if v != nil { + var preAuthorizedApplications []PreAuthorizedApplication + err = json.Unmarshal(*v, &preAuthorizedApplications) + if err != nil { + return err + } + a.PreAuthorizedApplications = &preAuthorizedApplications + } + case "publicClient": + if v != nil { + var publicClient bool + err = json.Unmarshal(*v, &publicClient) + if err != nil { + return err + } + a.PublicClient = &publicClient + } + case "publisherDomain": + if v != nil { + var publisherDomain string + err = json.Unmarshal(*v, &publisherDomain) + if err != nil { + return err + } + a.PublisherDomain = &publisherDomain + } + case "replyUrls": + if v != nil { + var replyUrls []string + err = json.Unmarshal(*v, &replyUrls) + if err != nil { + return err + } + a.ReplyUrls = &replyUrls + } + case "requiredResourceAccess": + if v != nil { + var requiredResourceAccess []RequiredResourceAccess + err = json.Unmarshal(*v, &requiredResourceAccess) + if err != nil { + return err + } + a.RequiredResourceAccess = &requiredResourceAccess + } + case "samlMetadataUrl": + if v != nil { + var samlMetadataURL string + err = json.Unmarshal(*v, &samlMetadataURL) + if err != nil { + return err + } + a.SamlMetadataURL = &samlMetadataURL + } + case "signInAudience": + if v != nil { + var signInAudience string + err = json.Unmarshal(*v, &signInAudience) + if err != nil { + return err + } + a.SignInAudience = &signInAudience + } + case "wwwHomepage": + if v != nil { + var wwwHomepage string + err = json.Unmarshal(*v, &wwwHomepage) + if err != nil { + return err + } + a.WwwHomepage = &wwwHomepage + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[k] = additionalProperties + } + case "objectId": + if v != nil { + var objectID string + err = json.Unmarshal(*v, &objectID) + if err != nil { + return err + } + a.ObjectID = &objectID + } + case "deletionTimestamp": + if v != nil { + var deletionTimestamp date.Time + err = json.Unmarshal(*v, &deletionTimestamp) + if err != nil { + return err + } + a.DeletionTimestamp = &deletionTimestamp + } + case "objectType": + if v != nil { + var objectType ObjectType + err = json.Unmarshal(*v, &objectType) + if err != nil { + return err + } + a.ObjectType = objectType + } + } + } + + return nil +} + +// ApplicationBase active Directive Application common properties shared among GET, POST and PATCH +type ApplicationBase struct { + // AllowGuestsSignIn - A property on the application to indicate if the application accepts other IDPs or not or partially accepts. + AllowGuestsSignIn *bool `json:"allowGuestsSignIn,omitempty"` + // AllowPassthroughUsers - Indicates that the application supports pass through users who have no presence in the resource tenant. + AllowPassthroughUsers *bool `json:"allowPassthroughUsers,omitempty"` + // AppLogoURL - The url for the application logo image stored in a CDN. + AppLogoURL *string `json:"appLogoUrl,omitempty"` + // AppRoles - The collection of application roles that an application may declare. These roles can be assigned to users, groups or service principals. + AppRoles *[]AppRole `json:"appRoles,omitempty"` + // AppPermissions - The application permissions. + AppPermissions *[]string `json:"appPermissions,omitempty"` + // AvailableToOtherTenants - Whether the application is available to other tenants. + AvailableToOtherTenants *bool `json:"availableToOtherTenants,omitempty"` + // ErrorURL - A URL provided by the author of the application to report errors when using the application. + ErrorURL *string `json:"errorUrl,omitempty"` + // GroupMembershipClaims - Configures the groups claim issued in a user or OAuth 2.0 access token that the app expects. + GroupMembershipClaims interface{} `json:"groupMembershipClaims,omitempty"` + // Homepage - The home page of the application. + Homepage *string `json:"homepage,omitempty"` + // InformationalUrls - URLs with more information about the application. + InformationalUrls *InformationalURL `json:"informationalUrls,omitempty"` + // IsDeviceOnlyAuthSupported - Specifies whether this application supports device authentication without a user. The default is false. + IsDeviceOnlyAuthSupported *bool `json:"isDeviceOnlyAuthSupported,omitempty"` + // KeyCredentials - A collection of KeyCredential objects. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // KnownClientApplications - Client applications that are tied to this resource application. Consent to any of the known client applications will result in implicit consent to the resource application through a combined consent dialog (showing the OAuth permission scopes required by the client and the resource). + KnownClientApplications *[]string `json:"knownClientApplications,omitempty"` + // LogoutURL - the url of the logout page + LogoutURL *string `json:"logoutUrl,omitempty"` + // Oauth2AllowImplicitFlow - Whether to allow implicit grant flow for OAuth2 + Oauth2AllowImplicitFlow *bool `json:"oauth2AllowImplicitFlow,omitempty"` + // Oauth2AllowURLPathMatching - Specifies whether during a token Request Azure AD will allow path matching of the redirect URI against the applications collection of replyURLs. The default is false. + Oauth2AllowURLPathMatching *bool `json:"oauth2AllowUrlPathMatching,omitempty"` + // Oauth2Permissions - The collection of OAuth 2.0 permission scopes that the web API (resource) application exposes to client applications. These permission scopes may be granted to client applications during consent. + Oauth2Permissions *[]OAuth2Permission `json:"oauth2Permissions,omitempty"` + // Oauth2RequirePostResponse - Specifies whether, as part of OAuth 2.0 token requests, Azure AD will allow POST requests, as opposed to GET requests. The default is false, which specifies that only GET requests will be allowed. + Oauth2RequirePostResponse *bool `json:"oauth2RequirePostResponse,omitempty"` + // OrgRestrictions - A list of tenants allowed to access application. + OrgRestrictions *[]string `json:"orgRestrictions,omitempty"` + OptionalClaims *OptionalClaims `json:"optionalClaims,omitempty"` + // PasswordCredentials - A collection of PasswordCredential objects + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // PreAuthorizedApplications - list of pre-authorized applications. + PreAuthorizedApplications *[]PreAuthorizedApplication `json:"preAuthorizedApplications,omitempty"` + // PublicClient - Specifies whether this application is a public client (such as an installed application running on a mobile device). Default is false. + PublicClient *bool `json:"publicClient,omitempty"` + // PublisherDomain - Reliable domain which can be used to identify an application. + PublisherDomain *string `json:"publisherDomain,omitempty"` + // ReplyUrls - A collection of reply URLs for the application. + ReplyUrls *[]string `json:"replyUrls,omitempty"` + // RequiredResourceAccess - Specifies resources that this application requires access to and the set of OAuth permission scopes and application roles that it needs under each of those resources. This pre-configuration of required resource access drives the consent experience. + RequiredResourceAccess *[]RequiredResourceAccess `json:"requiredResourceAccess,omitempty"` + // SamlMetadataURL - The URL to the SAML metadata for the application. + SamlMetadataURL *string `json:"samlMetadataUrl,omitempty"` + // SignInAudience - Audience for signing in to the application (AzureADMyOrganization, AzureADAllOrganizations, AzureADAndMicrosoftAccounts). + SignInAudience *string `json:"signInAudience,omitempty"` + // WwwHomepage - The primary Web page. + WwwHomepage *string `json:"wwwHomepage,omitempty"` +} + +// ApplicationCreateParameters request parameters for creating a new application. +type ApplicationCreateParameters struct { + // DisplayName - The display name of the application. + DisplayName *string `json:"displayName,omitempty"` + // IdentifierUris - A collection of URIs for the application. + IdentifierUris *[]string `json:"identifierUris,omitempty"` + // AllowGuestsSignIn - A property on the application to indicate if the application accepts other IDPs or not or partially accepts. + AllowGuestsSignIn *bool `json:"allowGuestsSignIn,omitempty"` + // AllowPassthroughUsers - Indicates that the application supports pass through users who have no presence in the resource tenant. + AllowPassthroughUsers *bool `json:"allowPassthroughUsers,omitempty"` + // AppLogoURL - The url for the application logo image stored in a CDN. + AppLogoURL *string `json:"appLogoUrl,omitempty"` + // AppRoles - The collection of application roles that an application may declare. These roles can be assigned to users, groups or service principals. + AppRoles *[]AppRole `json:"appRoles,omitempty"` + // AppPermissions - The application permissions. + AppPermissions *[]string `json:"appPermissions,omitempty"` + // AvailableToOtherTenants - Whether the application is available to other tenants. + AvailableToOtherTenants *bool `json:"availableToOtherTenants,omitempty"` + // ErrorURL - A URL provided by the author of the application to report errors when using the application. + ErrorURL *string `json:"errorUrl,omitempty"` + // GroupMembershipClaims - Configures the groups claim issued in a user or OAuth 2.0 access token that the app expects. + GroupMembershipClaims interface{} `json:"groupMembershipClaims,omitempty"` + // Homepage - The home page of the application. + Homepage *string `json:"homepage,omitempty"` + // InformationalUrls - URLs with more information about the application. + InformationalUrls *InformationalURL `json:"informationalUrls,omitempty"` + // IsDeviceOnlyAuthSupported - Specifies whether this application supports device authentication without a user. The default is false. + IsDeviceOnlyAuthSupported *bool `json:"isDeviceOnlyAuthSupported,omitempty"` + // KeyCredentials - A collection of KeyCredential objects. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // KnownClientApplications - Client applications that are tied to this resource application. Consent to any of the known client applications will result in implicit consent to the resource application through a combined consent dialog (showing the OAuth permission scopes required by the client and the resource). + KnownClientApplications *[]string `json:"knownClientApplications,omitempty"` + // LogoutURL - the url of the logout page + LogoutURL *string `json:"logoutUrl,omitempty"` + // Oauth2AllowImplicitFlow - Whether to allow implicit grant flow for OAuth2 + Oauth2AllowImplicitFlow *bool `json:"oauth2AllowImplicitFlow,omitempty"` + // Oauth2AllowURLPathMatching - Specifies whether during a token Request Azure AD will allow path matching of the redirect URI against the applications collection of replyURLs. The default is false. + Oauth2AllowURLPathMatching *bool `json:"oauth2AllowUrlPathMatching,omitempty"` + // Oauth2Permissions - The collection of OAuth 2.0 permission scopes that the web API (resource) application exposes to client applications. These permission scopes may be granted to client applications during consent. + Oauth2Permissions *[]OAuth2Permission `json:"oauth2Permissions,omitempty"` + // Oauth2RequirePostResponse - Specifies whether, as part of OAuth 2.0 token requests, Azure AD will allow POST requests, as opposed to GET requests. The default is false, which specifies that only GET requests will be allowed. + Oauth2RequirePostResponse *bool `json:"oauth2RequirePostResponse,omitempty"` + // OrgRestrictions - A list of tenants allowed to access application. + OrgRestrictions *[]string `json:"orgRestrictions,omitempty"` + OptionalClaims *OptionalClaims `json:"optionalClaims,omitempty"` + // PasswordCredentials - A collection of PasswordCredential objects + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // PreAuthorizedApplications - list of pre-authorized applications. + PreAuthorizedApplications *[]PreAuthorizedApplication `json:"preAuthorizedApplications,omitempty"` + // PublicClient - Specifies whether this application is a public client (such as an installed application running on a mobile device). Default is false. + PublicClient *bool `json:"publicClient,omitempty"` + // PublisherDomain - Reliable domain which can be used to identify an application. + PublisherDomain *string `json:"publisherDomain,omitempty"` + // ReplyUrls - A collection of reply URLs for the application. + ReplyUrls *[]string `json:"replyUrls,omitempty"` + // RequiredResourceAccess - Specifies resources that this application requires access to and the set of OAuth permission scopes and application roles that it needs under each of those resources. This pre-configuration of required resource access drives the consent experience. + RequiredResourceAccess *[]RequiredResourceAccess `json:"requiredResourceAccess,omitempty"` + // SamlMetadataURL - The URL to the SAML metadata for the application. + SamlMetadataURL *string `json:"samlMetadataUrl,omitempty"` + // SignInAudience - Audience for signing in to the application (AzureADMyOrganization, AzureADAllOrganizations, AzureADAndMicrosoftAccounts). + SignInAudience *string `json:"signInAudience,omitempty"` + // WwwHomepage - The primary Web page. + WwwHomepage *string `json:"wwwHomepage,omitempty"` +} + +// ApplicationListResult application list operation result. +type ApplicationListResult struct { + autorest.Response `json:"-"` + // Value - A collection of applications. + Value *[]Application `json:"value,omitempty"` + // OdataNextLink - The URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// ApplicationListResultIterator provides access to a complete listing of Application values. +type ApplicationListResultIterator struct { + i int + page ApplicationListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ApplicationListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ApplicationListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ApplicationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ApplicationListResultIterator) Response() ApplicationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ApplicationListResultIterator) Value() Application { + if !iter.page.NotDone() { + return Application{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ApplicationListResultIterator type. +func NewApplicationListResultIterator(page ApplicationListResultPage) ApplicationListResultIterator { + return ApplicationListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (alr ApplicationListResult) IsEmpty() bool { + return alr.Value == nil || len(*alr.Value) == 0 +} + +// ApplicationListResultPage contains a page of Application values. +type ApplicationListResultPage struct { + fn func(context.Context, ApplicationListResult) (ApplicationListResult, error) + alr ApplicationListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ApplicationListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.alr) + if err != nil { + return err + } + page.alr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ApplicationListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ApplicationListResultPage) NotDone() bool { + return !page.alr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ApplicationListResultPage) Response() ApplicationListResult { + return page.alr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ApplicationListResultPage) Values() []Application { + if page.alr.IsEmpty() { + return nil + } + return *page.alr.Value +} + +// Creates a new instance of the ApplicationListResultPage type. +func NewApplicationListResultPage(getNextPage func(context.Context, ApplicationListResult) (ApplicationListResult, error)) ApplicationListResultPage { + return ApplicationListResultPage{fn: getNextPage} +} + +// ApplicationUpdateParameters request parameters for updating a new application. +type ApplicationUpdateParameters struct { + // DisplayName - The display name of the application. + DisplayName *string `json:"displayName,omitempty"` + // IdentifierUris - A collection of URIs for the application. + IdentifierUris *[]string `json:"identifierUris,omitempty"` + // AllowGuestsSignIn - A property on the application to indicate if the application accepts other IDPs or not or partially accepts. + AllowGuestsSignIn *bool `json:"allowGuestsSignIn,omitempty"` + // AllowPassthroughUsers - Indicates that the application supports pass through users who have no presence in the resource tenant. + AllowPassthroughUsers *bool `json:"allowPassthroughUsers,omitempty"` + // AppLogoURL - The url for the application logo image stored in a CDN. + AppLogoURL *string `json:"appLogoUrl,omitempty"` + // AppRoles - The collection of application roles that an application may declare. These roles can be assigned to users, groups or service principals. + AppRoles *[]AppRole `json:"appRoles,omitempty"` + // AppPermissions - The application permissions. + AppPermissions *[]string `json:"appPermissions,omitempty"` + // AvailableToOtherTenants - Whether the application is available to other tenants. + AvailableToOtherTenants *bool `json:"availableToOtherTenants,omitempty"` + // ErrorURL - A URL provided by the author of the application to report errors when using the application. + ErrorURL *string `json:"errorUrl,omitempty"` + // GroupMembershipClaims - Configures the groups claim issued in a user or OAuth 2.0 access token that the app expects. + GroupMembershipClaims interface{} `json:"groupMembershipClaims,omitempty"` + // Homepage - The home page of the application. + Homepage *string `json:"homepage,omitempty"` + // InformationalUrls - URLs with more information about the application. + InformationalUrls *InformationalURL `json:"informationalUrls,omitempty"` + // IsDeviceOnlyAuthSupported - Specifies whether this application supports device authentication without a user. The default is false. + IsDeviceOnlyAuthSupported *bool `json:"isDeviceOnlyAuthSupported,omitempty"` + // KeyCredentials - A collection of KeyCredential objects. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // KnownClientApplications - Client applications that are tied to this resource application. Consent to any of the known client applications will result in implicit consent to the resource application through a combined consent dialog (showing the OAuth permission scopes required by the client and the resource). + KnownClientApplications *[]string `json:"knownClientApplications,omitempty"` + // LogoutURL - the url of the logout page + LogoutURL *string `json:"logoutUrl,omitempty"` + // Oauth2AllowImplicitFlow - Whether to allow implicit grant flow for OAuth2 + Oauth2AllowImplicitFlow *bool `json:"oauth2AllowImplicitFlow,omitempty"` + // Oauth2AllowURLPathMatching - Specifies whether during a token Request Azure AD will allow path matching of the redirect URI against the applications collection of replyURLs. The default is false. + Oauth2AllowURLPathMatching *bool `json:"oauth2AllowUrlPathMatching,omitempty"` + // Oauth2Permissions - The collection of OAuth 2.0 permission scopes that the web API (resource) application exposes to client applications. These permission scopes may be granted to client applications during consent. + Oauth2Permissions *[]OAuth2Permission `json:"oauth2Permissions,omitempty"` + // Oauth2RequirePostResponse - Specifies whether, as part of OAuth 2.0 token requests, Azure AD will allow POST requests, as opposed to GET requests. The default is false, which specifies that only GET requests will be allowed. + Oauth2RequirePostResponse *bool `json:"oauth2RequirePostResponse,omitempty"` + // OrgRestrictions - A list of tenants allowed to access application. + OrgRestrictions *[]string `json:"orgRestrictions,omitempty"` + OptionalClaims *OptionalClaims `json:"optionalClaims,omitempty"` + // PasswordCredentials - A collection of PasswordCredential objects + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // PreAuthorizedApplications - list of pre-authorized applications. + PreAuthorizedApplications *[]PreAuthorizedApplication `json:"preAuthorizedApplications,omitempty"` + // PublicClient - Specifies whether this application is a public client (such as an installed application running on a mobile device). Default is false. + PublicClient *bool `json:"publicClient,omitempty"` + // PublisherDomain - Reliable domain which can be used to identify an application. + PublisherDomain *string `json:"publisherDomain,omitempty"` + // ReplyUrls - A collection of reply URLs for the application. + ReplyUrls *[]string `json:"replyUrls,omitempty"` + // RequiredResourceAccess - Specifies resources that this application requires access to and the set of OAuth permission scopes and application roles that it needs under each of those resources. This pre-configuration of required resource access drives the consent experience. + RequiredResourceAccess *[]RequiredResourceAccess `json:"requiredResourceAccess,omitempty"` + // SamlMetadataURL - The URL to the SAML metadata for the application. + SamlMetadataURL *string `json:"samlMetadataUrl,omitempty"` + // SignInAudience - Audience for signing in to the application (AzureADMyOrganization, AzureADAllOrganizations, AzureADAndMicrosoftAccounts). + SignInAudience *string `json:"signInAudience,omitempty"` + // WwwHomepage - The primary Web page. + WwwHomepage *string `json:"wwwHomepage,omitempty"` +} + +// AppRole ... +type AppRole struct { + // ID - Unique role identifier inside the appRoles collection. + ID *string `json:"id,omitempty"` + // AllowedMemberTypes - Specifies whether this app role definition can be assigned to users and groups by setting to 'User', or to other applications (that are accessing this application in daemon service scenarios) by setting to 'Application', or to both. + AllowedMemberTypes *[]string `json:"allowedMemberTypes,omitempty"` + // Description - Permission help text that appears in the admin app assignment and consent experiences. + Description *string `json:"description,omitempty"` + // DisplayName - Display name for the permission that appears in the admin consent and app assignment experiences. + DisplayName *string `json:"displayName,omitempty"` + // IsEnabled - When creating or updating a role definition, this must be set to true (which is the default). To delete a role, this must first be set to false. At that point, in a subsequent call, this role may be removed. + IsEnabled *bool `json:"isEnabled,omitempty"` + // Value - Specifies the value of the roles claim that the application should expect in the authentication and access tokens. + Value *string `json:"value,omitempty"` +} + +// CheckGroupMembershipParameters request parameters for IsMemberOf API call. +type CheckGroupMembershipParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // GroupID - The object ID of the group to check. + GroupID *string `json:"groupId,omitempty"` + // MemberID - The object ID of the contact, group, user, or service principal to check for membership in the specified group. + MemberID *string `json:"memberId,omitempty"` +} + +// MarshalJSON is the custom marshaler for CheckGroupMembershipParameters. +func (cgmp CheckGroupMembershipParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cgmp.GroupID != nil { + objectMap["groupId"] = cgmp.GroupID + } + if cgmp.MemberID != nil { + objectMap["memberId"] = cgmp.MemberID + } + for k, v := range cgmp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CheckGroupMembershipParameters struct. +func (cgmp *CheckGroupMembershipParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if cgmp.AdditionalProperties == nil { + cgmp.AdditionalProperties = make(map[string]interface{}) + } + cgmp.AdditionalProperties[k] = additionalProperties + } + case "groupId": + if v != nil { + var groupID string + err = json.Unmarshal(*v, &groupID) + if err != nil { + return err + } + cgmp.GroupID = &groupID + } + case "memberId": + if v != nil { + var memberID string + err = json.Unmarshal(*v, &memberID) + if err != nil { + return err + } + cgmp.MemberID = &memberID + } + } + } + + return nil +} + +// CheckGroupMembershipResult server response for IsMemberOf API call +type CheckGroupMembershipResult struct { + autorest.Response `json:"-"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // Value - True if the specified user, group, contact, or service principal has either direct or transitive membership in the specified group; otherwise, false. + Value *bool `json:"value,omitempty"` +} + +// MarshalJSON is the custom marshaler for CheckGroupMembershipResult. +func (cgmr CheckGroupMembershipResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cgmr.Value != nil { + objectMap["value"] = cgmr.Value + } + for k, v := range cgmr.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CheckGroupMembershipResult struct. +func (cgmr *CheckGroupMembershipResult) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if cgmr.AdditionalProperties == nil { + cgmr.AdditionalProperties = make(map[string]interface{}) + } + cgmr.AdditionalProperties[k] = additionalProperties + } + case "value": + if v != nil { + var value bool + err = json.Unmarshal(*v, &value) + if err != nil { + return err + } + cgmr.Value = &value + } + } + } + + return nil +} + +// BasicDirectoryObject represents an Azure Active Directory object. +type BasicDirectoryObject interface { + AsApplication() (*Application, bool) + AsADGroup() (*ADGroup, bool) + AsServicePrincipal() (*ServicePrincipal, bool) + AsUser() (*User, bool) + AsDirectoryObject() (*DirectoryObject, bool) +} + +// DirectoryObject represents an Azure Active Directory object. +type DirectoryObject struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectID - READ-ONLY; The object ID. + ObjectID *string `json:"objectId,omitempty"` + // DeletionTimestamp - READ-ONLY; The time at which the directory object was deleted. + DeletionTimestamp *date.Time `json:"deletionTimestamp,omitempty"` + // ObjectType - Possible values include: 'ObjectTypeDirectoryObject', 'ObjectTypeApplication', 'ObjectTypeGroup', 'ObjectTypeServicePrincipal', 'ObjectTypeUser' + ObjectType ObjectType `json:"objectType,omitempty"` +} + +func unmarshalBasicDirectoryObject(body []byte) (BasicDirectoryObject, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["objectType"] { + case string(ObjectTypeApplication): + var a Application + err := json.Unmarshal(body, &a) + return a, err + case string(ObjectTypeGroup): + var ag ADGroup + err := json.Unmarshal(body, &ag) + return ag, err + case string(ObjectTypeServicePrincipal): + var sp ServicePrincipal + err := json.Unmarshal(body, &sp) + return sp, err + case string(ObjectTypeUser): + var u User + err := json.Unmarshal(body, &u) + return u, err + default: + var do DirectoryObject + err := json.Unmarshal(body, &do) + return do, err + } +} +func unmarshalBasicDirectoryObjectArray(body []byte) ([]BasicDirectoryObject, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + doArray := make([]BasicDirectoryObject, len(rawMessages)) + + for index, rawMessage := range rawMessages { + do, err := unmarshalBasicDirectoryObject(*rawMessage) + if err != nil { + return nil, err + } + doArray[index] = do + } + return doArray, nil +} + +// MarshalJSON is the custom marshaler for DirectoryObject. +func (do DirectoryObject) MarshalJSON() ([]byte, error) { + do.ObjectType = ObjectTypeDirectoryObject + objectMap := make(map[string]interface{}) + if do.ObjectType != "" { + objectMap["objectType"] = do.ObjectType + } + for k, v := range do.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// AsApplication is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsApplication() (*Application, bool) { + return nil, false +} + +// AsADGroup is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsADGroup() (*ADGroup, bool) { + return nil, false +} + +// AsServicePrincipal is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsServicePrincipal() (*ServicePrincipal, bool) { + return nil, false +} + +// AsUser is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsUser() (*User, bool) { + return nil, false +} + +// AsDirectoryObject is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsDirectoryObject() (*DirectoryObject, bool) { + return &do, true +} + +// AsBasicDirectoryObject is the BasicDirectoryObject implementation for DirectoryObject. +func (do DirectoryObject) AsBasicDirectoryObject() (BasicDirectoryObject, bool) { + return &do, true +} + +// UnmarshalJSON is the custom unmarshaler for DirectoryObject struct. +func (do *DirectoryObject) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if do.AdditionalProperties == nil { + do.AdditionalProperties = make(map[string]interface{}) + } + do.AdditionalProperties[k] = additionalProperties + } + case "objectId": + if v != nil { + var objectID string + err = json.Unmarshal(*v, &objectID) + if err != nil { + return err + } + do.ObjectID = &objectID + } + case "deletionTimestamp": + if v != nil { + var deletionTimestamp date.Time + err = json.Unmarshal(*v, &deletionTimestamp) + if err != nil { + return err + } + do.DeletionTimestamp = &deletionTimestamp + } + case "objectType": + if v != nil { + var objectType ObjectType + err = json.Unmarshal(*v, &objectType) + if err != nil { + return err + } + do.ObjectType = objectType + } + } + } + + return nil +} + +// DirectoryObjectListResult directoryObject list operation result. +type DirectoryObjectListResult struct { + autorest.Response `json:"-"` + // Value - A collection of DirectoryObject. + Value *[]BasicDirectoryObject `json:"value,omitempty"` + // OdataNextLink - The URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DirectoryObjectListResult struct. +func (dolr *DirectoryObjectListResult) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "value": + if v != nil { + value, err := unmarshalBasicDirectoryObjectArray(*v) + if err != nil { + return err + } + dolr.Value = &value + } + case "odata.nextLink": + if v != nil { + var odataNextLink string + err = json.Unmarshal(*v, &odataNextLink) + if err != nil { + return err + } + dolr.OdataNextLink = &odataNextLink + } + } + } + + return nil +} + +// DirectoryObjectListResultIterator provides access to a complete listing of DirectoryObject values. +type DirectoryObjectListResultIterator struct { + i int + page DirectoryObjectListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *DirectoryObjectListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DirectoryObjectListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *DirectoryObjectListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DirectoryObjectListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter DirectoryObjectListResultIterator) Response() DirectoryObjectListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter DirectoryObjectListResultIterator) Value() BasicDirectoryObject { + if !iter.page.NotDone() { + return DirectoryObject{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the DirectoryObjectListResultIterator type. +func NewDirectoryObjectListResultIterator(page DirectoryObjectListResultPage) DirectoryObjectListResultIterator { + return DirectoryObjectListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (dolr DirectoryObjectListResult) IsEmpty() bool { + return dolr.Value == nil || len(*dolr.Value) == 0 +} + +// directoryObjectListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dolr DirectoryObjectListResult) directoryObjectListResultPreparer(ctx context.Context) (*http.Request, error) { + if dolr.OdataNextLink == nil || len(to.String(dolr.OdataNextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dolr.OdataNextLink))) +} + +// DirectoryObjectListResultPage contains a page of BasicDirectoryObject values. +type DirectoryObjectListResultPage struct { + fn func(context.Context, DirectoryObjectListResult) (DirectoryObjectListResult, error) + dolr DirectoryObjectListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *DirectoryObjectListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DirectoryObjectListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.dolr) + if err != nil { + return err + } + page.dolr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *DirectoryObjectListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DirectoryObjectListResultPage) NotDone() bool { + return !page.dolr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DirectoryObjectListResultPage) Response() DirectoryObjectListResult { + return page.dolr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DirectoryObjectListResultPage) Values() []BasicDirectoryObject { + if page.dolr.IsEmpty() { + return nil + } + return *page.dolr.Value +} + +// Creates a new instance of the DirectoryObjectListResultPage type. +func NewDirectoryObjectListResultPage(getNextPage func(context.Context, DirectoryObjectListResult) (DirectoryObjectListResult, error)) DirectoryObjectListResultPage { + return DirectoryObjectListResultPage{fn: getNextPage} +} + +// Domain active Directory Domain information. +type Domain struct { + autorest.Response `json:"-"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // AuthenticationType - READ-ONLY; the type of the authentication into the domain. + AuthenticationType *string `json:"authenticationType,omitempty"` + // IsDefault - READ-ONLY; if this is the default domain in the tenant. + IsDefault *bool `json:"isDefault,omitempty"` + // IsVerified - READ-ONLY; if this domain's ownership is verified. + IsVerified *bool `json:"isVerified,omitempty"` + // Name - the domain name. + Name *string `json:"name,omitempty"` +} + +// MarshalJSON is the custom marshaler for Domain. +func (d Domain) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if d.Name != nil { + objectMap["name"] = d.Name + } + for k, v := range d.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Domain struct. +func (d *Domain) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if d.AdditionalProperties == nil { + d.AdditionalProperties = make(map[string]interface{}) + } + d.AdditionalProperties[k] = additionalProperties + } + case "authenticationType": + if v != nil { + var authenticationType string + err = json.Unmarshal(*v, &authenticationType) + if err != nil { + return err + } + d.AuthenticationType = &authenticationType + } + case "isDefault": + if v != nil { + var isDefault bool + err = json.Unmarshal(*v, &isDefault) + if err != nil { + return err + } + d.IsDefault = &isDefault + } + case "isVerified": + if v != nil { + var isVerified bool + err = json.Unmarshal(*v, &isVerified) + if err != nil { + return err + } + d.IsVerified = &isVerified + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + d.Name = &name + } + } + } + + return nil +} + +// DomainListResult server response for Get tenant domains API call. +type DomainListResult struct { + autorest.Response `json:"-"` + // Value - the list of domains. + Value *[]Domain `json:"value,omitempty"` +} + +// ErrorMessage active Directory error message. +type ErrorMessage struct { + // Message - Error message value. + Message *string `json:"value,omitempty"` +} + +// GetObjectsParameters request parameters for the GetObjectsByObjectIds API. +type GetObjectsParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectIds - The requested object IDs. + ObjectIds *[]string `json:"objectIds,omitempty"` + // Types - The requested object types. + Types *[]string `json:"types,omitempty"` + // IncludeDirectoryObjectReferences - If true, also searches for object IDs in the partner tenant. + IncludeDirectoryObjectReferences *bool `json:"includeDirectoryObjectReferences,omitempty"` +} + +// MarshalJSON is the custom marshaler for GetObjectsParameters. +func (gop GetObjectsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gop.ObjectIds != nil { + objectMap["objectIds"] = gop.ObjectIds + } + if gop.Types != nil { + objectMap["types"] = gop.Types + } + if gop.IncludeDirectoryObjectReferences != nil { + objectMap["includeDirectoryObjectReferences"] = gop.IncludeDirectoryObjectReferences + } + for k, v := range gop.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GetObjectsParameters struct. +func (gop *GetObjectsParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if gop.AdditionalProperties == nil { + gop.AdditionalProperties = make(map[string]interface{}) + } + gop.AdditionalProperties[k] = additionalProperties + } + case "objectIds": + if v != nil { + var objectIds []string + err = json.Unmarshal(*v, &objectIds) + if err != nil { + return err + } + gop.ObjectIds = &objectIds + } + case "types": + if v != nil { + var typesVar []string + err = json.Unmarshal(*v, &typesVar) + if err != nil { + return err + } + gop.Types = &typesVar + } + case "includeDirectoryObjectReferences": + if v != nil { + var includeDirectoryObjectReferences bool + err = json.Unmarshal(*v, &includeDirectoryObjectReferences) + if err != nil { + return err + } + gop.IncludeDirectoryObjectReferences = &includeDirectoryObjectReferences + } + } + } + + return nil +} + +// GraphError active Directory error information. +type GraphError struct { + // OdataError - A Graph API error. + *OdataError `json:"odata.error,omitempty"` +} + +// MarshalJSON is the custom marshaler for GraphError. +func (ge GraphError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ge.OdataError != nil { + objectMap["odata.error"] = ge.OdataError + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GraphError struct. +func (ge *GraphError) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "odata.error": + if v != nil { + var odataError OdataError + err = json.Unmarshal(*v, &odataError) + if err != nil { + return err + } + ge.OdataError = &odataError + } + } + } + + return nil +} + +// GroupAddMemberParameters request parameters for adding a member to a group. +type GroupAddMemberParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // URL - A member object URL, such as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the member (user, application, servicePrincipal, group) to be added. + URL *string `json:"url,omitempty"` +} + +// MarshalJSON is the custom marshaler for GroupAddMemberParameters. +func (gamp GroupAddMemberParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gamp.URL != nil { + objectMap["url"] = gamp.URL + } + for k, v := range gamp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GroupAddMemberParameters struct. +func (gamp *GroupAddMemberParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if gamp.AdditionalProperties == nil { + gamp.AdditionalProperties = make(map[string]interface{}) + } + gamp.AdditionalProperties[k] = additionalProperties + } + case "url": + if v != nil { + var URL string + err = json.Unmarshal(*v, &URL) + if err != nil { + return err + } + gamp.URL = &URL + } + } + } + + return nil +} + +// GroupCreateParameters request parameters for creating a new group. +type GroupCreateParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // DisplayName - Group display name + DisplayName *string `json:"displayName,omitempty"` + // MailEnabled - Whether the group is mail-enabled. Must be false. This is because only pure security groups can be created using the Graph API. + MailEnabled *bool `json:"mailEnabled,omitempty"` + // MailNickname - Mail nickname + MailNickname *string `json:"mailNickname,omitempty"` + // SecurityEnabled - Whether the group is a security group. Must be true. This is because only pure security groups can be created using the Graph API. + SecurityEnabled *bool `json:"securityEnabled,omitempty"` +} + +// MarshalJSON is the custom marshaler for GroupCreateParameters. +func (gcp GroupCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gcp.DisplayName != nil { + objectMap["displayName"] = gcp.DisplayName + } + if gcp.MailEnabled != nil { + objectMap["mailEnabled"] = gcp.MailEnabled + } + if gcp.MailNickname != nil { + objectMap["mailNickname"] = gcp.MailNickname + } + if gcp.SecurityEnabled != nil { + objectMap["securityEnabled"] = gcp.SecurityEnabled + } + for k, v := range gcp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GroupCreateParameters struct. +func (gcp *GroupCreateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if gcp.AdditionalProperties == nil { + gcp.AdditionalProperties = make(map[string]interface{}) + } + gcp.AdditionalProperties[k] = additionalProperties + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + gcp.DisplayName = &displayName + } + case "mailEnabled": + if v != nil { + var mailEnabled bool + err = json.Unmarshal(*v, &mailEnabled) + if err != nil { + return err + } + gcp.MailEnabled = &mailEnabled + } + case "mailNickname": + if v != nil { + var mailNickname string + err = json.Unmarshal(*v, &mailNickname) + if err != nil { + return err + } + gcp.MailNickname = &mailNickname + } + case "securityEnabled": + if v != nil { + var securityEnabled bool + err = json.Unmarshal(*v, &securityEnabled) + if err != nil { + return err + } + gcp.SecurityEnabled = &securityEnabled + } + } + } + + return nil +} + +// GroupGetMemberGroupsParameters request parameters for GetMemberGroups API call. +type GroupGetMemberGroupsParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // SecurityEnabledOnly - If true, only membership in security-enabled groups should be checked. Otherwise, membership in all groups should be checked. + SecurityEnabledOnly *bool `json:"securityEnabledOnly,omitempty"` +} + +// MarshalJSON is the custom marshaler for GroupGetMemberGroupsParameters. +func (ggmgp GroupGetMemberGroupsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ggmgp.SecurityEnabledOnly != nil { + objectMap["securityEnabledOnly"] = ggmgp.SecurityEnabledOnly + } + for k, v := range ggmgp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GroupGetMemberGroupsParameters struct. +func (ggmgp *GroupGetMemberGroupsParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ggmgp.AdditionalProperties == nil { + ggmgp.AdditionalProperties = make(map[string]interface{}) + } + ggmgp.AdditionalProperties[k] = additionalProperties + } + case "securityEnabledOnly": + if v != nil { + var securityEnabledOnly bool + err = json.Unmarshal(*v, &securityEnabledOnly) + if err != nil { + return err + } + ggmgp.SecurityEnabledOnly = &securityEnabledOnly + } + } + } + + return nil +} + +// GroupGetMemberGroupsResult server response for GetMemberGroups API call. +type GroupGetMemberGroupsResult struct { + autorest.Response `json:"-"` + // Value - A collection of group IDs of which the group is a member. + Value *[]string `json:"value,omitempty"` +} + +// GroupListResult server response for Get tenant groups API call +type GroupListResult struct { + autorest.Response `json:"-"` + // Value - A collection of Active Directory groups. + Value *[]ADGroup `json:"value,omitempty"` + // OdataNextLink - The URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// GroupListResultIterator provides access to a complete listing of ADGroup values. +type GroupListResultIterator struct { + i int + page GroupListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *GroupListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GroupListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GroupListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter GroupListResultIterator) Response() GroupListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter GroupListResultIterator) Value() ADGroup { + if !iter.page.NotDone() { + return ADGroup{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GroupListResultIterator type. +func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator { + return GroupListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (glr GroupListResult) IsEmpty() bool { + return glr.Value == nil || len(*glr.Value) == 0 +} + +// GroupListResultPage contains a page of ADGroup values. +type GroupListResultPage struct { + fn func(context.Context, GroupListResult) (GroupListResult, error) + glr GroupListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *GroupListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.glr) + if err != nil { + return err + } + page.glr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GroupListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GroupListResultPage) NotDone() bool { + return !page.glr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GroupListResultPage) Response() GroupListResult { + return page.glr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GroupListResultPage) Values() []ADGroup { + if page.glr.IsEmpty() { + return nil + } + return *page.glr.Value +} + +// Creates a new instance of the GroupListResultPage type. +func NewGroupListResultPage(getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage { + return GroupListResultPage{fn: getNextPage} +} + +// InformationalURL represents a group of URIs that provide terms of service, marketing, support and +// privacy policy information about an application. The default value for each string is null. +type InformationalURL struct { + // TermsOfService - The terms of service URI + TermsOfService *string `json:"termsOfService,omitempty"` + // Marketing - The marketing URI + Marketing *string `json:"marketing,omitempty"` + // Privacy - The privacy policy URI + Privacy *string `json:"privacy,omitempty"` + // Support - The support URI + Support *string `json:"support,omitempty"` +} + +// KeyCredential active Directory Key Credential information. +type KeyCredential struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // StartDate - Start date. + StartDate *date.Time `json:"startDate,omitempty"` + // EndDate - End date. + EndDate *date.Time `json:"endDate,omitempty"` + // Value - Key value. + Value *string `json:"value,omitempty"` + // KeyID - Key ID. + KeyID *string `json:"keyId,omitempty"` + // Usage - Usage. Acceptable values are 'Verify' and 'Sign'. + Usage *string `json:"usage,omitempty"` + // Type - Type. Acceptable values are 'AsymmetricX509Cert' and 'Symmetric'. + Type *string `json:"type,omitempty"` + // CustomKeyIdentifier - Custom Key Identifier + CustomKeyIdentifier *string `json:"customKeyIdentifier,omitempty"` +} + +// MarshalJSON is the custom marshaler for KeyCredential. +func (kc KeyCredential) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if kc.StartDate != nil { + objectMap["startDate"] = kc.StartDate + } + if kc.EndDate != nil { + objectMap["endDate"] = kc.EndDate + } + if kc.Value != nil { + objectMap["value"] = kc.Value + } + if kc.KeyID != nil { + objectMap["keyId"] = kc.KeyID + } + if kc.Usage != nil { + objectMap["usage"] = kc.Usage + } + if kc.Type != nil { + objectMap["type"] = kc.Type + } + if kc.CustomKeyIdentifier != nil { + objectMap["customKeyIdentifier"] = kc.CustomKeyIdentifier + } + for k, v := range kc.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for KeyCredential struct. +func (kc *KeyCredential) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if kc.AdditionalProperties == nil { + kc.AdditionalProperties = make(map[string]interface{}) + } + kc.AdditionalProperties[k] = additionalProperties + } + case "startDate": + if v != nil { + var startDate date.Time + err = json.Unmarshal(*v, &startDate) + if err != nil { + return err + } + kc.StartDate = &startDate + } + case "endDate": + if v != nil { + var endDate date.Time + err = json.Unmarshal(*v, &endDate) + if err != nil { + return err + } + kc.EndDate = &endDate + } + case "value": + if v != nil { + var value string + err = json.Unmarshal(*v, &value) + if err != nil { + return err + } + kc.Value = &value + } + case "keyId": + if v != nil { + var keyID string + err = json.Unmarshal(*v, &keyID) + if err != nil { + return err + } + kc.KeyID = &keyID + } + case "usage": + if v != nil { + var usage string + err = json.Unmarshal(*v, &usage) + if err != nil { + return err + } + kc.Usage = &usage + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + kc.Type = &typeVar + } + case "customKeyIdentifier": + if v != nil { + var customKeyIdentifier string + err = json.Unmarshal(*v, &customKeyIdentifier) + if err != nil { + return err + } + kc.CustomKeyIdentifier = &customKeyIdentifier + } + } + } + + return nil +} + +// KeyCredentialListResult keyCredential list operation result. +type KeyCredentialListResult struct { + autorest.Response `json:"-"` + // Value - A collection of KeyCredentials. + Value *[]KeyCredential `json:"value,omitempty"` +} + +// KeyCredentialsUpdateParameters request parameters for a KeyCredentials update operation +type KeyCredentialsUpdateParameters struct { + // Value - A collection of KeyCredentials. + Value *[]KeyCredential `json:"value,omitempty"` +} + +// OAuth2Permission represents an OAuth 2.0 delegated permission scope. The specified OAuth 2.0 delegated +// permission scopes may be requested by client applications (through the requiredResourceAccess collection +// on the Application object) when calling a resource application. The oauth2Permissions property of the +// ServicePrincipal entity and of the Application entity is a collection of OAuth2Permission. +type OAuth2Permission struct { + // AdminConsentDescription - Permission help text that appears in the admin consent and app assignment experiences. + AdminConsentDescription *string `json:"adminConsentDescription,omitempty"` + // AdminConsentDisplayName - Display name for the permission that appears in the admin consent and app assignment experiences. + AdminConsentDisplayName *string `json:"adminConsentDisplayName,omitempty"` + // ID - Unique scope permission identifier inside the oauth2Permissions collection. + ID *string `json:"id,omitempty"` + // IsEnabled - When creating or updating a permission, this property must be set to true (which is the default). To delete a permission, this property must first be set to false. At that point, in a subsequent call, the permission may be removed. + IsEnabled *bool `json:"isEnabled,omitempty"` + // Type - Specifies whether this scope permission can be consented to by an end user, or whether it is a tenant-wide permission that must be consented to by a Company Administrator. Possible values are "User" or "Admin". + Type *string `json:"type,omitempty"` + // UserConsentDescription - Permission help text that appears in the end user consent experience. + UserConsentDescription *string `json:"userConsentDescription,omitempty"` + // UserConsentDisplayName - Display name for the permission that appears in the end user consent experience. + UserConsentDisplayName *string `json:"userConsentDisplayName,omitempty"` + // Value - The value of the scope claim that the resource application should expect in the OAuth 2.0 access token. + Value *string `json:"value,omitempty"` +} + +// OAuth2PermissionGrant ... +type OAuth2PermissionGrant struct { + autorest.Response `json:"-"` + // OdataType - Microsoft.DirectoryServices.OAuth2PermissionGrant + OdataType *string `json:"odata.type,omitempty"` + // ClientID - The id of the resource's service principal granted consent to impersonate the user when accessing the resource (represented by the resourceId property). + ClientID *string `json:"clientId,omitempty"` + // ObjectID - The id of the permission grant + ObjectID *string `json:"objectId,omitempty"` + // ConsentType - Indicates if consent was provided by the administrator (on behalf of the organization) or by an individual. Possible values include: 'AllPrincipals', 'Principal' + ConsentType ConsentType `json:"consentType,omitempty"` + // PrincipalID - When consent type is Principal, this property specifies the id of the user that granted consent and applies only for that user. + PrincipalID *string `json:"principalId,omitempty"` + // ResourceID - Object Id of the resource you want to grant + ResourceID *string `json:"resourceId,omitempty"` + // Scope - Specifies the value of the scope claim that the resource application should expect in the OAuth 2.0 access token. For example, User.Read + Scope *string `json:"scope,omitempty"` + // StartTime - Start time for TTL + StartTime *string `json:"startTime,omitempty"` + // ExpiryTime - Expiry time for TTL + ExpiryTime *string `json:"expiryTime,omitempty"` +} + +// OAuth2PermissionGrantListResult server response for get oauth2 permissions grants +type OAuth2PermissionGrantListResult struct { + autorest.Response `json:"-"` + // Value - the list of oauth2 permissions grants + Value *[]OAuth2PermissionGrant `json:"value,omitempty"` + // OdataNextLink - the URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// OAuth2PermissionGrantListResultIterator provides access to a complete listing of OAuth2PermissionGrant +// values. +type OAuth2PermissionGrantListResultIterator struct { + i int + page OAuth2PermissionGrantListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OAuth2PermissionGrantListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *OAuth2PermissionGrantListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OAuth2PermissionGrantListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OAuth2PermissionGrantListResultIterator) Response() OAuth2PermissionGrantListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OAuth2PermissionGrantListResultIterator) Value() OAuth2PermissionGrant { + if !iter.page.NotDone() { + return OAuth2PermissionGrant{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the OAuth2PermissionGrantListResultIterator type. +func NewOAuth2PermissionGrantListResultIterator(page OAuth2PermissionGrantListResultPage) OAuth2PermissionGrantListResultIterator { + return OAuth2PermissionGrantListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (oa2pglr OAuth2PermissionGrantListResult) IsEmpty() bool { + return oa2pglr.Value == nil || len(*oa2pglr.Value) == 0 +} + +// OAuth2PermissionGrantListResultPage contains a page of OAuth2PermissionGrant values. +type OAuth2PermissionGrantListResultPage struct { + fn func(context.Context, OAuth2PermissionGrantListResult) (OAuth2PermissionGrantListResult, error) + oa2pglr OAuth2PermissionGrantListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OAuth2PermissionGrantListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.oa2pglr) + if err != nil { + return err + } + page.oa2pglr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *OAuth2PermissionGrantListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OAuth2PermissionGrantListResultPage) NotDone() bool { + return !page.oa2pglr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OAuth2PermissionGrantListResultPage) Response() OAuth2PermissionGrantListResult { + return page.oa2pglr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OAuth2PermissionGrantListResultPage) Values() []OAuth2PermissionGrant { + if page.oa2pglr.IsEmpty() { + return nil + } + return *page.oa2pglr.Value +} + +// Creates a new instance of the OAuth2PermissionGrantListResultPage type. +func NewOAuth2PermissionGrantListResultPage(getNextPage func(context.Context, OAuth2PermissionGrantListResult) (OAuth2PermissionGrantListResult, error)) OAuth2PermissionGrantListResultPage { + return OAuth2PermissionGrantListResultPage{fn: getNextPage} +} + +// OdataError active Directory OData error information. +type OdataError struct { + // Code - Error code. + Code *string `json:"code,omitempty"` + // ErrorMessage - Error Message. + *ErrorMessage `json:"message,omitempty"` +} + +// MarshalJSON is the custom marshaler for OdataError. +func (oe OdataError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if oe.Code != nil { + objectMap["code"] = oe.Code + } + if oe.ErrorMessage != nil { + objectMap["message"] = oe.ErrorMessage + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for OdataError struct. +func (oe *OdataError) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "code": + if v != nil { + var code string + err = json.Unmarshal(*v, &code) + if err != nil { + return err + } + oe.Code = &code + } + case "message": + if v != nil { + var errorMessage ErrorMessage + err = json.Unmarshal(*v, &errorMessage) + if err != nil { + return err + } + oe.ErrorMessage = &errorMessage + } + } + } + + return nil +} + +// OptionalClaim specifying the claims to be included in a token. +type OptionalClaim struct { + // Name - Claim name. + Name *string `json:"name,omitempty"` + // Source - Claim source. + Source *string `json:"source,omitempty"` + // Essential - Is this a required claim. + Essential *bool `json:"essential,omitempty"` + AdditionalProperties interface{} `json:"additionalProperties,omitempty"` +} + +// OptionalClaims specifying the claims to be included in the token. +type OptionalClaims struct { + // IDToken - Optional claims requested to be included in the id token. + IDToken *[]OptionalClaim `json:"idToken,omitempty"` + // AccessToken - Optional claims requested to be included in the access token. + AccessToken *[]OptionalClaim `json:"accessToken,omitempty"` + // SamlToken - Optional claims requested to be included in the saml token. + SamlToken *[]OptionalClaim `json:"samlToken,omitempty"` +} + +// PasswordCredential active Directory Password Credential information. +type PasswordCredential struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // StartDate - Start date. + StartDate *date.Time `json:"startDate,omitempty"` + // EndDate - End date. + EndDate *date.Time `json:"endDate,omitempty"` + // KeyID - Key ID. + KeyID *string `json:"keyId,omitempty"` + // Value - Key value. + Value *string `json:"value,omitempty"` + // CustomKeyIdentifier - Custom Key Identifier + CustomKeyIdentifier *[]byte `json:"customKeyIdentifier,omitempty"` +} + +// MarshalJSON is the custom marshaler for PasswordCredential. +func (pc PasswordCredential) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pc.StartDate != nil { + objectMap["startDate"] = pc.StartDate + } + if pc.EndDate != nil { + objectMap["endDate"] = pc.EndDate + } + if pc.KeyID != nil { + objectMap["keyId"] = pc.KeyID + } + if pc.Value != nil { + objectMap["value"] = pc.Value + } + if pc.CustomKeyIdentifier != nil { + objectMap["customKeyIdentifier"] = pc.CustomKeyIdentifier + } + for k, v := range pc.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PasswordCredential struct. +func (pc *PasswordCredential) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if pc.AdditionalProperties == nil { + pc.AdditionalProperties = make(map[string]interface{}) + } + pc.AdditionalProperties[k] = additionalProperties + } + case "startDate": + if v != nil { + var startDate date.Time + err = json.Unmarshal(*v, &startDate) + if err != nil { + return err + } + pc.StartDate = &startDate + } + case "endDate": + if v != nil { + var endDate date.Time + err = json.Unmarshal(*v, &endDate) + if err != nil { + return err + } + pc.EndDate = &endDate + } + case "keyId": + if v != nil { + var keyID string + err = json.Unmarshal(*v, &keyID) + if err != nil { + return err + } + pc.KeyID = &keyID + } + case "value": + if v != nil { + var value string + err = json.Unmarshal(*v, &value) + if err != nil { + return err + } + pc.Value = &value + } + case "customKeyIdentifier": + if v != nil { + var customKeyIdentifier []byte + err = json.Unmarshal(*v, &customKeyIdentifier) + if err != nil { + return err + } + pc.CustomKeyIdentifier = &customKeyIdentifier + } + } + } + + return nil +} + +// PasswordCredentialListResult passwordCredential list operation result. +type PasswordCredentialListResult struct { + autorest.Response `json:"-"` + // Value - A collection of PasswordCredentials. + Value *[]PasswordCredential `json:"value,omitempty"` +} + +// PasswordCredentialsUpdateParameters request parameters for a PasswordCredentials update operation. +type PasswordCredentialsUpdateParameters struct { + // Value - A collection of PasswordCredentials. + Value *[]PasswordCredential `json:"value,omitempty"` +} + +// PasswordProfile the password profile associated with a user. +type PasswordProfile struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // Password - Password + Password *string `json:"password,omitempty"` + // ForceChangePasswordNextLogin - Whether to force a password change on next login. + ForceChangePasswordNextLogin *bool `json:"forceChangePasswordNextLogin,omitempty"` +} + +// MarshalJSON is the custom marshaler for PasswordProfile. +func (pp PasswordProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pp.Password != nil { + objectMap["password"] = pp.Password + } + if pp.ForceChangePasswordNextLogin != nil { + objectMap["forceChangePasswordNextLogin"] = pp.ForceChangePasswordNextLogin + } + for k, v := range pp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PasswordProfile struct. +func (pp *PasswordProfile) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if pp.AdditionalProperties == nil { + pp.AdditionalProperties = make(map[string]interface{}) + } + pp.AdditionalProperties[k] = additionalProperties + } + case "password": + if v != nil { + var password string + err = json.Unmarshal(*v, &password) + if err != nil { + return err + } + pp.Password = &password + } + case "forceChangePasswordNextLogin": + if v != nil { + var forceChangePasswordNextLogin bool + err = json.Unmarshal(*v, &forceChangePasswordNextLogin) + if err != nil { + return err + } + pp.ForceChangePasswordNextLogin = &forceChangePasswordNextLogin + } + } + } + + return nil +} + +// PreAuthorizedApplication contains information about pre authorized client application. +type PreAuthorizedApplication struct { + // AppID - Represents the application id. + AppID *string `json:"appId,omitempty"` + // Permissions - Collection of required app permissions/entitlements from the resource application. + Permissions *[]PreAuthorizedApplicationPermission `json:"permissions,omitempty"` + // Extensions - Collection of extensions from the resource application. + Extensions *[]PreAuthorizedApplicationExtension `json:"extensions,omitempty"` +} + +// PreAuthorizedApplicationExtension representation of an app PreAuthorizedApplicationExtension required by +// a pre authorized client app. +type PreAuthorizedApplicationExtension struct { + // Conditions - The extension's conditions. + Conditions *[]string `json:"conditions,omitempty"` +} + +// PreAuthorizedApplicationPermission contains information about the pre-authorized permissions. +type PreAuthorizedApplicationPermission struct { + // DirectAccessGrant - Indicates whether the permission set is DirectAccess or impersonation. + DirectAccessGrant *bool `json:"directAccessGrant,omitempty"` + // AccessGrants - The list of permissions. + AccessGrants *[]string `json:"accessGrants,omitempty"` +} + +// RequiredResourceAccess specifies the set of OAuth 2.0 permission scopes and app roles under the +// specified resource that an application requires access to. The specified OAuth 2.0 permission scopes may +// be requested by client applications (through the requiredResourceAccess collection) when calling a +// resource application. The requiredResourceAccess property of the Application entity is a collection of +// RequiredResourceAccess. +type RequiredResourceAccess struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ResourceAccess - The list of OAuth2.0 permission scopes and app roles that the application requires from the specified resource. + ResourceAccess *[]ResourceAccess `json:"resourceAccess,omitempty"` + // ResourceAppID - The unique identifier for the resource that the application requires access to. This should be equal to the appId declared on the target resource application. + ResourceAppID *string `json:"resourceAppId,omitempty"` +} + +// MarshalJSON is the custom marshaler for RequiredResourceAccess. +func (rra RequiredResourceAccess) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rra.ResourceAccess != nil { + objectMap["resourceAccess"] = rra.ResourceAccess + } + if rra.ResourceAppID != nil { + objectMap["resourceAppId"] = rra.ResourceAppID + } + for k, v := range rra.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for RequiredResourceAccess struct. +func (rra *RequiredResourceAccess) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if rra.AdditionalProperties == nil { + rra.AdditionalProperties = make(map[string]interface{}) + } + rra.AdditionalProperties[k] = additionalProperties + } + case "resourceAccess": + if v != nil { + var resourceAccess []ResourceAccess + err = json.Unmarshal(*v, &resourceAccess) + if err != nil { + return err + } + rra.ResourceAccess = &resourceAccess + } + case "resourceAppId": + if v != nil { + var resourceAppID string + err = json.Unmarshal(*v, &resourceAppID) + if err != nil { + return err + } + rra.ResourceAppID = &resourceAppID + } + } + } + + return nil +} + +// ResourceAccess specifies an OAuth 2.0 permission scope or an app role that an application requires. The +// resourceAccess property of the RequiredResourceAccess type is a collection of ResourceAccess. +type ResourceAccess struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ID - The unique identifier for one of the OAuth2Permission or AppRole instances that the resource application exposes. + ID *string `json:"id,omitempty"` + // Type - Specifies whether the id property references an OAuth2Permission or an AppRole. Possible values are "scope" or "role". + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ResourceAccess. +func (ra ResourceAccess) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ra.ID != nil { + objectMap["id"] = ra.ID + } + if ra.Type != nil { + objectMap["type"] = ra.Type + } + for k, v := range ra.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ResourceAccess struct. +func (ra *ResourceAccess) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ra.AdditionalProperties == nil { + ra.AdditionalProperties = make(map[string]interface{}) + } + ra.AdditionalProperties[k] = additionalProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ra.ID = &ID + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ra.Type = &typeVar + } + } + } + + return nil +} + +// ServicePrincipal active Directory service principal information. +type ServicePrincipal struct { + autorest.Response `json:"-"` + // AccountEnabled - whether or not the service principal account is enabled + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // AlternativeNames - alternative names + AlternativeNames *[]string `json:"alternativeNames,omitempty"` + // AppDisplayName - READ-ONLY; The display name exposed by the associated application. + AppDisplayName *string `json:"appDisplayName,omitempty"` + // AppID - The application ID. + AppID *string `json:"appId,omitempty"` + // AppOwnerTenantID - READ-ONLY + AppOwnerTenantID *string `json:"appOwnerTenantId,omitempty"` + // AppRoleAssignmentRequired - Specifies whether an AppRoleAssignment to a user or group is required before Azure AD will issue a user or access token to the application. + AppRoleAssignmentRequired *bool `json:"appRoleAssignmentRequired,omitempty"` + // AppRoles - The collection of application roles that an application may declare. These roles can be assigned to users, groups or service principals. + AppRoles *[]AppRole `json:"appRoles,omitempty"` + // DisplayName - The display name of the service principal. + DisplayName *string `json:"displayName,omitempty"` + // ErrorURL - A URL provided by the author of the associated application to report errors when using the application. + ErrorURL *string `json:"errorUrl,omitempty"` + // Homepage - The URL to the homepage of the associated application. + Homepage *string `json:"homepage,omitempty"` + // KeyCredentials - The collection of key credentials associated with the service principal. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // LogoutURL - A URL provided by the author of the associated application to logout + LogoutURL *string `json:"logoutUrl,omitempty"` + // Oauth2Permissions - READ-ONLY; The OAuth 2.0 permissions exposed by the associated application. + Oauth2Permissions *[]OAuth2Permission `json:"oauth2Permissions,omitempty"` + // PasswordCredentials - The collection of password credentials associated with the service principal. + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // PreferredTokenSigningKeyThumbprint - The thumbprint of preferred certificate to sign the token + PreferredTokenSigningKeyThumbprint *string `json:"preferredTokenSigningKeyThumbprint,omitempty"` + // PublisherName - The publisher's name of the associated application + PublisherName *string `json:"publisherName,omitempty"` + // ReplyUrls - The URLs that user tokens are sent to for sign in with the associated application. The redirect URIs that the oAuth 2.0 authorization code and access tokens are sent to for the associated application. + ReplyUrls *[]string `json:"replyUrls,omitempty"` + // SamlMetadataURL - The URL to the SAML metadata of the associated application + SamlMetadataURL *string `json:"samlMetadataUrl,omitempty"` + // ServicePrincipalNames - A collection of service principal names. + ServicePrincipalNames *[]string `json:"servicePrincipalNames,omitempty"` + // ServicePrincipalType - the type of the service principal + ServicePrincipalType *string `json:"servicePrincipalType,omitempty"` + // Tags - Optional list of tags that you can apply to your service principals. Not nullable. + Tags *[]string `json:"tags,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectID - READ-ONLY; The object ID. + ObjectID *string `json:"objectId,omitempty"` + // DeletionTimestamp - READ-ONLY; The time at which the directory object was deleted. + DeletionTimestamp *date.Time `json:"deletionTimestamp,omitempty"` + // ObjectType - Possible values include: 'ObjectTypeDirectoryObject', 'ObjectTypeApplication', 'ObjectTypeGroup', 'ObjectTypeServicePrincipal', 'ObjectTypeUser' + ObjectType ObjectType `json:"objectType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServicePrincipal. +func (sp ServicePrincipal) MarshalJSON() ([]byte, error) { + sp.ObjectType = ObjectTypeServicePrincipal + objectMap := make(map[string]interface{}) + if sp.AccountEnabled != nil { + objectMap["accountEnabled"] = sp.AccountEnabled + } + if sp.AlternativeNames != nil { + objectMap["alternativeNames"] = sp.AlternativeNames + } + if sp.AppID != nil { + objectMap["appId"] = sp.AppID + } + if sp.AppRoleAssignmentRequired != nil { + objectMap["appRoleAssignmentRequired"] = sp.AppRoleAssignmentRequired + } + if sp.AppRoles != nil { + objectMap["appRoles"] = sp.AppRoles + } + if sp.DisplayName != nil { + objectMap["displayName"] = sp.DisplayName + } + if sp.ErrorURL != nil { + objectMap["errorUrl"] = sp.ErrorURL + } + if sp.Homepage != nil { + objectMap["homepage"] = sp.Homepage + } + if sp.KeyCredentials != nil { + objectMap["keyCredentials"] = sp.KeyCredentials + } + if sp.LogoutURL != nil { + objectMap["logoutUrl"] = sp.LogoutURL + } + if sp.PasswordCredentials != nil { + objectMap["passwordCredentials"] = sp.PasswordCredentials + } + if sp.PreferredTokenSigningKeyThumbprint != nil { + objectMap["preferredTokenSigningKeyThumbprint"] = sp.PreferredTokenSigningKeyThumbprint + } + if sp.PublisherName != nil { + objectMap["publisherName"] = sp.PublisherName + } + if sp.ReplyUrls != nil { + objectMap["replyUrls"] = sp.ReplyUrls + } + if sp.SamlMetadataURL != nil { + objectMap["samlMetadataUrl"] = sp.SamlMetadataURL + } + if sp.ServicePrincipalNames != nil { + objectMap["servicePrincipalNames"] = sp.ServicePrincipalNames + } + if sp.ServicePrincipalType != nil { + objectMap["servicePrincipalType"] = sp.ServicePrincipalType + } + if sp.Tags != nil { + objectMap["tags"] = sp.Tags + } + if sp.ObjectType != "" { + objectMap["objectType"] = sp.ObjectType + } + for k, v := range sp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// AsApplication is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsApplication() (*Application, bool) { + return nil, false +} + +// AsADGroup is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsADGroup() (*ADGroup, bool) { + return nil, false +} + +// AsServicePrincipal is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsServicePrincipal() (*ServicePrincipal, bool) { + return &sp, true +} + +// AsUser is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsUser() (*User, bool) { + return nil, false +} + +// AsDirectoryObject is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsDirectoryObject() (*DirectoryObject, bool) { + return nil, false +} + +// AsBasicDirectoryObject is the BasicDirectoryObject implementation for ServicePrincipal. +func (sp ServicePrincipal) AsBasicDirectoryObject() (BasicDirectoryObject, bool) { + return &sp, true +} + +// UnmarshalJSON is the custom unmarshaler for ServicePrincipal struct. +func (sp *ServicePrincipal) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "accountEnabled": + if v != nil { + var accountEnabled bool + err = json.Unmarshal(*v, &accountEnabled) + if err != nil { + return err + } + sp.AccountEnabled = &accountEnabled + } + case "alternativeNames": + if v != nil { + var alternativeNames []string + err = json.Unmarshal(*v, &alternativeNames) + if err != nil { + return err + } + sp.AlternativeNames = &alternativeNames + } + case "appDisplayName": + if v != nil { + var appDisplayName string + err = json.Unmarshal(*v, &appDisplayName) + if err != nil { + return err + } + sp.AppDisplayName = &appDisplayName + } + case "appId": + if v != nil { + var appID string + err = json.Unmarshal(*v, &appID) + if err != nil { + return err + } + sp.AppID = &appID + } + case "appOwnerTenantId": + if v != nil { + var appOwnerTenantID string + err = json.Unmarshal(*v, &appOwnerTenantID) + if err != nil { + return err + } + sp.AppOwnerTenantID = &appOwnerTenantID + } + case "appRoleAssignmentRequired": + if v != nil { + var appRoleAssignmentRequired bool + err = json.Unmarshal(*v, &appRoleAssignmentRequired) + if err != nil { + return err + } + sp.AppRoleAssignmentRequired = &appRoleAssignmentRequired + } + case "appRoles": + if v != nil { + var appRoles []AppRole + err = json.Unmarshal(*v, &appRoles) + if err != nil { + return err + } + sp.AppRoles = &appRoles + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + sp.DisplayName = &displayName + } + case "errorUrl": + if v != nil { + var errorURL string + err = json.Unmarshal(*v, &errorURL) + if err != nil { + return err + } + sp.ErrorURL = &errorURL + } + case "homepage": + if v != nil { + var homepage string + err = json.Unmarshal(*v, &homepage) + if err != nil { + return err + } + sp.Homepage = &homepage + } + case "keyCredentials": + if v != nil { + var keyCredentials []KeyCredential + err = json.Unmarshal(*v, &keyCredentials) + if err != nil { + return err + } + sp.KeyCredentials = &keyCredentials + } + case "logoutUrl": + if v != nil { + var logoutURL string + err = json.Unmarshal(*v, &logoutURL) + if err != nil { + return err + } + sp.LogoutURL = &logoutURL + } + case "oauth2Permissions": + if v != nil { + var oauth2Permissions []OAuth2Permission + err = json.Unmarshal(*v, &oauth2Permissions) + if err != nil { + return err + } + sp.Oauth2Permissions = &oauth2Permissions + } + case "passwordCredentials": + if v != nil { + var passwordCredentials []PasswordCredential + err = json.Unmarshal(*v, &passwordCredentials) + if err != nil { + return err + } + sp.PasswordCredentials = &passwordCredentials + } + case "preferredTokenSigningKeyThumbprint": + if v != nil { + var preferredTokenSigningKeyThumbprint string + err = json.Unmarshal(*v, &preferredTokenSigningKeyThumbprint) + if err != nil { + return err + } + sp.PreferredTokenSigningKeyThumbprint = &preferredTokenSigningKeyThumbprint + } + case "publisherName": + if v != nil { + var publisherName string + err = json.Unmarshal(*v, &publisherName) + if err != nil { + return err + } + sp.PublisherName = &publisherName + } + case "replyUrls": + if v != nil { + var replyUrls []string + err = json.Unmarshal(*v, &replyUrls) + if err != nil { + return err + } + sp.ReplyUrls = &replyUrls + } + case "samlMetadataUrl": + if v != nil { + var samlMetadataURL string + err = json.Unmarshal(*v, &samlMetadataURL) + if err != nil { + return err + } + sp.SamlMetadataURL = &samlMetadataURL + } + case "servicePrincipalNames": + if v != nil { + var servicePrincipalNames []string + err = json.Unmarshal(*v, &servicePrincipalNames) + if err != nil { + return err + } + sp.ServicePrincipalNames = &servicePrincipalNames + } + case "servicePrincipalType": + if v != nil { + var servicePrincipalType string + err = json.Unmarshal(*v, &servicePrincipalType) + if err != nil { + return err + } + sp.ServicePrincipalType = &servicePrincipalType + } + case "tags": + if v != nil { + var tags []string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sp.Tags = &tags + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if sp.AdditionalProperties == nil { + sp.AdditionalProperties = make(map[string]interface{}) + } + sp.AdditionalProperties[k] = additionalProperties + } + case "objectId": + if v != nil { + var objectID string + err = json.Unmarshal(*v, &objectID) + if err != nil { + return err + } + sp.ObjectID = &objectID + } + case "deletionTimestamp": + if v != nil { + var deletionTimestamp date.Time + err = json.Unmarshal(*v, &deletionTimestamp) + if err != nil { + return err + } + sp.DeletionTimestamp = &deletionTimestamp + } + case "objectType": + if v != nil { + var objectType ObjectType + err = json.Unmarshal(*v, &objectType) + if err != nil { + return err + } + sp.ObjectType = objectType + } + } + } + + return nil +} + +// ServicePrincipalBase active Directory service principal common properties shared among GET, POST and +// PATCH +type ServicePrincipalBase struct { + // AccountEnabled - whether or not the service principal account is enabled + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // AppRoleAssignmentRequired - Specifies whether an AppRoleAssignment to a user or group is required before Azure AD will issue a user or access token to the application. + AppRoleAssignmentRequired *bool `json:"appRoleAssignmentRequired,omitempty"` + // KeyCredentials - The collection of key credentials associated with the service principal. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // PasswordCredentials - The collection of password credentials associated with the service principal. + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // ServicePrincipalType - the type of the service principal + ServicePrincipalType *string `json:"servicePrincipalType,omitempty"` + // Tags - Optional list of tags that you can apply to your service principals. Not nullable. + Tags *[]string `json:"tags,omitempty"` +} + +// ServicePrincipalCreateParameters request parameters for creating a new service principal. +type ServicePrincipalCreateParameters struct { + // AppID - The application ID. + AppID *string `json:"appId,omitempty"` + // AccountEnabled - whether or not the service principal account is enabled + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // AppRoleAssignmentRequired - Specifies whether an AppRoleAssignment to a user or group is required before Azure AD will issue a user or access token to the application. + AppRoleAssignmentRequired *bool `json:"appRoleAssignmentRequired,omitempty"` + // KeyCredentials - The collection of key credentials associated with the service principal. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // PasswordCredentials - The collection of password credentials associated with the service principal. + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // ServicePrincipalType - the type of the service principal + ServicePrincipalType *string `json:"servicePrincipalType,omitempty"` + // Tags - Optional list of tags that you can apply to your service principals. Not nullable. + Tags *[]string `json:"tags,omitempty"` +} + +// ServicePrincipalListResult server response for get tenant service principals API call. +type ServicePrincipalListResult struct { + autorest.Response `json:"-"` + // Value - the list of service principals. + Value *[]ServicePrincipal `json:"value,omitempty"` + // OdataNextLink - the URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// ServicePrincipalListResultIterator provides access to a complete listing of ServicePrincipal values. +type ServicePrincipalListResultIterator struct { + i int + page ServicePrincipalListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ServicePrincipalListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ServicePrincipalListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ServicePrincipalListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ServicePrincipalListResultIterator) Response() ServicePrincipalListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ServicePrincipalListResultIterator) Value() ServicePrincipal { + if !iter.page.NotDone() { + return ServicePrincipal{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ServicePrincipalListResultIterator type. +func NewServicePrincipalListResultIterator(page ServicePrincipalListResultPage) ServicePrincipalListResultIterator { + return ServicePrincipalListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (splr ServicePrincipalListResult) IsEmpty() bool { + return splr.Value == nil || len(*splr.Value) == 0 +} + +// ServicePrincipalListResultPage contains a page of ServicePrincipal values. +type ServicePrincipalListResultPage struct { + fn func(context.Context, ServicePrincipalListResult) (ServicePrincipalListResult, error) + splr ServicePrincipalListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ServicePrincipalListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.splr) + if err != nil { + return err + } + page.splr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ServicePrincipalListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ServicePrincipalListResultPage) NotDone() bool { + return !page.splr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ServicePrincipalListResultPage) Response() ServicePrincipalListResult { + return page.splr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ServicePrincipalListResultPage) Values() []ServicePrincipal { + if page.splr.IsEmpty() { + return nil + } + return *page.splr.Value +} + +// Creates a new instance of the ServicePrincipalListResultPage type. +func NewServicePrincipalListResultPage(getNextPage func(context.Context, ServicePrincipalListResult) (ServicePrincipalListResult, error)) ServicePrincipalListResultPage { + return ServicePrincipalListResultPage{fn: getNextPage} +} + +// ServicePrincipalObjectResult service Principal Object Result. +type ServicePrincipalObjectResult struct { + autorest.Response `json:"-"` + // Value - The Object ID of the service principal with the specified application ID. + Value *string `json:"value,omitempty"` + // OdataMetadata - The URL representing edm equivalent. + OdataMetadata *string `json:"odata.metadata,omitempty"` +} + +// ServicePrincipalUpdateParameters request parameters for update an existing service principal. +type ServicePrincipalUpdateParameters struct { + // AccountEnabled - whether or not the service principal account is enabled + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // AppRoleAssignmentRequired - Specifies whether an AppRoleAssignment to a user or group is required before Azure AD will issue a user or access token to the application. + AppRoleAssignmentRequired *bool `json:"appRoleAssignmentRequired,omitempty"` + // KeyCredentials - The collection of key credentials associated with the service principal. + KeyCredentials *[]KeyCredential `json:"keyCredentials,omitempty"` + // PasswordCredentials - The collection of password credentials associated with the service principal. + PasswordCredentials *[]PasswordCredential `json:"passwordCredentials,omitempty"` + // ServicePrincipalType - the type of the service principal + ServicePrincipalType *string `json:"servicePrincipalType,omitempty"` + // Tags - Optional list of tags that you can apply to your service principals. Not nullable. + Tags *[]string `json:"tags,omitempty"` +} + +// SignInName contains information about a sign-in name of a local account user in an Azure Active +// Directory B2C tenant. +type SignInName struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // Type - A string value that can be used to classify user sign-in types in your directory, such as 'emailAddress' or 'userName'. + Type *string `json:"type,omitempty"` + // Value - The sign-in used by the local account. Must be unique across the company/tenant. For example, 'johnc@example.com'. + Value *string `json:"value,omitempty"` +} + +// MarshalJSON is the custom marshaler for SignInName. +func (sin SignInName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sin.Type != nil { + objectMap["type"] = sin.Type + } + if sin.Value != nil { + objectMap["value"] = sin.Value + } + for k, v := range sin.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SignInName struct. +func (sin *SignInName) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if sin.AdditionalProperties == nil { + sin.AdditionalProperties = make(map[string]interface{}) + } + sin.AdditionalProperties[k] = additionalProperties + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sin.Type = &typeVar + } + case "value": + if v != nil { + var value string + err = json.Unmarshal(*v, &value) + if err != nil { + return err + } + sin.Value = &value + } + } + } + + return nil +} + +// User active Directory user information. +type User struct { + autorest.Response `json:"-"` + // ImmutableID - This must be specified if you are using a federated domain for the user's userPrincipalName (UPN) property when creating a new user account. It is used to associate an on-premises Active Directory user account with their Azure AD user object. + ImmutableID *string `json:"immutableId,omitempty"` + // UsageLocation - A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: "US", "JP", and "GB". + UsageLocation *string `json:"usageLocation,omitempty"` + // GivenName - The given name for the user. + GivenName *string `json:"givenName,omitempty"` + // Surname - The user's surname (family name or last name). + Surname *string `json:"surname,omitempty"` + // UserType - A string value that can be used to classify user types in your directory, such as 'Member' and 'Guest'. Possible values include: 'Member', 'Guest' + UserType UserType `json:"userType,omitempty"` + // AccountEnabled - Whether the account is enabled. + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // DisplayName - The display name of the user. + DisplayName *string `json:"displayName,omitempty"` + // UserPrincipalName - The principal name of the user. + UserPrincipalName *string `json:"userPrincipalName,omitempty"` + // MailNickname - The mail alias for the user. + MailNickname *string `json:"mailNickname,omitempty"` + // Mail - The primary email address of the user. + Mail *string `json:"mail,omitempty"` + // SignInNames - The sign-in names of the user. + SignInNames *[]SignInName `json:"signInNames,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ObjectID - READ-ONLY; The object ID. + ObjectID *string `json:"objectId,omitempty"` + // DeletionTimestamp - READ-ONLY; The time at which the directory object was deleted. + DeletionTimestamp *date.Time `json:"deletionTimestamp,omitempty"` + // ObjectType - Possible values include: 'ObjectTypeDirectoryObject', 'ObjectTypeApplication', 'ObjectTypeGroup', 'ObjectTypeServicePrincipal', 'ObjectTypeUser' + ObjectType ObjectType `json:"objectType,omitempty"` +} + +// MarshalJSON is the custom marshaler for User. +func (u User) MarshalJSON() ([]byte, error) { + u.ObjectType = ObjectTypeUser + objectMap := make(map[string]interface{}) + if u.ImmutableID != nil { + objectMap["immutableId"] = u.ImmutableID + } + if u.UsageLocation != nil { + objectMap["usageLocation"] = u.UsageLocation + } + if u.GivenName != nil { + objectMap["givenName"] = u.GivenName + } + if u.Surname != nil { + objectMap["surname"] = u.Surname + } + if u.UserType != "" { + objectMap["userType"] = u.UserType + } + if u.AccountEnabled != nil { + objectMap["accountEnabled"] = u.AccountEnabled + } + if u.DisplayName != nil { + objectMap["displayName"] = u.DisplayName + } + if u.UserPrincipalName != nil { + objectMap["userPrincipalName"] = u.UserPrincipalName + } + if u.MailNickname != nil { + objectMap["mailNickname"] = u.MailNickname + } + if u.Mail != nil { + objectMap["mail"] = u.Mail + } + if u.SignInNames != nil { + objectMap["signInNames"] = u.SignInNames + } + if u.ObjectType != "" { + objectMap["objectType"] = u.ObjectType + } + for k, v := range u.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// AsApplication is the BasicDirectoryObject implementation for User. +func (u User) AsApplication() (*Application, bool) { + return nil, false +} + +// AsADGroup is the BasicDirectoryObject implementation for User. +func (u User) AsADGroup() (*ADGroup, bool) { + return nil, false +} + +// AsServicePrincipal is the BasicDirectoryObject implementation for User. +func (u User) AsServicePrincipal() (*ServicePrincipal, bool) { + return nil, false +} + +// AsUser is the BasicDirectoryObject implementation for User. +func (u User) AsUser() (*User, bool) { + return &u, true +} + +// AsDirectoryObject is the BasicDirectoryObject implementation for User. +func (u User) AsDirectoryObject() (*DirectoryObject, bool) { + return nil, false +} + +// AsBasicDirectoryObject is the BasicDirectoryObject implementation for User. +func (u User) AsBasicDirectoryObject() (BasicDirectoryObject, bool) { + return &u, true +} + +// UnmarshalJSON is the custom unmarshaler for User struct. +func (u *User) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "immutableId": + if v != nil { + var immutableID string + err = json.Unmarshal(*v, &immutableID) + if err != nil { + return err + } + u.ImmutableID = &immutableID + } + case "usageLocation": + if v != nil { + var usageLocation string + err = json.Unmarshal(*v, &usageLocation) + if err != nil { + return err + } + u.UsageLocation = &usageLocation + } + case "givenName": + if v != nil { + var givenName string + err = json.Unmarshal(*v, &givenName) + if err != nil { + return err + } + u.GivenName = &givenName + } + case "surname": + if v != nil { + var surname string + err = json.Unmarshal(*v, &surname) + if err != nil { + return err + } + u.Surname = &surname + } + case "userType": + if v != nil { + var userType UserType + err = json.Unmarshal(*v, &userType) + if err != nil { + return err + } + u.UserType = userType + } + case "accountEnabled": + if v != nil { + var accountEnabled bool + err = json.Unmarshal(*v, &accountEnabled) + if err != nil { + return err + } + u.AccountEnabled = &accountEnabled + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + u.DisplayName = &displayName + } + case "userPrincipalName": + if v != nil { + var userPrincipalName string + err = json.Unmarshal(*v, &userPrincipalName) + if err != nil { + return err + } + u.UserPrincipalName = &userPrincipalName + } + case "mailNickname": + if v != nil { + var mailNickname string + err = json.Unmarshal(*v, &mailNickname) + if err != nil { + return err + } + u.MailNickname = &mailNickname + } + case "mail": + if v != nil { + var mailVar string + err = json.Unmarshal(*v, &mailVar) + if err != nil { + return err + } + u.Mail = &mailVar + } + case "signInNames": + if v != nil { + var signInNames []SignInName + err = json.Unmarshal(*v, &signInNames) + if err != nil { + return err + } + u.SignInNames = &signInNames + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if u.AdditionalProperties == nil { + u.AdditionalProperties = make(map[string]interface{}) + } + u.AdditionalProperties[k] = additionalProperties + } + case "objectId": + if v != nil { + var objectID string + err = json.Unmarshal(*v, &objectID) + if err != nil { + return err + } + u.ObjectID = &objectID + } + case "deletionTimestamp": + if v != nil { + var deletionTimestamp date.Time + err = json.Unmarshal(*v, &deletionTimestamp) + if err != nil { + return err + } + u.DeletionTimestamp = &deletionTimestamp + } + case "objectType": + if v != nil { + var objectType ObjectType + err = json.Unmarshal(*v, &objectType) + if err != nil { + return err + } + u.ObjectType = objectType + } + } + } + + return nil +} + +// UserBase ... +type UserBase struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ImmutableID - This must be specified if you are using a federated domain for the user's userPrincipalName (UPN) property when creating a new user account. It is used to associate an on-premises Active Directory user account with their Azure AD user object. + ImmutableID *string `json:"immutableId,omitempty"` + // UsageLocation - A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: "US", "JP", and "GB". + UsageLocation *string `json:"usageLocation,omitempty"` + // GivenName - The given name for the user. + GivenName *string `json:"givenName,omitempty"` + // Surname - The user's surname (family name or last name). + Surname *string `json:"surname,omitempty"` + // UserType - A string value that can be used to classify user types in your directory, such as 'Member' and 'Guest'. Possible values include: 'Member', 'Guest' + UserType UserType `json:"userType,omitempty"` +} + +// MarshalJSON is the custom marshaler for UserBase. +func (ub UserBase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ub.ImmutableID != nil { + objectMap["immutableId"] = ub.ImmutableID + } + if ub.UsageLocation != nil { + objectMap["usageLocation"] = ub.UsageLocation + } + if ub.GivenName != nil { + objectMap["givenName"] = ub.GivenName + } + if ub.Surname != nil { + objectMap["surname"] = ub.Surname + } + if ub.UserType != "" { + objectMap["userType"] = ub.UserType + } + for k, v := range ub.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for UserBase struct. +func (ub *UserBase) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ub.AdditionalProperties == nil { + ub.AdditionalProperties = make(map[string]interface{}) + } + ub.AdditionalProperties[k] = additionalProperties + } + case "immutableId": + if v != nil { + var immutableID string + err = json.Unmarshal(*v, &immutableID) + if err != nil { + return err + } + ub.ImmutableID = &immutableID + } + case "usageLocation": + if v != nil { + var usageLocation string + err = json.Unmarshal(*v, &usageLocation) + if err != nil { + return err + } + ub.UsageLocation = &usageLocation + } + case "givenName": + if v != nil { + var givenName string + err = json.Unmarshal(*v, &givenName) + if err != nil { + return err + } + ub.GivenName = &givenName + } + case "surname": + if v != nil { + var surname string + err = json.Unmarshal(*v, &surname) + if err != nil { + return err + } + ub.Surname = &surname + } + case "userType": + if v != nil { + var userType UserType + err = json.Unmarshal(*v, &userType) + if err != nil { + return err + } + ub.UserType = userType + } + } + } + + return nil +} + +// UserCreateParameters request parameters for creating a new work or school account user. +type UserCreateParameters struct { + // AccountEnabled - Whether the account is enabled. + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // DisplayName - The display name of the user. + DisplayName *string `json:"displayName,omitempty"` + // PasswordProfile - Password Profile + PasswordProfile *PasswordProfile `json:"passwordProfile,omitempty"` + // UserPrincipalName - The user principal name (someuser@contoso.com). It must contain one of the verified domains for the tenant. + UserPrincipalName *string `json:"userPrincipalName,omitempty"` + // MailNickname - The mail alias for the user. + MailNickname *string `json:"mailNickname,omitempty"` + // Mail - The primary email address of the user. + Mail *string `json:"mail,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ImmutableID - This must be specified if you are using a federated domain for the user's userPrincipalName (UPN) property when creating a new user account. It is used to associate an on-premises Active Directory user account with their Azure AD user object. + ImmutableID *string `json:"immutableId,omitempty"` + // UsageLocation - A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: "US", "JP", and "GB". + UsageLocation *string `json:"usageLocation,omitempty"` + // GivenName - The given name for the user. + GivenName *string `json:"givenName,omitempty"` + // Surname - The user's surname (family name or last name). + Surname *string `json:"surname,omitempty"` + // UserType - A string value that can be used to classify user types in your directory, such as 'Member' and 'Guest'. Possible values include: 'Member', 'Guest' + UserType UserType `json:"userType,omitempty"` +} + +// MarshalJSON is the custom marshaler for UserCreateParameters. +func (ucp UserCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ucp.AccountEnabled != nil { + objectMap["accountEnabled"] = ucp.AccountEnabled + } + if ucp.DisplayName != nil { + objectMap["displayName"] = ucp.DisplayName + } + if ucp.PasswordProfile != nil { + objectMap["passwordProfile"] = ucp.PasswordProfile + } + if ucp.UserPrincipalName != nil { + objectMap["userPrincipalName"] = ucp.UserPrincipalName + } + if ucp.MailNickname != nil { + objectMap["mailNickname"] = ucp.MailNickname + } + if ucp.Mail != nil { + objectMap["mail"] = ucp.Mail + } + if ucp.ImmutableID != nil { + objectMap["immutableId"] = ucp.ImmutableID + } + if ucp.UsageLocation != nil { + objectMap["usageLocation"] = ucp.UsageLocation + } + if ucp.GivenName != nil { + objectMap["givenName"] = ucp.GivenName + } + if ucp.Surname != nil { + objectMap["surname"] = ucp.Surname + } + if ucp.UserType != "" { + objectMap["userType"] = ucp.UserType + } + for k, v := range ucp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for UserCreateParameters struct. +func (ucp *UserCreateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "accountEnabled": + if v != nil { + var accountEnabled bool + err = json.Unmarshal(*v, &accountEnabled) + if err != nil { + return err + } + ucp.AccountEnabled = &accountEnabled + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + ucp.DisplayName = &displayName + } + case "passwordProfile": + if v != nil { + var passwordProfile PasswordProfile + err = json.Unmarshal(*v, &passwordProfile) + if err != nil { + return err + } + ucp.PasswordProfile = &passwordProfile + } + case "userPrincipalName": + if v != nil { + var userPrincipalName string + err = json.Unmarshal(*v, &userPrincipalName) + if err != nil { + return err + } + ucp.UserPrincipalName = &userPrincipalName + } + case "mailNickname": + if v != nil { + var mailNickname string + err = json.Unmarshal(*v, &mailNickname) + if err != nil { + return err + } + ucp.MailNickname = &mailNickname + } + case "mail": + if v != nil { + var mailVar string + err = json.Unmarshal(*v, &mailVar) + if err != nil { + return err + } + ucp.Mail = &mailVar + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ucp.AdditionalProperties == nil { + ucp.AdditionalProperties = make(map[string]interface{}) + } + ucp.AdditionalProperties[k] = additionalProperties + } + case "immutableId": + if v != nil { + var immutableID string + err = json.Unmarshal(*v, &immutableID) + if err != nil { + return err + } + ucp.ImmutableID = &immutableID + } + case "usageLocation": + if v != nil { + var usageLocation string + err = json.Unmarshal(*v, &usageLocation) + if err != nil { + return err + } + ucp.UsageLocation = &usageLocation + } + case "givenName": + if v != nil { + var givenName string + err = json.Unmarshal(*v, &givenName) + if err != nil { + return err + } + ucp.GivenName = &givenName + } + case "surname": + if v != nil { + var surname string + err = json.Unmarshal(*v, &surname) + if err != nil { + return err + } + ucp.Surname = &surname + } + case "userType": + if v != nil { + var userType UserType + err = json.Unmarshal(*v, &userType) + if err != nil { + return err + } + ucp.UserType = userType + } + } + } + + return nil +} + +// UserGetMemberGroupsParameters request parameters for GetMemberGroups API call. +type UserGetMemberGroupsParameters struct { + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // SecurityEnabledOnly - If true, only membership in security-enabled groups should be checked. Otherwise, membership in all groups should be checked. + SecurityEnabledOnly *bool `json:"securityEnabledOnly,omitempty"` +} + +// MarshalJSON is the custom marshaler for UserGetMemberGroupsParameters. +func (ugmgp UserGetMemberGroupsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ugmgp.SecurityEnabledOnly != nil { + objectMap["securityEnabledOnly"] = ugmgp.SecurityEnabledOnly + } + for k, v := range ugmgp.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for UserGetMemberGroupsParameters struct. +func (ugmgp *UserGetMemberGroupsParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if ugmgp.AdditionalProperties == nil { + ugmgp.AdditionalProperties = make(map[string]interface{}) + } + ugmgp.AdditionalProperties[k] = additionalProperties + } + case "securityEnabledOnly": + if v != nil { + var securityEnabledOnly bool + err = json.Unmarshal(*v, &securityEnabledOnly) + if err != nil { + return err + } + ugmgp.SecurityEnabledOnly = &securityEnabledOnly + } + } + } + + return nil +} + +// UserGetMemberGroupsResult server response for GetMemberGroups API call. +type UserGetMemberGroupsResult struct { + autorest.Response `json:"-"` + // Value - A collection of group IDs of which the user is a member. + Value *[]string `json:"value,omitempty"` +} + +// UserListResult server response for Get tenant users API call. +type UserListResult struct { + autorest.Response `json:"-"` + // Value - the list of users. + Value *[]User `json:"value,omitempty"` + // OdataNextLink - The URL to get the next set of results. + OdataNextLink *string `json:"odata.nextLink,omitempty"` +} + +// UserListResultIterator provides access to a complete listing of User values. +type UserListResultIterator struct { + i int + page UserListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *UserListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UserListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *UserListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter UserListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter UserListResultIterator) Response() UserListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter UserListResultIterator) Value() User { + if !iter.page.NotDone() { + return User{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the UserListResultIterator type. +func NewUserListResultIterator(page UserListResultPage) UserListResultIterator { + return UserListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ulr UserListResult) IsEmpty() bool { + return ulr.Value == nil || len(*ulr.Value) == 0 +} + +// UserListResultPage contains a page of User values. +type UserListResultPage struct { + fn func(context.Context, UserListResult) (UserListResult, error) + ulr UserListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *UserListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UserListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.ulr) + if err != nil { + return err + } + page.ulr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *UserListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page UserListResultPage) NotDone() bool { + return !page.ulr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page UserListResultPage) Response() UserListResult { + return page.ulr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page UserListResultPage) Values() []User { + if page.ulr.IsEmpty() { + return nil + } + return *page.ulr.Value +} + +// Creates a new instance of the UserListResultPage type. +func NewUserListResultPage(getNextPage func(context.Context, UserListResult) (UserListResult, error)) UserListResultPage { + return UserListResultPage{fn: getNextPage} +} + +// UserUpdateParameters request parameters for updating an existing work or school account user. +type UserUpdateParameters struct { + // AccountEnabled - Whether the account is enabled. + AccountEnabled *bool `json:"accountEnabled,omitempty"` + // DisplayName - The display name of the user. + DisplayName *string `json:"displayName,omitempty"` + // PasswordProfile - The password profile of the user. + PasswordProfile *PasswordProfile `json:"passwordProfile,omitempty"` + // UserPrincipalName - The user principal name (someuser@contoso.com). It must contain one of the verified domains for the tenant. + UserPrincipalName *string `json:"userPrincipalName,omitempty"` + // MailNickname - The mail alias for the user. + MailNickname *string `json:"mailNickname,omitempty"` + // AdditionalProperties - Unmatched properties from the message are deserialized this collection + AdditionalProperties map[string]interface{} `json:""` + // ImmutableID - This must be specified if you are using a federated domain for the user's userPrincipalName (UPN) property when creating a new user account. It is used to associate an on-premises Active Directory user account with their Azure AD user object. + ImmutableID *string `json:"immutableId,omitempty"` + // UsageLocation - A two letter country code (ISO standard 3166). Required for users that will be assigned licenses due to legal requirement to check for availability of services in countries. Examples include: "US", "JP", and "GB". + UsageLocation *string `json:"usageLocation,omitempty"` + // GivenName - The given name for the user. + GivenName *string `json:"givenName,omitempty"` + // Surname - The user's surname (family name or last name). + Surname *string `json:"surname,omitempty"` + // UserType - A string value that can be used to classify user types in your directory, such as 'Member' and 'Guest'. Possible values include: 'Member', 'Guest' + UserType UserType `json:"userType,omitempty"` +} + +// MarshalJSON is the custom marshaler for UserUpdateParameters. +func (uup UserUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if uup.AccountEnabled != nil { + objectMap["accountEnabled"] = uup.AccountEnabled + } + if uup.DisplayName != nil { + objectMap["displayName"] = uup.DisplayName + } + if uup.PasswordProfile != nil { + objectMap["passwordProfile"] = uup.PasswordProfile + } + if uup.UserPrincipalName != nil { + objectMap["userPrincipalName"] = uup.UserPrincipalName + } + if uup.MailNickname != nil { + objectMap["mailNickname"] = uup.MailNickname + } + if uup.ImmutableID != nil { + objectMap["immutableId"] = uup.ImmutableID + } + if uup.UsageLocation != nil { + objectMap["usageLocation"] = uup.UsageLocation + } + if uup.GivenName != nil { + objectMap["givenName"] = uup.GivenName + } + if uup.Surname != nil { + objectMap["surname"] = uup.Surname + } + if uup.UserType != "" { + objectMap["userType"] = uup.UserType + } + for k, v := range uup.AdditionalProperties { + objectMap[k] = v + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for UserUpdateParameters struct. +func (uup *UserUpdateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "accountEnabled": + if v != nil { + var accountEnabled bool + err = json.Unmarshal(*v, &accountEnabled) + if err != nil { + return err + } + uup.AccountEnabled = &accountEnabled + } + case "displayName": + if v != nil { + var displayName string + err = json.Unmarshal(*v, &displayName) + if err != nil { + return err + } + uup.DisplayName = &displayName + } + case "passwordProfile": + if v != nil { + var passwordProfile PasswordProfile + err = json.Unmarshal(*v, &passwordProfile) + if err != nil { + return err + } + uup.PasswordProfile = &passwordProfile + } + case "userPrincipalName": + if v != nil { + var userPrincipalName string + err = json.Unmarshal(*v, &userPrincipalName) + if err != nil { + return err + } + uup.UserPrincipalName = &userPrincipalName + } + case "mailNickname": + if v != nil { + var mailNickname string + err = json.Unmarshal(*v, &mailNickname) + if err != nil { + return err + } + uup.MailNickname = &mailNickname + } + default: + if v != nil { + var additionalProperties interface{} + err = json.Unmarshal(*v, &additionalProperties) + if err != nil { + return err + } + if uup.AdditionalProperties == nil { + uup.AdditionalProperties = make(map[string]interface{}) + } + uup.AdditionalProperties[k] = additionalProperties + } + case "immutableId": + if v != nil { + var immutableID string + err = json.Unmarshal(*v, &immutableID) + if err != nil { + return err + } + uup.ImmutableID = &immutableID + } + case "usageLocation": + if v != nil { + var usageLocation string + err = json.Unmarshal(*v, &usageLocation) + if err != nil { + return err + } + uup.UsageLocation = &usageLocation + } + case "givenName": + if v != nil { + var givenName string + err = json.Unmarshal(*v, &givenName) + if err != nil { + return err + } + uup.GivenName = &givenName + } + case "surname": + if v != nil { + var surname string + err = json.Unmarshal(*v, &surname) + if err != nil { + return err + } + uup.Surname = &surname + } + case "userType": + if v != nil { + var userType UserType + err = json.Unmarshal(*v, &userType) + if err != nil { + return err + } + uup.UserType = userType + } + } + } + + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/oauth2permissiongrant.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/oauth2permissiongrant.go new file mode 100644 index 000000000..04ddbb3e8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/oauth2permissiongrant.go @@ -0,0 +1,369 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// OAuth2PermissionGrantClient is the the Graph RBAC Management Client +type OAuth2PermissionGrantClient struct { + BaseClient +} + +// NewOAuth2PermissionGrantClient creates an instance of the OAuth2PermissionGrantClient client. +func NewOAuth2PermissionGrantClient(tenantID string) OAuth2PermissionGrantClient { + return NewOAuth2PermissionGrantClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewOAuth2PermissionGrantClientWithBaseURI creates an instance of the OAuth2PermissionGrantClient client. +func NewOAuth2PermissionGrantClientWithBaseURI(baseURI string, tenantID string) OAuth2PermissionGrantClient { + return OAuth2PermissionGrantClient{NewWithBaseURI(baseURI, tenantID)} +} + +// Create grants OAuth2 permissions for the relevant resource Ids of an app. +// Parameters: +// body - the relevant app Service Principal Object Id and the Service Principal Object Id you want to grant. +func (client OAuth2PermissionGrantClient) Create(ctx context.Context, body *OAuth2PermissionGrant) (result OAuth2PermissionGrant, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantClient.Create") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreatePreparer(ctx, body) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client OAuth2PermissionGrantClient) CreatePreparer(ctx context.Context, body *OAuth2PermissionGrant) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/oauth2PermissionGrants", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if body != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(body)) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client OAuth2PermissionGrantClient) CreateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client OAuth2PermissionGrantClient) CreateResponder(resp *http.Response) (result OAuth2PermissionGrant, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a OAuth2 permission grant for the relevant resource Ids of an app. +// Parameters: +// objectID - the object ID of a permission grant. +func (client OAuth2PermissionGrantClient) Delete(ctx context.Context, objectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client OAuth2PermissionGrantClient) DeletePreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/oauth2PermissionGrants/{objectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client OAuth2PermissionGrantClient) DeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client OAuth2PermissionGrantClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// List queries OAuth2 permissions grants for the relevant SP ObjectId of an app. +// Parameters: +// filter - this is the Service Principal ObjectId associated with the app +func (client OAuth2PermissionGrantClient) List(ctx context.Context, filter string) (result OAuth2PermissionGrantListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantClient.List") + defer func() { + sc := -1 + if result.oa2pglr.Response.Response != nil { + sc = result.oa2pglr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult OAuth2PermissionGrantListResult) (OAuth2PermissionGrantListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return OAuth2PermissionGrantListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.oa2pglr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "List", resp, "Failure sending request") + return + } + + result.oa2pglr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OAuth2PermissionGrantClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/oauth2PermissionGrants", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OAuth2PermissionGrantClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OAuth2PermissionGrantClient) ListResponder(resp *http.Response) (result OAuth2PermissionGrantListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OAuth2PermissionGrantClient) ListComplete(ctx context.Context, filter string) (result OAuth2PermissionGrantListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListNext gets the next page of OAuth2 permission grants +// Parameters: +// nextLink - next link for the list operation. +func (client OAuth2PermissionGrantClient) ListNext(ctx context.Context, nextLink string) (result OAuth2PermissionGrantListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OAuth2PermissionGrantClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.OAuth2PermissionGrantClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client OAuth2PermissionGrantClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client OAuth2PermissionGrantClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client OAuth2PermissionGrantClient) ListNextResponder(resp *http.Response) (result OAuth2PermissionGrantListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/objects.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/objects.go new file mode 100644 index 000000000..3f6ca5c4b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/objects.go @@ -0,0 +1,216 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ObjectsClient is the the Graph RBAC Management Client +type ObjectsClient struct { + BaseClient +} + +// NewObjectsClient creates an instance of the ObjectsClient client. +func NewObjectsClient(tenantID string) ObjectsClient { + return NewObjectsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewObjectsClientWithBaseURI creates an instance of the ObjectsClient client. +func NewObjectsClientWithBaseURI(baseURI string, tenantID string) ObjectsClient { + return ObjectsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// GetObjectsByObjectIds gets the directory objects specified in a list of object IDs. You can also specify which +// resource collections (users, groups, etc.) should be searched by specifying the optional types parameter. +// Parameters: +// parameters - objects filtering parameters. +func (client ObjectsClient) GetObjectsByObjectIds(ctx context.Context, parameters GetObjectsParameters) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ObjectsClient.GetObjectsByObjectIds") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult DirectoryObjectListResult) (DirectoryObjectListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return DirectoryObjectListResult{}, nil + } + return client.GetObjectsByObjectIdsNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.GetObjectsByObjectIdsPreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIds", nil, "Failure preparing request") + return + } + + resp, err := client.GetObjectsByObjectIdsSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIds", resp, "Failure sending request") + return + } + + result.dolr, err = client.GetObjectsByObjectIdsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIds", resp, "Failure responding to request") + } + + return +} + +// GetObjectsByObjectIdsPreparer prepares the GetObjectsByObjectIds request. +func (client ObjectsClient) GetObjectsByObjectIdsPreparer(ctx context.Context, parameters GetObjectsParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/getObjectsByObjectIds", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetObjectsByObjectIdsSender sends the GetObjectsByObjectIds request. The method will close the +// http.Response Body if it receives an error. +func (client ObjectsClient) GetObjectsByObjectIdsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetObjectsByObjectIdsResponder handles the response to the GetObjectsByObjectIds request. The method always +// closes the http.Response Body. +func (client ObjectsClient) GetObjectsByObjectIdsResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetObjectsByObjectIdsComplete enumerates all values, automatically crossing page boundaries as required. +func (client ObjectsClient) GetObjectsByObjectIdsComplete(ctx context.Context, parameters GetObjectsParameters) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ObjectsClient.GetObjectsByObjectIds") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.GetObjectsByObjectIds(ctx, parameters) + return +} + +// GetObjectsByObjectIdsNext gets AD group membership for the specified AD object IDs. +// Parameters: +// nextLink - next link for the list operation. +func (client ObjectsClient) GetObjectsByObjectIdsNext(ctx context.Context, nextLink string) (result DirectoryObjectListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ObjectsClient.GetObjectsByObjectIdsNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetObjectsByObjectIdsNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIdsNext", nil, "Failure preparing request") + return + } + + resp, err := client.GetObjectsByObjectIdsNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIdsNext", resp, "Failure sending request") + return + } + + result, err = client.GetObjectsByObjectIdsNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ObjectsClient", "GetObjectsByObjectIdsNext", resp, "Failure responding to request") + } + + return +} + +// GetObjectsByObjectIdsNextPreparer prepares the GetObjectsByObjectIdsNext request. +func (client ObjectsClient) GetObjectsByObjectIdsNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetObjectsByObjectIdsNextSender sends the GetObjectsByObjectIdsNext request. The method will close the +// http.Response Body if it receives an error. +func (client ObjectsClient) GetObjectsByObjectIdsNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetObjectsByObjectIdsNextResponder handles the response to the GetObjectsByObjectIdsNext request. The method always +// closes the http.Response Body. +func (client ObjectsClient) GetObjectsByObjectIdsNextResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/serviceprincipals.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/serviceprincipals.go new file mode 100644 index 000000000..45099830b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/serviceprincipals.go @@ -0,0 +1,942 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ServicePrincipalsClient is the the Graph RBAC Management Client +type ServicePrincipalsClient struct { + BaseClient +} + +// NewServicePrincipalsClient creates an instance of the ServicePrincipalsClient client. +func NewServicePrincipalsClient(tenantID string) ServicePrincipalsClient { + return NewServicePrincipalsClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewServicePrincipalsClientWithBaseURI creates an instance of the ServicePrincipalsClient client. +func NewServicePrincipalsClientWithBaseURI(baseURI string, tenantID string) ServicePrincipalsClient { + return ServicePrincipalsClient{NewWithBaseURI(baseURI, tenantID)} +} + +// Create creates a service principal in the directory. +// Parameters: +// parameters - parameters to create a service principal. +func (client ServicePrincipalsClient) Create(ctx context.Context, parameters ServicePrincipalCreateParameters) (result ServicePrincipal, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.Create") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.AppID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.ServicePrincipalsClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ServicePrincipalsClient) CreatePreparer(ctx context.Context, parameters ServicePrincipalCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) CreateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) CreateResponder(resp *http.Response) (result ServicePrincipal, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a service principal from the directory. +// Parameters: +// objectID - the object ID of the service principal to delete. +func (client ServicePrincipalsClient) Delete(ctx context.Context, objectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServicePrincipalsClient) DeletePreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) DeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets service principal information from the directory. Query by objectId or pass a filter to query by appId +// Parameters: +// objectID - the object ID of the service principal to get. +func (client ServicePrincipalsClient) Get(ctx context.Context, objectID string) (result ServicePrincipal, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServicePrincipalsClient) GetPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) GetResponder(resp *http.Response) (result ServicePrincipal, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets a list of service principals from the current tenant. +// Parameters: +// filter - the filter to apply to the operation. +func (client ServicePrincipalsClient) List(ctx context.Context, filter string) (result ServicePrincipalListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.List") + defer func() { + sc := -1 + if result.splr.Response.Response != nil { + sc = result.splr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult ServicePrincipalListResult) (ServicePrincipalListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return ServicePrincipalListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.splr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "List", resp, "Failure sending request") + return + } + + result.splr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServicePrincipalsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) ListResponder(resp *http.Response) (result ServicePrincipalListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServicePrincipalsClient) ListComplete(ctx context.Context, filter string) (result ServicePrincipalListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListKeyCredentials get the keyCredentials associated with the specified service principal. +// Parameters: +// objectID - the object ID of the service principal for which to get keyCredentials. +func (client ServicePrincipalsClient) ListKeyCredentials(ctx context.Context, objectID string) (result KeyCredentialListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.ListKeyCredentials") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListKeyCredentialsPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListKeyCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeyCredentialsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListKeyCredentials", resp, "Failure sending request") + return + } + + result, err = client.ListKeyCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListKeyCredentials", resp, "Failure responding to request") + } + + return +} + +// ListKeyCredentialsPreparer prepares the ListKeyCredentials request. +func (client ServicePrincipalsClient) ListKeyCredentialsPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}/keyCredentials", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeyCredentialsSender sends the ListKeyCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) ListKeyCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListKeyCredentialsResponder handles the response to the ListKeyCredentials request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) ListKeyCredentialsResponder(resp *http.Response) (result KeyCredentialListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNext gets a list of service principals from the current tenant. +// Parameters: +// nextLink - next link for the list operation. +func (client ServicePrincipalsClient) ListNext(ctx context.Context, nextLink string) (result ServicePrincipalListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client ServicePrincipalsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) ListNextResponder(resp *http.Response) (result ServicePrincipalListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOwners the owners are a set of non-admin users who are allowed to modify this object. +// Parameters: +// objectID - the object ID of the service principal for which to get owners. +func (client ServicePrincipalsClient) ListOwners(ctx context.Context, objectID string) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.ListOwners") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listOwnersNextResults + req, err := client.ListOwnersPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListOwners", nil, "Failure preparing request") + return + } + + resp, err := client.ListOwnersSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListOwners", resp, "Failure sending request") + return + } + + result.dolr, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListOwners", resp, "Failure responding to request") + } + + return +} + +// ListOwnersPreparer prepares the ListOwners request. +func (client ServicePrincipalsClient) ListOwnersPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}/owners", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOwnersSender sends the ListOwners request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) ListOwnersSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListOwnersResponder handles the response to the ListOwners request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) ListOwnersResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listOwnersNextResults retrieves the next set of results, if any. +func (client ServicePrincipalsClient) listOwnersNextResults(ctx context.Context, lastResults DirectoryObjectListResult) (result DirectoryObjectListResult, err error) { + req, err := lastResults.directoryObjectListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "listOwnersNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListOwnersSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "listOwnersNextResults", resp, "Failure sending next results request") + } + result, err = client.ListOwnersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "listOwnersNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListOwnersComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServicePrincipalsClient) ListOwnersComplete(ctx context.Context, objectID string) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.ListOwners") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListOwners(ctx, objectID) + return +} + +// ListPasswordCredentials gets the passwordCredentials associated with a service principal. +// Parameters: +// objectID - the object ID of the service principal. +func (client ServicePrincipalsClient) ListPasswordCredentials(ctx context.Context, objectID string) (result PasswordCredentialListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.ListPasswordCredentials") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPasswordCredentialsPreparer(ctx, objectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListPasswordCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.ListPasswordCredentialsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListPasswordCredentials", resp, "Failure sending request") + return + } + + result, err = client.ListPasswordCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "ListPasswordCredentials", resp, "Failure responding to request") + } + + return +} + +// ListPasswordCredentialsPreparer prepares the ListPasswordCredentials request. +func (client ServicePrincipalsClient) ListPasswordCredentialsPreparer(ctx context.Context, objectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}/passwordCredentials", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListPasswordCredentialsSender sends the ListPasswordCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) ListPasswordCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListPasswordCredentialsResponder handles the response to the ListPasswordCredentials request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) ListPasswordCredentialsResponder(resp *http.Response) (result PasswordCredentialListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a service principal in the directory. +// Parameters: +// objectID - the object ID of the service principal to delete. +// parameters - parameters to update a service principal. +func (client ServicePrincipalsClient) Update(ctx context.Context, objectID string, parameters ServicePrincipalUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.Update") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ServicePrincipalsClient) UpdatePreparer(ctx context.Context, objectID string, parameters ServicePrincipalUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) UpdateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// UpdateKeyCredentials update the keyCredentials associated with a service principal. +// Parameters: +// objectID - the object ID for which to get service principal information. +// parameters - parameters to update the keyCredentials of an existing service principal. +func (client ServicePrincipalsClient) UpdateKeyCredentials(ctx context.Context, objectID string, parameters KeyCredentialsUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.UpdateKeyCredentials") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdateKeyCredentialsPreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdateKeyCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateKeyCredentialsSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdateKeyCredentials", resp, "Failure sending request") + return + } + + result, err = client.UpdateKeyCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdateKeyCredentials", resp, "Failure responding to request") + } + + return +} + +// UpdateKeyCredentialsPreparer prepares the UpdateKeyCredentials request. +func (client ServicePrincipalsClient) UpdateKeyCredentialsPreparer(ctx context.Context, objectID string, parameters KeyCredentialsUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}/keyCredentials", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateKeyCredentialsSender sends the UpdateKeyCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) UpdateKeyCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdateKeyCredentialsResponder handles the response to the UpdateKeyCredentials request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) UpdateKeyCredentialsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// UpdatePasswordCredentials updates the passwordCredentials associated with a service principal. +// Parameters: +// objectID - the object ID of the service principal. +// parameters - parameters to update the passwordCredentials of an existing service principal. +func (client ServicePrincipalsClient) UpdatePasswordCredentials(ctx context.Context, objectID string, parameters PasswordCredentialsUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicePrincipalsClient.UpdatePasswordCredentials") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePasswordCredentialsPreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdatePasswordCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.UpdatePasswordCredentialsSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdatePasswordCredentials", resp, "Failure sending request") + return + } + + result, err = client.UpdatePasswordCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.ServicePrincipalsClient", "UpdatePasswordCredentials", resp, "Failure responding to request") + } + + return +} + +// UpdatePasswordCredentialsPreparer prepares the UpdatePasswordCredentials request. +func (client ServicePrincipalsClient) UpdatePasswordCredentialsPreparer(ctx context.Context, objectID string, parameters PasswordCredentialsUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/servicePrincipals/{objectId}/passwordCredentials", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePasswordCredentialsSender sends the UpdatePasswordCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client ServicePrincipalsClient) UpdatePasswordCredentialsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdatePasswordCredentialsResponder handles the response to the UpdatePasswordCredentials request. The method always +// closes the http.Response Body. +func (client ServicePrincipalsClient) UpdatePasswordCredentialsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/signedinuser.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/signedinuser.go new file mode 100644 index 000000000..057658eef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/signedinuser.go @@ -0,0 +1,283 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// SignedInUserClient is the the Graph RBAC Management Client +type SignedInUserClient struct { + BaseClient +} + +// NewSignedInUserClient creates an instance of the SignedInUserClient client. +func NewSignedInUserClient(tenantID string) SignedInUserClient { + return NewSignedInUserClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewSignedInUserClientWithBaseURI creates an instance of the SignedInUserClient client. +func NewSignedInUserClientWithBaseURI(baseURI string, tenantID string) SignedInUserClient { + return SignedInUserClient{NewWithBaseURI(baseURI, tenantID)} +} + +// Get gets the details for the currently logged-in user. +func (client SignedInUserClient) Get(ctx context.Context) (result User, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SignedInUserClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SignedInUserClient) GetPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/me", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SignedInUserClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SignedInUserClient) GetResponder(resp *http.Response) (result User, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOwnedObjects get the list of directory objects that are owned by the user. +func (client SignedInUserClient) ListOwnedObjects(ctx context.Context) (result DirectoryObjectListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SignedInUserClient.ListOwnedObjects") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult DirectoryObjectListResult) (DirectoryObjectListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return DirectoryObjectListResult{}, nil + } + return client.ListOwnedObjectsNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListOwnedObjectsPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjects", nil, "Failure preparing request") + return + } + + resp, err := client.ListOwnedObjectsSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjects", resp, "Failure sending request") + return + } + + result.dolr, err = client.ListOwnedObjectsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjects", resp, "Failure responding to request") + } + + return +} + +// ListOwnedObjectsPreparer prepares the ListOwnedObjects request. +func (client SignedInUserClient) ListOwnedObjectsPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/me/ownedObjects", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOwnedObjectsSender sends the ListOwnedObjects request. The method will close the +// http.Response Body if it receives an error. +func (client SignedInUserClient) ListOwnedObjectsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListOwnedObjectsResponder handles the response to the ListOwnedObjects request. The method always +// closes the http.Response Body. +func (client SignedInUserClient) ListOwnedObjectsResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOwnedObjectsComplete enumerates all values, automatically crossing page boundaries as required. +func (client SignedInUserClient) ListOwnedObjectsComplete(ctx context.Context) (result DirectoryObjectListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SignedInUserClient.ListOwnedObjects") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListOwnedObjects(ctx) + return +} + +// ListOwnedObjectsNext get the list of directory objects that are owned by the user. +// Parameters: +// nextLink - next link for the list operation. +func (client SignedInUserClient) ListOwnedObjectsNext(ctx context.Context, nextLink string) (result DirectoryObjectListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SignedInUserClient.ListOwnedObjectsNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListOwnedObjectsNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjectsNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListOwnedObjectsNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjectsNext", resp, "Failure sending request") + return + } + + result, err = client.ListOwnedObjectsNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.SignedInUserClient", "ListOwnedObjectsNext", resp, "Failure responding to request") + } + + return +} + +// ListOwnedObjectsNextPreparer prepares the ListOwnedObjectsNext request. +func (client SignedInUserClient) ListOwnedObjectsNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOwnedObjectsNextSender sends the ListOwnedObjectsNext request. The method will close the +// http.Response Body if it receives an error. +func (client SignedInUserClient) ListOwnedObjectsNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListOwnedObjectsNextResponder handles the response to the ListOwnedObjectsNext request. The method always +// closes the http.Response Body. +func (client SignedInUserClient) ListOwnedObjectsNextResponder(resp *http.Response) (result DirectoryObjectListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/users.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/users.go new file mode 100644 index 000000000..3c688fe7b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/users.go @@ -0,0 +1,614 @@ +package graphrbac + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// UsersClient is the the Graph RBAC Management Client +type UsersClient struct { + BaseClient +} + +// NewUsersClient creates an instance of the UsersClient client. +func NewUsersClient(tenantID string) UsersClient { + return NewUsersClientWithBaseURI(DefaultBaseURI, tenantID) +} + +// NewUsersClientWithBaseURI creates an instance of the UsersClient client. +func NewUsersClientWithBaseURI(baseURI string, tenantID string) UsersClient { + return UsersClient{NewWithBaseURI(baseURI, tenantID)} +} + +// Create create a new user. +// Parameters: +// parameters - parameters to create a user. +func (client UsersClient) Create(ctx context.Context, parameters UserCreateParameters) (result User, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Create") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.AccountEnabled", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.DisplayName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.PasswordProfile", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.PasswordProfile.Password", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.UserPrincipalName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.MailNickname", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.UsersClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client UsersClient) CreatePreparer(ctx context.Context, parameters UserCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) CreateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client UsersClient) CreateResponder(resp *http.Response) (result User, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a user. +// Parameters: +// upnOrObjectID - the object ID or principal name of the user to delete. +func (client UsersClient) Delete(ctx context.Context, upnOrObjectID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, upnOrObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client UsersClient) DeletePreparer(ctx context.Context, upnOrObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + "upnOrObjectId": autorest.Encode("path", upnOrObjectID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users/{upnOrObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) DeleteSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client UsersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets user information from the directory. +// Parameters: +// upnOrObjectID - the object ID or principal name of the user for which to get information. +func (client UsersClient) Get(ctx context.Context, upnOrObjectID string) (result User, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, upnOrObjectID) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client UsersClient) GetPreparer(ctx context.Context, upnOrObjectID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + "upnOrObjectId": autorest.Encode("path", upnOrObjectID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users/{upnOrObjectId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) GetSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client UsersClient) GetResponder(resp *http.Response) (result User, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetMemberGroups gets a collection that contains the object IDs of the groups of which the user is a member. +// Parameters: +// objectID - the object ID of the user for which to get group membership. +// parameters - user filtering parameters. +func (client UsersClient) GetMemberGroups(ctx context.Context, objectID string, parameters UserGetMemberGroupsParameters) (result UserGetMemberGroupsResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.GetMemberGroups") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SecurityEnabledOnly", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("graphrbac.UsersClient", "GetMemberGroups", err.Error()) + } + + req, err := client.GetMemberGroupsPreparer(ctx, objectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "GetMemberGroups", nil, "Failure preparing request") + return + } + + resp, err := client.GetMemberGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "GetMemberGroups", resp, "Failure sending request") + return + } + + result, err = client.GetMemberGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "GetMemberGroups", resp, "Failure responding to request") + } + + return +} + +// GetMemberGroupsPreparer prepares the GetMemberGroups request. +func (client UsersClient) GetMemberGroupsPreparer(ctx context.Context, objectID string, parameters UserGetMemberGroupsParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "objectId": autorest.Encode("path", objectID), + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users/{objectId}/getMemberGroups", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetMemberGroupsSender sends the GetMemberGroups request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) GetMemberGroupsSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// GetMemberGroupsResponder handles the response to the GetMemberGroups request. The method always +// closes the http.Response Body. +func (client UsersClient) GetMemberGroupsResponder(resp *http.Response) (result UserGetMemberGroupsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets list of users for the current tenant. +// Parameters: +// filter - the filter to apply to the operation. +func (client UsersClient) List(ctx context.Context, filter string) (result UserListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.List") + defer func() { + sc := -1 + if result.ulr.Response.Response != nil { + sc = result.ulr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = func(ctx context.Context, lastResult UserListResult) (UserListResult, error) { + if lastResult.OdataNextLink == nil || len(to.String(lastResult.OdataNextLink)) < 1 { + return UserListResult{}, nil + } + return client.ListNext(ctx, *lastResult.OdataNextLink) + } + req, err := client.ListPreparer(ctx, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.ulr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "List", resp, "Failure sending request") + return + } + + result.ulr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client UsersClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) ListSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client UsersClient) ListResponder(resp *http.Response) (result UserListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client UsersClient) ListComplete(ctx context.Context, filter string) (result UserListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, filter) + return +} + +// ListNext gets a list of users for the current tenant. +// Parameters: +// nextLink - next link for the list operation. +func (client UsersClient) ListNext(ctx context.Context, nextLink string) (result UserListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.ListNext") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListNextPreparer(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "ListNext", nil, "Failure preparing request") + return + } + + resp, err := client.ListNextSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "ListNext", resp, "Failure sending request") + return + } + + result, err = client.ListNextResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "ListNext", resp, "Failure responding to request") + } + + return +} + +// ListNextPreparer prepares the ListNext request. +func (client UsersClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "nextLink": nextLink, + "tenantID": autorest.Encode("path", client.TenantID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/{nextLink}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListNextSender sends the ListNext request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) ListNextSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// ListNextResponder handles the response to the ListNext request. The method always +// closes the http.Response Body. +func (client UsersClient) ListNextResponder(resp *http.Response) (result UserListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a user. +// Parameters: +// upnOrObjectID - the object ID or principal name of the user to update. +// parameters - parameters to update an existing user. +func (client UsersClient) Update(ctx context.Context, upnOrObjectID string, parameters UserUpdateParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Update") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, upnOrObjectID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "graphrbac.UsersClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client UsersClient) UpdatePreparer(ctx context.Context, upnOrObjectID string, parameters UserUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "tenantID": autorest.Encode("path", client.TenantID), + "upnOrObjectId": autorest.Encode("path", upnOrObjectID), + } + + const APIVersion = "1.6" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{tenantID}/users/{upnOrObjectId}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client UsersClient) UpdateSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client UsersClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/version.go new file mode 100644 index 000000000..b8397dc96 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/version.go @@ -0,0 +1,30 @@ +package graphrbac + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " graphrbac/1.6" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deploymentoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deploymentoperations.go index 215e1ffba..3047aa00b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deploymentoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deploymentoperations.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -46,11 +47,21 @@ func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID str // deploymentName - the name of the deployment. // operationID - operation Id. func (client DeploymentOperationsClient) Get(ctx context.Context, resourceGroupName string, deploymentName string, operationID string) (result DeploymentOperation, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "Get", err.Error()) } @@ -100,8 +111,8 @@ func (client DeploymentOperationsClient) GetPreparer(ctx context.Context, resour // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always @@ -123,11 +134,21 @@ func (client DeploymentOperationsClient) GetResponder(resp *http.Response) (resu // deploymentName - the name of the deployment. // top - query parameters. func (client DeploymentOperationsClient) List(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.List") + defer func() { + sc := -1 + if result.dolr.Response.Response != nil { + sc = result.dolr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "List", err.Error()) } @@ -180,8 +201,8 @@ func (client DeploymentOperationsClient) ListPreparer(ctx context.Context, resou // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -198,8 +219,8 @@ func (client DeploymentOperationsClient) ListResponder(resp *http.Response) (res } // listNextResults retrieves the next set of results, if any. -func (client DeploymentOperationsClient) listNextResults(lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, err error) { - req, err := lastResults.deploymentOperationsListResultPreparer() +func (client DeploymentOperationsClient) listNextResults(ctx context.Context, lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, err error) { + req, err := lastResults.deploymentOperationsListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listNextResults", nil, "Failure preparing next results request") } @@ -220,6 +241,16 @@ func (client DeploymentOperationsClient) listNextResults(lastResults DeploymentO // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client DeploymentOperationsClient) ListComplete(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx, resourceGroupName, deploymentName, top) return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deployments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deployments.go index db4c7ca6a..184c1fecc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deployments.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/deployments.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -40,16 +41,98 @@ func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) Depl return DeploymentsClient{NewWithBaseURI(baseURI, subscriptionID)} } +// CalculateTemplateHash calculate the hash of the given template. +// Parameters: +// templateParameter - the template provided to calculate hash. +func (client DeploymentsClient) CalculateTemplateHash(ctx context.Context, templateParameter interface{}) (result TemplateHashResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.CalculateTemplateHash") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CalculateTemplateHashPreparer(ctx, templateParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CalculateTemplateHash", nil, "Failure preparing request") + return + } + + resp, err := client.CalculateTemplateHashSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CalculateTemplateHash", resp, "Failure sending request") + return + } + + result, err = client.CalculateTemplateHashResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CalculateTemplateHash", resp, "Failure responding to request") + } + + return +} + +// CalculateTemplateHashPreparer prepares the CalculateTemplateHash request. +func (client DeploymentsClient) CalculateTemplateHashPreparer(ctx context.Context, templateParameter interface{}) (*http.Request, error) { + const APIVersion = "2016-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Resources/calculateTemplateHash"), + autorest.WithJSON(templateParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CalculateTemplateHashSender sends the CalculateTemplateHash request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) CalculateTemplateHashSender(req *http.Request) (*http.Response, error) { + sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + return autorest.SendWithSender(client, req, sd...) +} + +// CalculateTemplateHashResponder handles the response to the CalculateTemplateHash request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) CalculateTemplateHashResponder(resp *http.Response) (result TemplateHashResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + // Cancel cancel a currently running template deployment. // Parameters: // resourceGroupName - the name of the resource group. The name is case insensitive. // deploymentName - the name of the deployment. func (client DeploymentsClient) Cancel(ctx context.Context, resourceGroupName string, deploymentName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Cancel") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "Cancel", err.Error()) } @@ -98,8 +181,8 @@ func (client DeploymentsClient) CancelPreparer(ctx context.Context, resourceGrou // CancelSender sends the Cancel request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CancelSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CancelResponder handles the response to the Cancel request. The method always @@ -119,11 +202,21 @@ func (client DeploymentsClient) CancelResponder(resp *http.Response) (result aut // resourceGroupName - the name of the resource group to check. The name is case insensitive. // deploymentName - the name of the deployment. func (client DeploymentsClient) CheckExistence(ctx context.Context, resourceGroupName string, deploymentName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.CheckExistence") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "CheckExistence", err.Error()) } @@ -172,8 +265,8 @@ func (client DeploymentsClient) CheckExistencePreparer(ctx context.Context, reso // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -194,11 +287,21 @@ func (client DeploymentsClient) CheckExistenceResponder(resp *http.Response) (re // deploymentName - the name of the deployment. // parameters - additional parameters supplied to the operation. func (client DeploymentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, parameters Deployment) (result DeploymentsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Properties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.Properties.TemplateLink", Name: validation.Null, Rule: false, @@ -250,9 +353,9 @@ func (client DeploymentsClient) CreateOrUpdatePreparer(ctx context.Context, reso // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CreateOrUpdateSender(req *http.Request) (future DeploymentsCreateOrUpdateFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } @@ -278,11 +381,21 @@ func (client DeploymentsClient) CreateOrUpdateResponder(resp *http.Response) (re // resourceGroupName - the name of the resource group. The name is case insensitive. // deploymentName - the name of the deployment to be deleted. func (client DeploymentsClient) Delete(ctx context.Context, resourceGroupName string, deploymentName string) (result DeploymentsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "Delete", err.Error()) } @@ -325,9 +438,9 @@ func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGrou // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) DeleteSender(req *http.Request) (future DeploymentsDeleteFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } @@ -352,11 +465,21 @@ func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result aut // resourceGroupName - the name of the resource group. The name is case insensitive. // deploymentName - the name of the deployment. func (client DeploymentsClient) ExportTemplate(ctx context.Context, resourceGroupName string, deploymentName string) (result DeploymentExportResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.ExportTemplate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "ExportTemplate", err.Error()) } @@ -405,8 +528,8 @@ func (client DeploymentsClient) ExportTemplatePreparer(ctx context.Context, reso // ExportTemplateSender sends the ExportTemplate request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) ExportTemplateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ExportTemplateResponder handles the response to the ExportTemplate request. The method always @@ -427,11 +550,21 @@ func (client DeploymentsClient) ExportTemplateResponder(resp *http.Response) (re // resourceGroupName - the name of the resource group to get. The name is case insensitive. // deploymentName - the name of the deployment. func (client DeploymentsClient) Get(ctx context.Context, resourceGroupName string, deploymentName string) (result DeploymentExtended, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "Get", err.Error()) } @@ -480,8 +613,8 @@ func (client DeploymentsClient) GetPreparer(ctx context.Context, resourceGroupNa // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always @@ -503,11 +636,21 @@ func (client DeploymentsClient) GetResponder(resp *http.Response) (result Deploy // filter - the filter to apply on the operation. // top - query parameters. If null is passed returns all deployments. func (client DeploymentsClient) List(ctx context.Context, resourceGroupName string, filter string, top *int32) (result DeploymentListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") + defer func() { + sc := -1 + if result.dlr.Response.Response != nil { + sc = result.dlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentsClient", "List", err.Error()) } @@ -562,8 +705,8 @@ func (client DeploymentsClient) ListPreparer(ctx context.Context, resourceGroupN // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -580,8 +723,8 @@ func (client DeploymentsClient) ListResponder(resp *http.Response) (result Deplo } // listNextResults retrieves the next set of results, if any. -func (client DeploymentsClient) listNextResults(lastResults DeploymentListResult) (result DeploymentListResult, err error) { - req, err := lastResults.deploymentListResultPreparer() +func (client DeploymentsClient) listNextResults(ctx context.Context, lastResults DeploymentListResult) (result DeploymentListResult, err error) { + req, err := lastResults.deploymentListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "listNextResults", nil, "Failure preparing next results request") } @@ -602,6 +745,16 @@ func (client DeploymentsClient) listNextResults(lastResults DeploymentListResult // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client DeploymentsClient) ListComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result DeploymentListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx, resourceGroupName, filter, top) return } @@ -612,11 +765,21 @@ func (client DeploymentsClient) ListComplete(ctx context.Context, resourceGroupN // deploymentName - the name of the deployment. // parameters - deployment to validate. func (client DeploymentsClient) Validate(ctx context.Context, resourceGroupName string, deploymentName string, parameters Deployment) (result DeploymentValidateResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Validate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Properties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.Properties.TemplateLink", Name: validation.Null, Rule: false, @@ -674,8 +837,8 @@ func (client DeploymentsClient) ValidatePreparer(ctx context.Context, resourceGr // ValidateSender sends the Validate request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) ValidateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ValidateResponder handles the response to the Validate request. The method always diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/groups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/groups.go index f4d05a1b4..9858b639b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/groups.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/groups.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -44,11 +45,21 @@ func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsCli // Parameters: // resourceGroupName - the name of the resource group to check. The name is case insensitive. func (client GroupsClient) CheckExistence(ctx context.Context, resourceGroupName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.CheckExistence") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "CheckExistence", err.Error()) } @@ -96,8 +107,8 @@ func (client GroupsClient) CheckExistencePreparer(ctx context.Context, resourceG // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -117,11 +128,21 @@ func (client GroupsClient) CheckExistenceResponder(resp *http.Response) (result // resourceGroupName - the name of the resource group to be created or updated. // parameters - parameters supplied to the create or update resource group service operation. func (client GroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parameters Group) (result Group, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "CreateOrUpdate", err.Error()) @@ -160,6 +181,7 @@ func (client GroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceG "api-version": APIVersion, } + parameters.ID = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), @@ -173,8 +195,8 @@ func (client GroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceG // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -194,11 +216,21 @@ func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result // Parameters: // resourceGroupName - the name of the resource group to be deleted. The name is case insensitive. func (client GroupsClient) Delete(ctx context.Context, resourceGroupName string) (result GroupsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "Delete", err.Error()) } @@ -240,9 +272,9 @@ func (client GroupsClient) DeletePreparer(ctx context.Context, resourceGroupName // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) DeleteSender(req *http.Request) (future GroupsDeleteFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } @@ -267,11 +299,21 @@ func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest // resourceGroupName - the name of the resource group to be created or updated. // parameters - parameters supplied to the export template resource group operation. func (client GroupsClient) ExportTemplate(ctx context.Context, resourceGroupName string, parameters ExportTemplateRequest) (result GroupExportResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ExportTemplate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "ExportTemplate", err.Error()) } @@ -321,8 +363,8 @@ func (client GroupsClient) ExportTemplatePreparer(ctx context.Context, resourceG // ExportTemplateSender sends the ExportTemplate request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) ExportTemplateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ExportTemplateResponder handles the response to the ExportTemplate request. The method always @@ -342,11 +384,21 @@ func (client GroupsClient) ExportTemplateResponder(resp *http.Response) (result // Parameters: // resourceGroupName - the name of the resource group to get. The name is case insensitive. func (client GroupsClient) Get(ctx context.Context, resourceGroupName string) (result Group, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "Get", err.Error()) } @@ -394,8 +446,8 @@ func (client GroupsClient) GetPreparer(ctx context.Context, resourceGroupName st // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always @@ -416,6 +468,16 @@ func (client GroupsClient) GetResponder(resp *http.Response) (result Group, err // filter - the filter to apply on the operation. // top - query parameters. If null is passed returns all resource groups. func (client GroupsClient) List(ctx context.Context, filter string, top *int32) (result GroupListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.glr.Response.Response != nil { + sc = result.glr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, filter, top) if err != nil { @@ -466,8 +528,8 @@ func (client GroupsClient) ListPreparer(ctx context.Context, filter string, top // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -484,8 +546,8 @@ func (client GroupsClient) ListResponder(resp *http.Response) (result GroupListR } // listNextResults retrieves the next set of results, if any. -func (client GroupsClient) listNextResults(lastResults GroupListResult) (result GroupListResult, err error) { - req, err := lastResults.groupListResultPreparer() +func (client GroupsClient) listNextResults(ctx context.Context, lastResults GroupListResult) (result GroupListResult, err error) { + req, err := lastResults.groupListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "listNextResults", nil, "Failure preparing next results request") } @@ -506,6 +568,16 @@ func (client GroupsClient) listNextResults(lastResults GroupListResult) (result // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client GroupsClient) ListComplete(ctx context.Context, filter string, top *int32) (result GroupListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx, filter, top) return } @@ -517,11 +589,21 @@ func (client GroupsClient) ListComplete(ctx context.Context, filter string, top // expand - the $expand query parameter // top - query parameters. If null is passed returns all resource groups. func (client GroupsClient) ListResources(ctx context.Context, resourceGroupName string, filter string, expand string, top *int32) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListResources") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "ListResources", err.Error()) } @@ -579,8 +661,8 @@ func (client GroupsClient) ListResourcesPreparer(ctx context.Context, resourceGr // ListResourcesSender sends the ListResources request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) ListResourcesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResourcesResponder handles the response to the ListResources request. The method always @@ -597,8 +679,8 @@ func (client GroupsClient) ListResourcesResponder(resp *http.Response) (result L } // listResourcesNextResults retrieves the next set of results, if any. -func (client GroupsClient) listResourcesNextResults(lastResults ListResult) (result ListResult, err error) { - req, err := lastResults.listResultPreparer() +func (client GroupsClient) listResourcesNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "listResourcesNextResults", nil, "Failure preparing next results request") } @@ -619,6 +701,16 @@ func (client GroupsClient) listResourcesNextResults(lastResults ListResult) (res // ListResourcesComplete enumerates all values, automatically crossing page boundaries as required. func (client GroupsClient) ListResourcesComplete(ctx context.Context, resourceGroupName string, filter string, expand string, top *int32) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListResources") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.ListResources(ctx, resourceGroupName, filter, expand, top) return } @@ -630,11 +722,21 @@ func (client GroupsClient) ListResourcesComplete(ctx context.Context, resourceGr // resourceGroupName - the name of the resource group to be created or updated. The name is case insensitive. // parameters - parameters supplied to the update state resource group service operation. func (client GroupsClient) Patch(ctx context.Context, resourceGroupName string, parameters Group) (result Group, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Patch") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.GroupsClient", "Patch", err.Error()) } @@ -671,6 +773,7 @@ func (client GroupsClient) PatchPreparer(ctx context.Context, resourceGroupName "api-version": APIVersion, } + parameters.ID = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), @@ -684,8 +787,8 @@ func (client GroupsClient) PatchPreparer(ctx context.Context, resourceGroupName // PatchSender sends the Patch request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) PatchSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // PatchResponder handles the response to the Patch request. The method always diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/models.go index bf84a5d4c..bfd5e4acb 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/models.go @@ -18,14 +18,19 @@ package resources // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( + "context" "encoding/json" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/date" "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" "net/http" ) +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources" + // DeploymentMode enumerates the values for deployment mode. type DeploymentMode string @@ -80,6 +85,11 @@ type BasicDependency struct { ResourceName *string `json:"resourceName,omitempty"` } +// CloudError an error response for a resource management request. +type CloudError struct { + Error *ErrorResponse `json:"error,omitempty"` +} + // DebugSetting ... type DebugSetting struct { // DetailLevel - The debug detail level. @@ -114,7 +124,7 @@ type DeploymentExportResult struct { // DeploymentExtended deployment information. type DeploymentExtended struct { autorest.Response `json:"-"` - // ID - The ID of the deployment. + // ID - READ-ONLY; The ID of the deployment. ID *string `json:"id,omitempty"` // Name - The name of the deployment. Name *string `json:"name,omitempty"` @@ -143,14 +153,24 @@ type DeploymentListResultIterator struct { page DeploymentListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *DeploymentListResultIterator) Next() error { +func (iter *DeploymentListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -159,6 +179,13 @@ func (iter *DeploymentListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *DeploymentListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DeploymentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -178,6 +205,11 @@ func (iter DeploymentListResultIterator) Value() DeploymentExtended { return iter.page.Values()[iter.i] } +// Creates a new instance of the DeploymentListResultIterator type. +func NewDeploymentListResultIterator(page DeploymentListResultPage) DeploymentListResultIterator { + return DeploymentListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (dlr DeploymentListResult) IsEmpty() bool { return dlr.Value == nil || len(*dlr.Value) == 0 @@ -185,11 +217,11 @@ func (dlr DeploymentListResult) IsEmpty() bool { // deploymentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (dlr DeploymentListResult) deploymentListResultPreparer() (*http.Request, error) { +func (dlr DeploymentListResult) deploymentListResultPreparer(ctx context.Context) (*http.Request, error) { if dlr.NextLink == nil || len(to.String(dlr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dlr.NextLink))) @@ -197,14 +229,24 @@ func (dlr DeploymentListResult) deploymentListResultPreparer() (*http.Request, e // DeploymentListResultPage contains a page of DeploymentExtended values. type DeploymentListResultPage struct { - fn func(DeploymentListResult) (DeploymentListResult, error) + fn func(context.Context, DeploymentListResult) (DeploymentListResult, error) dlr DeploymentListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *DeploymentListResultPage) Next() error { - next, err := page.fn(page.dlr) +func (page *DeploymentListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.dlr) if err != nil { return err } @@ -212,6 +254,13 @@ func (page *DeploymentListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *DeploymentListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DeploymentListResultPage) NotDone() bool { return !page.dlr.IsEmpty() @@ -230,6 +279,11 @@ func (page DeploymentListResultPage) Values() []DeploymentExtended { return *page.dlr.Value } +// Creates a new instance of the DeploymentListResultPage type. +func NewDeploymentListResultPage(getNextPage func(context.Context, DeploymentListResult) (DeploymentListResult, error)) DeploymentListResultPage { + return DeploymentListResultPage{fn: getNextPage} +} + // DeploymentOperation deployment operation information. type DeploymentOperation struct { autorest.Response `json:"-"` @@ -270,20 +324,31 @@ type DeploymentOperationsListResult struct { NextLink *string `json:"nextLink,omitempty"` } -// DeploymentOperationsListResultIterator provides access to a complete listing of DeploymentOperation values. +// DeploymentOperationsListResultIterator provides access to a complete listing of DeploymentOperation +// values. type DeploymentOperationsListResultIterator struct { i int page DeploymentOperationsListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *DeploymentOperationsListResultIterator) Next() error { +func (iter *DeploymentOperationsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -292,6 +357,13 @@ func (iter *DeploymentOperationsListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *DeploymentOperationsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DeploymentOperationsListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -311,6 +383,11 @@ func (iter DeploymentOperationsListResultIterator) Value() DeploymentOperation { return iter.page.Values()[iter.i] } +// Creates a new instance of the DeploymentOperationsListResultIterator type. +func NewDeploymentOperationsListResultIterator(page DeploymentOperationsListResultPage) DeploymentOperationsListResultIterator { + return DeploymentOperationsListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (dolr DeploymentOperationsListResult) IsEmpty() bool { return dolr.Value == nil || len(*dolr.Value) == 0 @@ -318,11 +395,11 @@ func (dolr DeploymentOperationsListResult) IsEmpty() bool { // deploymentOperationsListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (dolr DeploymentOperationsListResult) deploymentOperationsListResultPreparer() (*http.Request, error) { +func (dolr DeploymentOperationsListResult) deploymentOperationsListResultPreparer(ctx context.Context) (*http.Request, error) { if dolr.NextLink == nil || len(to.String(dolr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dolr.NextLink))) @@ -330,14 +407,24 @@ func (dolr DeploymentOperationsListResult) deploymentOperationsListResultPrepare // DeploymentOperationsListResultPage contains a page of DeploymentOperation values. type DeploymentOperationsListResultPage struct { - fn func(DeploymentOperationsListResult) (DeploymentOperationsListResult, error) + fn func(context.Context, DeploymentOperationsListResult) (DeploymentOperationsListResult, error) dolr DeploymentOperationsListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *DeploymentOperationsListResultPage) Next() error { - next, err := page.fn(page.dolr) +func (page *DeploymentOperationsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.dolr) if err != nil { return err } @@ -345,6 +432,13 @@ func (page *DeploymentOperationsListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *DeploymentOperationsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DeploymentOperationsListResultPage) NotDone() bool { return !page.dolr.IsEmpty() @@ -363,6 +457,11 @@ func (page DeploymentOperationsListResultPage) Values() []DeploymentOperation { return *page.dolr.Value } +// Creates a new instance of the DeploymentOperationsListResultPage type. +func NewDeploymentOperationsListResultPage(getNextPage func(context.Context, DeploymentOperationsListResult) (DeploymentOperationsListResult, error)) DeploymentOperationsListResultPage { + return DeploymentOperationsListResultPage{fn: getNextPage} +} + // DeploymentProperties deployment properties. type DeploymentProperties struct { // Template - The template content. It can be a JObject or a well formed JSON string. Use only one of Template or TemplateLink. @@ -387,7 +486,7 @@ type DeploymentPropertiesExtended struct { CorrelationID *string `json:"correlationId,omitempty"` // Timestamp - The timestamp of the template deployment. Timestamp *date.Time `json:"timestamp,omitempty"` - // Outputs - Key/value pairs that represent deploymentoutput. + // Outputs - Key/value pairs that represent deployment output. Outputs interface{} `json:"outputs,omitempty"` // Providers - The list of resource providers needed for the deployment. Providers *[]Provider `json:"providers,omitempty"` @@ -407,8 +506,8 @@ type DeploymentPropertiesExtended struct { DebugSetting *DebugSetting `json:"debugSetting,omitempty"` } -// DeploymentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. +// DeploymentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. type DeploymentsCreateOrUpdateFuture struct { azure.Future } @@ -417,7 +516,7 @@ type DeploymentsCreateOrUpdateFuture struct { // If the operation has not completed it will return an error. func (future *DeploymentsCreateOrUpdateFuture) Result(client DeploymentsClient) (de DeploymentExtended, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return @@ -436,7 +535,8 @@ func (future *DeploymentsCreateOrUpdateFuture) Result(client DeploymentsClient) return } -// DeploymentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +// DeploymentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. type DeploymentsDeleteFuture struct { azure.Future } @@ -445,7 +545,7 @@ type DeploymentsDeleteFuture struct { // If the operation has not completed it will return an error. func (future *DeploymentsDeleteFuture) Result(client DeploymentsClient) (ar autorest.Response, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentsDeleteFuture", "Result", future.Response(), "Polling failure") return @@ -467,11 +567,33 @@ type DeploymentValidateResult struct { Properties *DeploymentPropertiesExtended `json:"properties,omitempty"` } +// ErrorAdditionalInfo the resource management error additional info. +type ErrorAdditionalInfo struct { + // Type - READ-ONLY; The additional info type. + Type *string `json:"type,omitempty"` + // Info - READ-ONLY; The additional info. + Info interface{} `json:"info,omitempty"` +} + +// ErrorResponse the resource management error response. +type ErrorResponse struct { + // Code - READ-ONLY; The error code. + Code *string `json:"code,omitempty"` + // Message - READ-ONLY; The error message. + Message *string `json:"message,omitempty"` + // Target - READ-ONLY; The error target. + Target *string `json:"target,omitempty"` + // Details - READ-ONLY; The error details. + Details *[]ErrorResponse `json:"details,omitempty"` + // AdditionalInfo - READ-ONLY; The error additional info. + AdditionalInfo *[]ErrorAdditionalInfo `json:"additionalInfo,omitempty"` +} + // ExportTemplateRequest export resource group template request parameters. type ExportTemplateRequest struct { - // ResourcesProperty - The ids of the resources. The only supported string currently is '*' (all resources). Future api updates will support exporting specific resources. + // ResourcesProperty - The IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. ResourcesProperty *[]string `json:"resources,omitempty"` - // Options - The export template options. Supported values include 'IncludeParameterDefaultValue', 'IncludeComments' or 'IncludeParameterDefaultValue, IncludeComments + // Options - The export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization' Options *string `json:"options,omitempty"` } @@ -490,11 +612,11 @@ type GenericResource struct { Sku *Sku `json:"sku,omitempty"` // Identity - The identity of the resource. Identity *Identity `json:"identity,omitempty"` - // ID - Resource Id + // ID - READ-ONLY; Resource Id ID *string `json:"id,omitempty"` - // Name - Resource name + // Name - READ-ONLY; Resource name Name *string `json:"name,omitempty"` - // Type - Resource type + // Type - READ-ONLY; Resource type Type *string `json:"type,omitempty"` // Location - Resource location Location *string `json:"location,omitempty"` @@ -508,7 +630,9 @@ func (gr GenericResource) MarshalJSON() ([]byte, error) { if gr.Plan != nil { objectMap["plan"] = gr.Plan } - objectMap["properties"] = gr.Properties + if gr.Properties != nil { + objectMap["properties"] = gr.Properties + } if gr.Kind != nil { objectMap["kind"] = gr.Kind } @@ -521,15 +645,6 @@ func (gr GenericResource) MarshalJSON() ([]byte, error) { if gr.Identity != nil { objectMap["identity"] = gr.Identity } - if gr.ID != nil { - objectMap["id"] = gr.ID - } - if gr.Name != nil { - objectMap["name"] = gr.Name - } - if gr.Type != nil { - objectMap["type"] = gr.Type - } if gr.Location != nil { objectMap["location"] = gr.Location } @@ -552,7 +667,7 @@ type GenericResourceFilter struct { // Group resource group information. type Group struct { autorest.Response `json:"-"` - // ID - The ID of the resource group. + // ID - READ-ONLY; The ID of the resource group. ID *string `json:"id,omitempty"` // Name - The Name of the resource group. Name *string `json:"name,omitempty"` @@ -566,9 +681,6 @@ type Group struct { // MarshalJSON is the custom marshaler for Group. func (g Group) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if g.ID != nil { - objectMap["id"] = g.ID - } if g.Name != nil { objectMap["name"] = g.Name } @@ -616,14 +728,24 @@ type GroupListResultIterator struct { page GroupListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *GroupListResultIterator) Next() error { +func (iter *GroupListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -632,6 +754,13 @@ func (iter *GroupListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GroupListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter GroupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -651,6 +780,11 @@ func (iter GroupListResultIterator) Value() Group { return iter.page.Values()[iter.i] } +// Creates a new instance of the GroupListResultIterator type. +func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator { + return GroupListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (glr GroupListResult) IsEmpty() bool { return glr.Value == nil || len(*glr.Value) == 0 @@ -658,11 +792,11 @@ func (glr GroupListResult) IsEmpty() bool { // groupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (glr GroupListResult) groupListResultPreparer() (*http.Request, error) { +func (glr GroupListResult) groupListResultPreparer(ctx context.Context) (*http.Request, error) { if glr.NextLink == nil || len(to.String(glr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(glr.NextLink))) @@ -670,14 +804,24 @@ func (glr GroupListResult) groupListResultPreparer() (*http.Request, error) { // GroupListResultPage contains a page of Group values. type GroupListResultPage struct { - fn func(GroupListResult) (GroupListResult, error) + fn func(context.Context, GroupListResult) (GroupListResult, error) glr GroupListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *GroupListResultPage) Next() error { - next, err := page.fn(page.glr) +func (page *GroupListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.glr) if err != nil { return err } @@ -685,6 +829,13 @@ func (page *GroupListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GroupListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page GroupListResultPage) NotDone() bool { return !page.glr.IsEmpty() @@ -703,9 +854,14 @@ func (page GroupListResultPage) Values() []Group { return *page.glr.Value } +// Creates a new instance of the GroupListResultPage type. +func NewGroupListResultPage(getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage { + return GroupListResultPage{fn: getNextPage} +} + // GroupProperties the resource group properties. type GroupProperties struct { - // ProvisioningState - The provisioning state. + // ProvisioningState - READ-ONLY; The provisioning state. ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -718,7 +874,7 @@ type GroupsDeleteFuture struct { // If the operation has not completed it will return an error. func (future *GroupsDeleteFuture) Result(client GroupsClient) (ar autorest.Response, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "resources.GroupsDeleteFuture", "Result", future.Response(), "Polling failure") return @@ -739,9 +895,9 @@ type HTTPMessage struct { // Identity identity for the resource. type Identity struct { - // PrincipalID - The principal id of resource identity. + // PrincipalID - READ-ONLY; The principal id of resource identity. PrincipalID *string `json:"principalId,omitempty"` - // TenantID - The tenant id of resource. + // TenantID - READ-ONLY; The tenant id of resource. TenantID *string `json:"tenantId,omitempty"` // Type - The identity type. Possible values include: 'SystemAssigned' Type ResourceIdentityType `json:"type,omitempty"` @@ -762,14 +918,24 @@ type ListResultIterator struct { page ListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *ListResultIterator) Next() error { +func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -778,6 +944,13 @@ func (iter *ListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -797,6 +970,11 @@ func (iter ListResultIterator) Value() GenericResource { return iter.page.Values()[iter.i] } +// Creates a new instance of the ListResultIterator type. +func NewListResultIterator(page ListResultPage) ListResultIterator { + return ListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (lr ListResult) IsEmpty() bool { return lr.Value == nil || len(*lr.Value) == 0 @@ -804,11 +982,11 @@ func (lr ListResult) IsEmpty() bool { // listResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (lr ListResult) listResultPreparer() (*http.Request, error) { +func (lr ListResult) listResultPreparer(ctx context.Context) (*http.Request, error) { if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(lr.NextLink))) @@ -816,14 +994,24 @@ func (lr ListResult) listResultPreparer() (*http.Request, error) { // ListResultPage contains a page of GenericResource values. type ListResultPage struct { - fn func(ListResult) (ListResult, error) + fn func(context.Context, ListResult) (ListResult, error) lr ListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *ListResultPage) Next() error { - next, err := page.fn(page.lr) +func (page *ListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.lr) if err != nil { return err } @@ -831,6 +1019,13 @@ func (page *ListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ListResultPage) NotDone() bool { return !page.lr.IsEmpty() @@ -849,6 +1044,11 @@ func (page ListResultPage) Values() []GenericResource { return *page.lr.Value } +// Creates a new instance of the ListResultPage type. +func NewListResultPage(getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage { + return ListResultPage{fn: getNextPage} +} + // ManagementErrorWithDetails ... type ManagementErrorWithDetails struct { // Code - The error code returned from the server. @@ -869,7 +1069,8 @@ type MoveInfo struct { TargetResourceGroup *string `json:"targetResourceGroup,omitempty"` } -// MoveResourcesFuture an abstraction for monitoring and retrieving the results of a long-running operation. +// MoveResourcesFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. type MoveResourcesFuture struct { azure.Future } @@ -878,7 +1079,7 @@ type MoveResourcesFuture struct { // If the operation has not completed it will return an error. func (future *MoveResourcesFuture) Result(client Client) (ar autorest.Response, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "resources.MoveResourcesFuture", "Result", future.Response(), "Polling failure") return @@ -891,7 +1092,7 @@ func (future *MoveResourcesFuture) Result(client Client) (ar autorest.Response, return } -// ParametersLink entity representing the reference to the deployment paramaters. +// ParametersLink entity representing the reference to the deployment parameters. type ParametersLink struct { // URI - URI referencing the template. URI *string `json:"uri,omitempty"` @@ -939,14 +1140,24 @@ type ProviderListResultIterator struct { page ProviderListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *ProviderListResultIterator) Next() error { +func (iter *ProviderListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -955,6 +1166,13 @@ func (iter *ProviderListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ProviderListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ProviderListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -974,6 +1192,11 @@ func (iter ProviderListResultIterator) Value() Provider { return iter.page.Values()[iter.i] } +// Creates a new instance of the ProviderListResultIterator type. +func NewProviderListResultIterator(page ProviderListResultPage) ProviderListResultIterator { + return ProviderListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (plr ProviderListResult) IsEmpty() bool { return plr.Value == nil || len(*plr.Value) == 0 @@ -981,11 +1204,11 @@ func (plr ProviderListResult) IsEmpty() bool { // providerListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (plr ProviderListResult) providerListResultPreparer() (*http.Request, error) { +func (plr ProviderListResult) providerListResultPreparer(ctx context.Context) (*http.Request, error) { if plr.NextLink == nil || len(to.String(plr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(plr.NextLink))) @@ -993,14 +1216,24 @@ func (plr ProviderListResult) providerListResultPreparer() (*http.Request, error // ProviderListResultPage contains a page of Provider values. type ProviderListResultPage struct { - fn func(ProviderListResult) (ProviderListResult, error) + fn func(context.Context, ProviderListResult) (ProviderListResult, error) plr ProviderListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *ProviderListResultPage) Next() error { - next, err := page.fn(page.plr) +func (page *ProviderListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.plr) if err != nil { return err } @@ -1008,6 +1241,13 @@ func (page *ProviderListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ProviderListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ProviderListResultPage) NotDone() bool { return !page.plr.IsEmpty() @@ -1026,6 +1266,11 @@ func (page ProviderListResultPage) Values() []Provider { return *page.plr.Value } +// Creates a new instance of the ProviderListResultPage type. +func NewProviderListResultPage(getNextPage func(context.Context, ProviderListResult) (ProviderListResult, error)) ProviderListResultPage { + return ProviderListResultPage{fn: getNextPage} +} + // ProviderOperationDisplayProperties resource provider operation's display properties. type ProviderOperationDisplayProperties struct { // Publisher - Operation description. @@ -1077,11 +1322,11 @@ func (prt ProviderResourceType) MarshalJSON() ([]byte, error) { // Resource ... type Resource struct { - // ID - Resource Id + // ID - READ-ONLY; Resource Id ID *string `json:"id,omitempty"` - // Name - Resource name + // Name - READ-ONLY; Resource name Name *string `json:"name,omitempty"` - // Type - Resource type + // Type - READ-ONLY; Resource type Type *string `json:"type,omitempty"` // Location - Resource location Location *string `json:"location,omitempty"` @@ -1092,15 +1337,6 @@ type Resource struct { // MarshalJSON is the custom marshaler for Resource. func (r Resource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } if r.Location != nil { objectMap["location"] = r.Location } @@ -1143,7 +1379,7 @@ type TagCount struct { // TagDetails tag details. type TagDetails struct { autorest.Response `json:"-"` - // ID - The tag ID. + // ID - READ-ONLY; The tag ID. ID *string `json:"id,omitempty"` // TagName - The tag name. TagName *string `json:"tagName,omitempty"` @@ -1168,14 +1404,24 @@ type TagsListResultIterator struct { page TagsListResultPage } -// Next advances to the next value. If there was an error making +// NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. -func (iter *TagsListResultIterator) Next() error { +func (iter *TagsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } iter.i++ if iter.i < len(iter.page.Values()) { return nil } - err := iter.page.Next() + err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err @@ -1184,6 +1430,13 @@ func (iter *TagsListResultIterator) Next() error { return nil } +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *TagsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + // NotDone returns true if the enumeration should be started or is not yet complete. func (iter TagsListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) @@ -1203,6 +1456,11 @@ func (iter TagsListResultIterator) Value() TagDetails { return iter.page.Values()[iter.i] } +// Creates a new instance of the TagsListResultIterator type. +func NewTagsListResultIterator(page TagsListResultPage) TagsListResultIterator { + return TagsListResultIterator{page: page} +} + // IsEmpty returns true if the ListResult contains no values. func (tlr TagsListResult) IsEmpty() bool { return tlr.Value == nil || len(*tlr.Value) == 0 @@ -1210,11 +1468,11 @@ func (tlr TagsListResult) IsEmpty() bool { // tagsListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. -func (tlr TagsListResult) tagsListResultPreparer() (*http.Request, error) { +func (tlr TagsListResult) tagsListResultPreparer(ctx context.Context) (*http.Request, error) { if tlr.NextLink == nil || len(to.String(tlr.NextLink)) < 1 { return nil, nil } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(tlr.NextLink))) @@ -1222,14 +1480,24 @@ func (tlr TagsListResult) tagsListResultPreparer() (*http.Request, error) { // TagsListResultPage contains a page of TagDetails values. type TagsListResultPage struct { - fn func(TagsListResult) (TagsListResult, error) + fn func(context.Context, TagsListResult) (TagsListResult, error) tlr TagsListResult } -// Next advances to the next page of values. If there was an error making +// NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. -func (page *TagsListResultPage) Next() error { - next, err := page.fn(page.tlr) +func (page *TagsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.tlr) if err != nil { return err } @@ -1237,6 +1505,13 @@ func (page *TagsListResultPage) Next() error { return nil } +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *TagsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + // NotDone returns true if the page enumeration should be started or is not yet complete. func (page TagsListResultPage) NotDone() bool { return !page.tlr.IsEmpty() @@ -1255,10 +1530,15 @@ func (page TagsListResultPage) Values() []TagDetails { return *page.tlr.Value } +// Creates a new instance of the TagsListResultPage type. +func NewTagsListResultPage(getNextPage func(context.Context, TagsListResult) (TagsListResult, error)) TagsListResultPage { + return TagsListResultPage{fn: getNextPage} +} + // TagValue tag information. type TagValue struct { autorest.Response `json:"-"` - // ID - The tag ID. + // ID - READ-ONLY; The tag ID. ID *string `json:"id,omitempty"` // TagValue - The tag value. TagValue *string `json:"tagValue,omitempty"` @@ -1276,6 +1556,16 @@ type TargetResource struct { ResourceType *string `json:"resourceType,omitempty"` } +// TemplateHashResult result of the request to calculate template hash. It contains a string of minified +// template and its hash. +type TemplateHashResult struct { + autorest.Response `json:"-"` + // MinifiedTemplate - The minified template string. + MinifiedTemplate *string `json:"minifiedTemplate,omitempty"` + // TemplateHash - The template hash. + TemplateHash *string `json:"templateHash,omitempty"` +} + // TemplateLink entity representing the reference to the template. type TemplateLink struct { // URI - URI referencing the template. @@ -1293,7 +1583,7 @@ type UpdateFuture struct { // If the operation has not completed it will return an error. func (future *UpdateFuture) Result(client Client) (gr GenericResource, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "resources.UpdateFuture", "Result", future.Response(), "Polling failure") return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/providers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/providers.go index 4993b1f43..7ba9bdfc8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/providers.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/providers.go @@ -21,6 +21,7 @@ import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -45,6 +46,16 @@ func NewProvidersClientWithBaseURI(baseURI string, subscriptionID string) Provid // expand - the $expand query parameter. e.g. To include property aliases in response, use // $expand=resourceTypes/aliases. func (client ProvidersClient) Get(ctx context.Context, resourceProviderNamespace string, expand string) (result Provider, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProvidersClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.GetPreparer(ctx, resourceProviderNamespace, expand) if err != nil { err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Get", nil, "Failure preparing request") @@ -92,8 +103,8 @@ func (client ProvidersClient) GetPreparer(ctx context.Context, resourceProviderN // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always @@ -115,6 +126,16 @@ func (client ProvidersClient) GetResponder(resp *http.Response) (result Provider // expand - the $expand query parameter. e.g. To include property aliases in response, use // $expand=resourceTypes/aliases. func (client ProvidersClient) List(ctx context.Context, top *int32, expand string) (result ProviderListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProvidersClient.List") + defer func() { + sc := -1 + if result.plr.Response.Response != nil { + sc = result.plr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, top, expand) if err != nil { @@ -165,8 +186,8 @@ func (client ProvidersClient) ListPreparer(ctx context.Context, top *int32, expa // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -183,8 +204,8 @@ func (client ProvidersClient) ListResponder(resp *http.Response) (result Provide } // listNextResults retrieves the next set of results, if any. -func (client ProvidersClient) listNextResults(lastResults ProviderListResult) (result ProviderListResult, err error) { - req, err := lastResults.providerListResultPreparer() +func (client ProvidersClient) listNextResults(ctx context.Context, lastResults ProviderListResult) (result ProviderListResult, err error) { + req, err := lastResults.providerListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "listNextResults", nil, "Failure preparing next results request") } @@ -205,6 +226,16 @@ func (client ProvidersClient) listNextResults(lastResults ProviderListResult) (r // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client ProvidersClient) ListComplete(ctx context.Context, top *int32, expand string) (result ProviderListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProvidersClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx, top, expand) return } @@ -213,6 +244,16 @@ func (client ProvidersClient) ListComplete(ctx context.Context, top *int32, expa // Parameters: // resourceProviderNamespace - namespace of the resource provider. func (client ProvidersClient) Register(ctx context.Context, resourceProviderNamespace string) (result Provider, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProvidersClient.Register") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.RegisterPreparer(ctx, resourceProviderNamespace) if err != nil { err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Register", nil, "Failure preparing request") @@ -257,8 +298,8 @@ func (client ProvidersClient) RegisterPreparer(ctx context.Context, resourceProv // RegisterSender sends the Register request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) RegisterSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // RegisterResponder handles the response to the Register request. The method always @@ -278,6 +319,16 @@ func (client ProvidersClient) RegisterResponder(resp *http.Response) (result Pro // Parameters: // resourceProviderNamespace - namespace of the resource provider. func (client ProvidersClient) Unregister(ctx context.Context, resourceProviderNamespace string) (result Provider, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProvidersClient.Unregister") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.UnregisterPreparer(ctx, resourceProviderNamespace) if err != nil { err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Unregister", nil, "Failure preparing request") @@ -322,8 +373,8 @@ func (client ProvidersClient) UnregisterPreparer(ctx context.Context, resourcePr // UnregisterSender sends the Unregister request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) UnregisterSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // UnregisterResponder handles the response to the Unregister request. The method always diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/resources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/resources.go index 301b9934e..d0c2d4c5f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/resources.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/resources.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -48,11 +49,21 @@ func NewClientWithBaseURI(baseURI string, subscriptionID string) Client { // resourceType - resource identity. // resourceName - resource identity. func (client Client) CheckExistence(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.CheckExistence") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "CheckExistence", err.Error()) } @@ -104,8 +115,8 @@ func (client Client) CheckExistencePreparer(ctx context.Context, resourceGroupNa // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client Client) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -129,11 +140,21 @@ func (client Client) CheckExistenceResponder(resp *http.Response) (result autore // resourceName - resource identity. // parameters - create or update resource parameters. func (client Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, parameters GenericResource) (result GenericResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "CreateOrUpdate", err.Error()) } @@ -187,8 +208,8 @@ func (client Client) CreateOrUpdatePreparer(ctx context.Context, resourceGroupNa // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client Client) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -212,11 +233,21 @@ func (client Client) CreateOrUpdateResponder(resp *http.Response) (result Generi // resourceType - resource identity. // resourceName - resource identity. func (client Client) Delete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "Delete", err.Error()) } @@ -268,8 +299,8 @@ func (client Client) DeletePreparer(ctx context.Context, resourceGroupName strin // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // DeleteResponder handles the response to the Delete request. The method always @@ -292,11 +323,21 @@ func (client Client) DeleteResponder(resp *http.Response) (result autorest.Respo // resourceType - resource identity. // resourceName - resource identity. func (client Client) Get(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string) (result GenericResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "Get", err.Error()) } @@ -348,8 +389,8 @@ func (client Client) GetPreparer(ctx context.Context, resourceGroupName string, // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always @@ -371,6 +412,16 @@ func (client Client) GetResponder(resp *http.Response) (result GenericResource, // expand - the $expand query parameter. // top - query parameters. If null is passed returns all resource groups. func (client Client) List(ctx context.Context, filter string, expand string, top *int32) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.List") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, filter, expand, top) if err != nil { @@ -424,8 +475,8 @@ func (client Client) ListPreparer(ctx context.Context, filter string, expand str // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client Client) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -442,8 +493,8 @@ func (client Client) ListResponder(resp *http.Response) (result ListResult, err } // listNextResults retrieves the next set of results, if any. -func (client Client) listNextResults(lastResults ListResult) (result ListResult, err error) { - req, err := lastResults.listResultPreparer() +func (client Client) listNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.Client", "listNextResults", nil, "Failure preparing next results request") } @@ -464,6 +515,16 @@ func (client Client) listNextResults(lastResults ListResult) (result ListResult, // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client Client) ListComplete(ctx context.Context, filter string, expand string, top *int32) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx, filter, expand, top) return } @@ -474,11 +535,21 @@ func (client Client) ListComplete(ctx context.Context, filter string, expand str // sourceResourceGroupName - source resource group name. // parameters - move resources' parameters. func (client Client) MoveResources(ctx context.Context, sourceResourceGroupName string, parameters MoveInfo) (result MoveResourcesFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.MoveResources") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: sourceResourceGroupName, Constraints: []validation.Constraint{{Target: "sourceResourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "sourceResourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "sourceResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "sourceResourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "MoveResources", err.Error()) } @@ -522,9 +593,9 @@ func (client Client) MoveResourcesPreparer(ctx context.Context, sourceResourceGr // MoveResourcesSender sends the MoveResources request. The method will close the // http.Response Body if it receives an error. func (client Client) MoveResourcesSender(req *http.Request) (future MoveResourcesFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } @@ -553,11 +624,21 @@ func (client Client) MoveResourcesResponder(resp *http.Response) (result autores // resourceName - the name of the resource to update. // parameters - parameters for updating the resource. func (client Client) Update(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, parameters GenericResource) (result UpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/Client.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.Client", "Update", err.Error()) } @@ -605,9 +686,9 @@ func (client Client) UpdatePreparer(ctx context.Context, resourceGroupName strin // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client Client) UpdateSender(req *http.Request) (future UpdateFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/tags.go b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/tags.go index c38a38188..62f9d05b9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/tags.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources/tags.go @@ -21,6 +21,7 @@ import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -43,6 +44,16 @@ func NewTagsClientWithBaseURI(baseURI string, subscriptionID string) TagsClient // Parameters: // tagName - the name of the tag. func (client TagsClient) CreateOrUpdate(ctx context.Context, tagName string) (result TagDetails, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.CreateOrUpdatePreparer(ctx, tagName) if err != nil { err = autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdate", nil, "Failure preparing request") @@ -87,8 +98,8 @@ func (client TagsClient) CreateOrUpdatePreparer(ctx context.Context, tagName str // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -109,6 +120,16 @@ func (client TagsClient) CreateOrUpdateResponder(resp *http.Response) (result Ta // tagName - the name of the tag. // tagValue - the value of the tag. func (client TagsClient) CreateOrUpdateValue(ctx context.Context, tagName string, tagValue string) (result TagValue, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.CreateOrUpdateValue") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.CreateOrUpdateValuePreparer(ctx, tagName, tagValue) if err != nil { err = autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdateValue", nil, "Failure preparing request") @@ -154,8 +175,8 @@ func (client TagsClient) CreateOrUpdateValuePreparer(ctx context.Context, tagNam // CreateOrUpdateValueSender sends the CreateOrUpdateValue request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) CreateOrUpdateValueSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CreateOrUpdateValueResponder handles the response to the CreateOrUpdateValue request. The method always @@ -175,6 +196,16 @@ func (client TagsClient) CreateOrUpdateValueResponder(resp *http.Response) (resu // Parameters: // tagName - the name of the tag. func (client TagsClient) Delete(ctx context.Context, tagName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.DeletePreparer(ctx, tagName) if err != nil { err = autorest.NewErrorWithError(err, "resources.TagsClient", "Delete", nil, "Failure preparing request") @@ -219,8 +250,8 @@ func (client TagsClient) DeletePreparer(ctx context.Context, tagName string) (*h // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // DeleteResponder handles the response to the Delete request. The method always @@ -240,6 +271,16 @@ func (client TagsClient) DeleteResponder(resp *http.Response) (result autorest.R // tagName - the name of the tag. // tagValue - the value of the tag. func (client TagsClient) DeleteValue(ctx context.Context, tagName string, tagValue string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.DeleteValue") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.DeleteValuePreparer(ctx, tagName, tagValue) if err != nil { err = autorest.NewErrorWithError(err, "resources.TagsClient", "DeleteValue", nil, "Failure preparing request") @@ -285,8 +326,8 @@ func (client TagsClient) DeleteValuePreparer(ctx context.Context, tagName string // DeleteValueSender sends the DeleteValue request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) DeleteValueSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // DeleteValueResponder handles the response to the DeleteValue request. The method always @@ -303,6 +344,16 @@ func (client TagsClient) DeleteValueResponder(resp *http.Response) (result autor // List get a list of subscription resource tags. func (client TagsClient) List(ctx context.Context) (result TagsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.List") + defer func() { + sc := -1 + if result.tlr.Response.Response != nil { + sc = result.tlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { @@ -347,8 +398,8 @@ func (client TagsClient) ListPreparer(ctx context.Context) (*http.Request, error // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -365,8 +416,8 @@ func (client TagsClient) ListResponder(resp *http.Response) (result TagsListResu } // listNextResults retrieves the next set of results, if any. -func (client TagsClient) listNextResults(lastResults TagsListResult) (result TagsListResult, err error) { - req, err := lastResults.tagsListResultPreparer() +func (client TagsClient) listNextResults(ctx context.Context, lastResults TagsListResult) (result TagsListResult, err error) { + req, err := lastResults.tagsListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.TagsClient", "listNextResults", nil, "Failure preparing next results request") } @@ -387,6 +438,16 @@ func (client TagsClient) listNextResults(lastResults TagsListResult) (result Tag // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client TagsClient) ListComplete(ctx context.Context) (result TagsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TagsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } result.page, err = client.List(ctx) return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/accounts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/accounts.go index b9d2cbd99..4d553ca22 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/accounts.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/accounts.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -45,6 +46,16 @@ func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) Account // accountName - the name of the storage account within the specified resource group. Storage account names // must be between 3 and 24 characters in length and use numbers and lower-case letters only. func (client AccountsClient) CheckNameAvailability(ctx context.Context, accountName AccountCheckNameAvailabilityParameters) (result CheckNameAvailabilityResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName.Name", Name: validation.Null, Rule: true, Chain: nil}, @@ -97,8 +108,8 @@ func (client AccountsClient) CheckNameAvailabilityPreparer(ctx context.Context, // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always @@ -124,6 +135,16 @@ func (client AccountsClient) CheckNameAvailabilityResponder(resp *http.Response) // must be between 3 and 24 characters in length and use numbers and lower-case letters only. // parameters - the parameters to provide for the created account. func (client AccountsClient) Create(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (result AccountsCreateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Create") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -181,13 +202,9 @@ func (client AccountsClient) CreatePreparer(ctx context.Context, resourceGroupNa // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) CreateSender(req *http.Request) (future AccountsCreateFuture, err error) { + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } @@ -214,6 +231,16 @@ func (client AccountsClient) CreateResponder(resp *http.Response) (result Accoun // accountName - the name of the storage account within the specified resource group. Storage account names // must be between 3 and 24 characters in length and use numbers and lower-case letters only. func (client AccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -266,8 +293,8 @@ func (client AccountsClient) DeletePreparer(ctx context.Context, resourceGroupNa // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // DeleteResponder handles the response to the Delete request. The method always @@ -289,6 +316,16 @@ func (client AccountsClient) DeleteResponder(resp *http.Response) (result autore // accountName - the name of the storage account within the specified resource group. Storage account names // must be between 3 and 24 characters in length and use numbers and lower-case letters only. func (client AccountsClient) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (result Account, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.GetProperties") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -341,8 +378,8 @@ func (client AccountsClient) GetPropertiesPreparer(ctx context.Context, resource // GetPropertiesSender sends the GetProperties request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // GetPropertiesResponder handles the response to the GetProperties request. The method always @@ -361,6 +398,16 @@ func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result // List lists all the storage accounts available under the subscription. Note that storage keys are not returned; use // the ListKeys operation for this. func (client AccountsClient) List(ctx context.Context) (result AccountListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "storage.AccountsClient", "List", nil, "Failure preparing request") @@ -404,8 +451,8 @@ func (client AccountsClient) ListPreparer(ctx context.Context) (*http.Request, e // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always @@ -426,6 +473,16 @@ func (client AccountsClient) ListResponder(resp *http.Response) (result AccountL // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. func (client AccountsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result AccountListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request") @@ -470,8 +527,8 @@ func (client AccountsClient) ListByResourceGroupPreparer(ctx context.Context, re // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always @@ -493,6 +550,16 @@ func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) ( // accountName - the name of the storage account within the specified resource group. Storage account names // must be between 3 and 24 characters in length and use numbers and lower-case letters only. func (client AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result AccountListKeysResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.ListKeys") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -545,8 +612,8 @@ func (client AccountsClient) ListKeysPreparer(ctx context.Context, resourceGroup // ListKeysSender sends the ListKeys request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListKeysSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListKeysResponder handles the response to the ListKeys request. The method always @@ -569,6 +636,16 @@ func (client AccountsClient) ListKeysResponder(resp *http.Response) (result Acco // must be between 3 and 24 characters in length and use numbers and lower-case letters only. // regenerateKey - specifies name of the key which should be regenerated -- key1 or key2. func (client AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters) (result AccountListKeysResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.RegenerateKey") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -625,8 +702,8 @@ func (client AccountsClient) RegenerateKeyPreparer(ctx context.Context, resource // RegenerateKeySender sends the RegenerateKey request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) RegenerateKeySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // RegenerateKeyResponder handles the response to the RegenerateKey request. The method always @@ -654,6 +731,16 @@ func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result // must be between 3 and 24 characters in length and use numbers and lower-case letters only. // parameters - the parameters to provide for the updated account. func (client AccountsClient) Update(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, @@ -708,8 +795,8 @@ func (client AccountsClient) UpdatePreparer(ctx context.Context, resourceGroupNa // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // UpdateResponder handles the response to the Update request. The method always diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/models.go index 4fdf467fa..f8dbdc078 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/models.go @@ -18,6 +18,7 @@ package storage // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( + "context" "encoding/json" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" @@ -25,6 +26,9 @@ import ( "net/http" ) +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage" + // AccessTier enumerates the values for access tier. type AccessTier string @@ -179,16 +183,16 @@ func PossibleUsageUnitValues() []UsageUnit { // Account the storage account. type Account struct { autorest.Response `json:"-"` - // Sku - Gets the SKU. + // Sku - READ-ONLY; Gets the SKU. Sku *Sku `json:"sku,omitempty"` - // Kind - Gets the Kind. Possible values include: 'Storage', 'BlobStorage' + // Kind - READ-ONLY; Gets the Kind. Possible values include: 'Storage', 'BlobStorage' Kind Kind `json:"kind,omitempty"` *AccountProperties `json:"properties,omitempty"` - // ID - Resource Id + // ID - READ-ONLY; Resource Id ID *string `json:"id,omitempty"` - // Name - Resource name + // Name - READ-ONLY; Resource name Name *string `json:"name,omitempty"` - // Type - Resource type + // Type - READ-ONLY; Resource type Type *string `json:"type,omitempty"` // Location - Resource location Location *string `json:"location,omitempty"` @@ -199,24 +203,9 @@ type Account struct { // MarshalJSON is the custom marshaler for Account. func (a Account) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if a.Sku != nil { - objectMap["sku"] = a.Sku - } - if a.Kind != "" { - objectMap["kind"] = a.Kind - } if a.AccountProperties != nil { objectMap["properties"] = a.AccountProperties } - if a.ID != nil { - objectMap["id"] = a.ID - } - if a.Name != nil { - objectMap["name"] = a.Name - } - if a.Type != nil { - objectMap["type"] = a.Type - } if a.Location != nil { objectMap["location"] = a.Location } @@ -415,53 +404,53 @@ func (acp *AccountCreateParameters) UnmarshalJSON(body []byte) error { // AccountKey an access key for the storage account. type AccountKey struct { - // KeyName - Name of the key. + // KeyName - READ-ONLY; Name of the key. KeyName *string `json:"keyName,omitempty"` - // Value - Base 64-encoded value of the key. + // Value - READ-ONLY; Base 64-encoded value of the key. Value *string `json:"value,omitempty"` - // Permissions - Permissions for the key -- read-only or full permissions. Possible values include: 'READ', 'FULL' + // Permissions - READ-ONLY; Permissions for the key -- read-only or full permissions. Possible values include: 'READ', 'FULL' Permissions KeyPermission `json:"permissions,omitempty"` } // AccountListKeysResult the response from the ListKeys operation. type AccountListKeysResult struct { autorest.Response `json:"-"` - // Keys - Gets the list of storage account keys and their properties for the specified storage account. + // Keys - READ-ONLY; Gets the list of storage account keys and their properties for the specified storage account. Keys *[]AccountKey `json:"keys,omitempty"` } // AccountListResult the response from the List Storage Accounts operation. type AccountListResult struct { autorest.Response `json:"-"` - // Value - Gets the list of storage accounts and their properties. + // Value - READ-ONLY; Gets the list of storage accounts and their properties. Value *[]Account `json:"value,omitempty"` } // AccountProperties ... type AccountProperties struct { - // ProvisioningState - Gets the status of the storage account at the time the operation was called. Possible values include: 'Creating', 'ResolvingDNS', 'Succeeded' + // ProvisioningState - READ-ONLY; Gets the status of the storage account at the time the operation was called. Possible values include: 'Creating', 'ResolvingDNS', 'Succeeded' ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrimaryEndpoints - Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object. Note that Standard_ZRS and Premium_LRS accounts only return the blob endpoint. + // PrimaryEndpoints - READ-ONLY; Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object. Note that Standard_ZRS and Premium_LRS accounts only return the blob endpoint. PrimaryEndpoints *Endpoints `json:"primaryEndpoints,omitempty"` - // PrimaryLocation - Gets the location of the primary data center for the storage account. + // PrimaryLocation - READ-ONLY; Gets the location of the primary data center for the storage account. PrimaryLocation *string `json:"primaryLocation,omitempty"` - // StatusOfPrimary - Gets the status indicating whether the primary location of the storage account is available or unavailable. Possible values include: 'Available', 'Unavailable' + // StatusOfPrimary - READ-ONLY; Gets the status indicating whether the primary location of the storage account is available or unavailable. Possible values include: 'Available', 'Unavailable' StatusOfPrimary AccountStatus `json:"statusOfPrimary,omitempty"` - // LastGeoFailoverTime - Gets the timestamp of the most recent instance of a failover to the secondary location. Only the most recent timestamp is retained. This element is not returned if there has never been a failover instance. Only available if the accountType is Standard_GRS or Standard_RAGRS. + // LastGeoFailoverTime - READ-ONLY; Gets the timestamp of the most recent instance of a failover to the secondary location. Only the most recent timestamp is retained. This element is not returned if there has never been a failover instance. Only available if the accountType is Standard_GRS or Standard_RAGRS. LastGeoFailoverTime *date.Time `json:"lastGeoFailoverTime,omitempty"` - // SecondaryLocation - Gets the location of the geo-replicated secondary for the storage account. Only available if the accountType is Standard_GRS or Standard_RAGRS. + // SecondaryLocation - READ-ONLY; Gets the location of the geo-replicated secondary for the storage account. Only available if the accountType is Standard_GRS or Standard_RAGRS. SecondaryLocation *string `json:"secondaryLocation,omitempty"` - // StatusOfSecondary - Gets the status indicating whether the secondary location of the storage account is available or unavailable. Only available if the SKU name is Standard_GRS or Standard_RAGRS. Possible values include: 'Available', 'Unavailable' + // StatusOfSecondary - READ-ONLY; Gets the status indicating whether the secondary location of the storage account is available or unavailable. Only available if the SKU name is Standard_GRS or Standard_RAGRS. Possible values include: 'Available', 'Unavailable' StatusOfSecondary AccountStatus `json:"statusOfSecondary,omitempty"` - // CreationTime - Gets the creation date and time of the storage account in UTC. + // CreationTime - READ-ONLY; Gets the creation date and time of the storage account in UTC. CreationTime *date.Time `json:"creationTime,omitempty"` - // CustomDomain - Gets the custom domain the user assigned to this storage account. + // CustomDomain - READ-ONLY; Gets the custom domain the user assigned to this storage account. CustomDomain *CustomDomain `json:"customDomain,omitempty"` - // SecondaryEndpoints - Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object from the secondary location of the storage account. Only available if the SKU name is Standard_RAGRS. + // SecondaryEndpoints - READ-ONLY; Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object from the secondary location of the storage account. Only available if the SKU name is Standard_RAGRS. SecondaryEndpoints *Endpoints `json:"secondaryEndpoints,omitempty"` - // Encryption - Gets the encryption settings on the account. If unspecified, the account is unencrypted. + // Encryption - READ-ONLY; Gets the encryption settings on the account. If unspecified, the account is unencrypted. Encryption *Encryption `json:"encryption,omitempty"` - // AccessTier - Required for storage accounts where kind = BlobStorage. The access tier used for billing. Possible values include: 'Hot', 'Cool' + // AccessTier - READ-ONLY; Required for storage accounts where kind = BlobStorage. The access tier used for billing. Possible values include: 'Hot', 'Cool' AccessTier AccessTier `json:"accessTier,omitempty"` } @@ -490,7 +479,8 @@ type AccountRegenerateKeyParameters struct { KeyName *string `json:"keyName,omitempty"` } -// AccountsCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +// AccountsCreateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. type AccountsCreateFuture struct { azure.Future } @@ -499,7 +489,7 @@ type AccountsCreateFuture struct { // If the operation has not completed it will return an error. func (future *AccountsCreateFuture) Result(client AccountsClient) (a Account, err error) { var done bool - done, err = future.Done(client) + done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "storage.AccountsCreateFuture", "Result", future.Response(), "Polling failure") return @@ -518,7 +508,8 @@ func (future *AccountsCreateFuture) Result(client AccountsClient) (a Account, er return } -// AccountUpdateParameters the parameters that can be provided when updating the storage account properties. +// AccountUpdateParameters the parameters that can be provided when updating the storage account +// properties. type AccountUpdateParameters struct { // Sku - Gets or sets the SKU name. Note that the SKU name cannot be updated to Standard_ZRS or Premium_LRS, nor can accounts of those sku names be updated to any other value. Sku *Sku `json:"sku,omitempty"` @@ -587,11 +578,11 @@ func (aup *AccountUpdateParameters) UnmarshalJSON(body []byte) error { // CheckNameAvailabilityResult the CheckNameAvailability operation response. type CheckNameAvailabilityResult struct { autorest.Response `json:"-"` - // NameAvailable - Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or is invalid and cannot be used. + // NameAvailable - READ-ONLY; Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or is invalid and cannot be used. NameAvailable *bool `json:"nameAvailable,omitempty"` - // Reason - Gets the reason that a storage account name could not be used. The Reason element is only returned if NameAvailable is false. Possible values include: 'AccountNameInvalid', 'AlreadyExists' + // Reason - READ-ONLY; Gets the reason that a storage account name could not be used. The Reason element is only returned if NameAvailable is false. Possible values include: 'AccountNameInvalid', 'AlreadyExists' Reason Reason `json:"reason,omitempty"` - // Message - Gets an error message explaining the Reason value in more detail. + // Message - READ-ONLY; Gets an error message explaining the Reason value in more detail. Message *string `json:"message,omitempty"` } @@ -599,8 +590,8 @@ type CheckNameAvailabilityResult struct { type CustomDomain struct { // Name - Gets or sets the custom domain name assigned to the storage account. Name is the CNAME source. Name *string `json:"name,omitempty"` - // UseSubDomain - Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates. - UseSubDomain *bool `json:"useSubDomain,omitempty"` + // UseSubDomainName - Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates. + UseSubDomainName *bool `json:"useSubDomainName,omitempty"` } // Encryption the encryption settings on the storage account. @@ -615,7 +606,7 @@ type Encryption struct { type EncryptionService struct { // Enabled - A boolean indicating whether or not the service encrypts the data as it is stored. Enabled *bool `json:"enabled,omitempty"` - // LastEnabledTime - Gets a rough estimate of the date/time when the encryption was last enabled by the user. Only returned when encryption is enabled. There might be some unencrypted blobs which were written after this time, as it is just a rough estimate. + // LastEnabledTime - READ-ONLY; Gets a rough estimate of the date/time when the encryption was last enabled by the user. Only returned when encryption is enabled. There might be some unencrypted blobs which were written after this time, as it is just a rough estimate. LastEnabledTime *date.Time `json:"lastEnabledTime,omitempty"` } @@ -627,23 +618,23 @@ type EncryptionServices struct { // Endpoints the URIs that are used to perform a retrieval of a public blob, queue, or table object. type Endpoints struct { - // Blob - Gets the blob endpoint. + // Blob - READ-ONLY; Gets the blob endpoint. Blob *string `json:"blob,omitempty"` - // Queue - Gets the queue endpoint. + // Queue - READ-ONLY; Gets the queue endpoint. Queue *string `json:"queue,omitempty"` - // Table - Gets the table endpoint. + // Table - READ-ONLY; Gets the table endpoint. Table *string `json:"table,omitempty"` - // File - Gets the file endpoint. + // File - READ-ONLY; Gets the file endpoint. File *string `json:"file,omitempty"` } // Resource ... type Resource struct { - // ID - Resource Id + // ID - READ-ONLY; Resource Id ID *string `json:"id,omitempty"` - // Name - Resource name + // Name - READ-ONLY; Resource name Name *string `json:"name,omitempty"` - // Type - Resource type + // Type - READ-ONLY; Resource type Type *string `json:"type,omitempty"` // Location - Resource location Location *string `json:"location,omitempty"` @@ -654,15 +645,6 @@ type Resource struct { // MarshalJSON is the custom marshaler for Resource. func (r Resource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } if r.Location != nil { objectMap["location"] = r.Location } @@ -676,19 +658,19 @@ func (r Resource) MarshalJSON() ([]byte, error) { type Sku struct { // Name - Gets or sets the sku name. Required for account creation; optional for update. Note that in older versions, sku name was called accountType. Possible values include: 'StandardLRS', 'StandardGRS', 'StandardRAGRS', 'StandardZRS', 'PremiumLRS' Name SkuName `json:"name,omitempty"` - // Tier - Gets the sku tier. This is based on the SKU name. Possible values include: 'Standard', 'Premium' + // Tier - READ-ONLY; Gets the sku tier. This is based on the SKU name. Possible values include: 'Standard', 'Premium' Tier SkuTier `json:"tier,omitempty"` } // Usage describes Storage Resource Usage. type Usage struct { - // Unit - Gets the unit of measurement. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond' + // Unit - READ-ONLY; Gets the unit of measurement. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond' Unit UsageUnit `json:"unit,omitempty"` - // CurrentValue - Gets the current count of the allocated resources in the subscription. + // CurrentValue - READ-ONLY; Gets the current count of the allocated resources in the subscription. CurrentValue *int32 `json:"currentValue,omitempty"` - // Limit - Gets the maximum count of the resources that can be allocated in the subscription. + // Limit - READ-ONLY; Gets the maximum count of the resources that can be allocated in the subscription. Limit *int32 `json:"limit,omitempty"` - // Name - Gets the name of the type of usage. + // Name - READ-ONLY; Gets the name of the type of usage. Name *UsageName `json:"name,omitempty"` } @@ -701,8 +683,8 @@ type UsageListResult struct { // UsageName the usage names that can be used; currently limited to StorageAccount. type UsageName struct { - // Value - Gets a string describing the resource name. + // Value - READ-ONLY; Gets a string describing the resource name. Value *string `json:"value,omitempty"` - // LocalizedValue - Gets a localized string describing the resource name. + // LocalizedValue - READ-ONLY; Gets a localized string describing the resource name. LocalizedValue *string `json:"localizedValue,omitempty"` } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/usage.go b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/usage.go index 1c136faf7..cc6ce3315 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/usage.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage/usage.go @@ -21,6 +21,7 @@ import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" "net/http" ) @@ -41,6 +42,16 @@ func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClien // List gets the current usage count and the limit for the resources under the subscription. func (client UsageClient) List(ctx context.Context) (result UsageListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsageClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "storage.UsageClient", "List", nil, "Failure preparing request") @@ -84,8 +95,8 @@ func (client UsageClient) ListPreparer(ctx context.Context) (*http.Request, erro // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client UsageClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) + return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go index 31894dbfc..62e461a55 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go @@ -107,7 +107,7 @@ func (c *Client) blobAndFileSASURI(options SASOptions, uri, permissions, canonic if options.UseHTTPS { protocols = "https" } - stringToSign, err := blobSASStringToSign(permissions, start, expiry, canonicalizedResource, options.Identifier, options.IP, protocols, c.apiVersion, headers) + stringToSign, err := blobSASStringToSign(permissions, start, expiry, canonicalizedResource, options.Identifier, options.IP, protocols, c.apiVersion, signedResource, "", headers) if err != nil { return "", err } @@ -149,7 +149,7 @@ func (c *Client) blobAndFileSASURI(options SASOptions, uri, permissions, canonic return sasURL.String(), nil } -func blobSASStringToSign(signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion string, headers OverrideHeaders) (string, error) { +func blobSASStringToSign(signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion, signedResource, signedSnapshotTime string, headers OverrideHeaders) (string, error) { rscc := headers.CacheControl rscd := headers.ContentDisposition rsce := headers.ContentEncoding @@ -160,6 +160,11 @@ func blobSASStringToSign(signedPermissions, signedStart, signedExpiry, canonical canonicalizedResource = "/blob" + canonicalizedResource } + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + if signedVersion >= "2018-11-09" { + return fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion, signedResource, signedSnapshotTime, rscc, rscd, rsce, rscl, rsct), nil + } + // https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx#Anchor_12 if signedVersion >= "2015-04-05" { return fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion, rscc, rscd, rsce, rscl, rsct), nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go index c9c62d799..bd19eccc4 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go @@ -197,6 +197,47 @@ func (b *Blob) PutBlockWithLength(blockID string, size uint64, blob io.Reader, o return b.respondCreation(resp, BlobTypeBlock) } +// PutBlockFromURLOptions includes the options for a put block from URL operation +type PutBlockFromURLOptions struct { + PutBlockOptions + + SourceContentMD5 string `header:"x-ms-source-content-md5"` + SourceContentCRC64 string `header:"x-ms-source-content-crc64"` +} + +// PutBlockFromURL copy data of exactly specified size from specified URL to +// the block blob with given ID. It is an alternative to PutBlocks where data +// comes from a remote URL and the offset and length is known in advance. +// +// The API rejects requests with size > 100 MiB (but this limit is not +// checked by the SDK). +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url +func (b *Blob) PutBlockFromURL(blockID string, blobURL string, offset int64, size uint64, options *PutBlockFromURLOptions) error { + query := url.Values{ + "comp": {"block"}, + "blockid": {blockID}, + } + headers := b.Container.bsc.client.getStandardHeaders() + // The value of this header must be set to zero. + // When the length is not zero, the operation will fail with the status code 400 (Bad Request). + headers["Content-Length"] = "0" + headers["x-ms-copy-source"] = blobURL + headers["x-ms-source-range"] = fmt.Sprintf("bytes=%d-%d", offset, uint64(offset)+size-1) + + if options != nil { + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), query) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return err + } + return b.respondCreation(resp, BlobTypeBlock) +} + // PutBlockListOptions includes the options for a put block list operation type PutBlockListOptions struct { Timeout uint diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go index 427558b5d..99702effe 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go @@ -46,7 +46,7 @@ const ( // DefaultAPIVersion is the Azure Storage API version string used when a // basic client is created. - DefaultAPIVersion = "2016-05-31" + DefaultAPIVersion = "2018-03-28" defaultUseHTTPS = true defaultRetryAttempts = 5 @@ -367,11 +367,14 @@ func newSASClient(accountName, baseURL string, sasToken url.Values) Client { accountName: accountName, baseURL: baseURL, accountSASToken: sasToken, + useHTTPS: defaultUseHTTPS, } c.userAgent = c.getDefaultUserAgent() // Get API version and protocol from token c.apiVersion = sasToken.Get("sv") - c.useHTTPS = sasToken.Get("spr") == "https" + if spr := sasToken.Get("spr"); spr != "" { + c.useHTTPS = spr == "https" + } return c } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go index fbbcb93ba..385253527 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go @@ -27,7 +27,7 @@ import ( "strings" "time" - "github.com/satori/go.uuid" + uuid "github.com/satori/go.uuid" ) // Annotating as secure for gas scanning @@ -257,6 +257,9 @@ func (e *Entity) MarshalJSON() ([]byte, error) { case int64: completeMap[typeKey] = OdataInt64 completeMap[k] = fmt.Sprintf("%v", v) + case float32, float64: + completeMap[typeKey] = OdataDouble + completeMap[k] = fmt.Sprintf("%v", v) default: completeMap[k] = v } @@ -264,7 +267,8 @@ func (e *Entity) MarshalJSON() ([]byte, error) { if !(completeMap[k] == OdataBinary || completeMap[k] == OdataDateTime || completeMap[k] == OdataGUID || - completeMap[k] == OdataInt64) { + completeMap[k] == OdataInt64 || + completeMap[k] == OdataDouble) { return nil, fmt.Errorf("Odata.type annotation %v value is not valid", k) } valueKey := strings.TrimSuffix(k, OdataTypeSuffix) @@ -339,6 +343,12 @@ func (e *Entity) UnmarshalJSON(data []byte) error { return fmt.Errorf(errorTemplate, err) } props[valueKey] = i + case OdataDouble: + f, err := strconv.ParseFloat(str, 64) + if err != nil { + return fmt.Errorf(errorTemplate, err) + } + props[valueKey] = f default: return fmt.Errorf(errorTemplate, fmt.Sprintf("%v is not supported", v)) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go index 06bbe4ba0..6a480b12a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go @@ -29,7 +29,11 @@ const fourMB = uint64(4194304) const oneTB = uint64(1099511627776) // Export maximum range and file sizes + +// MaxRangeSize defines the maximum size in bytes for a file range. const MaxRangeSize = fourMB + +// MaxFileSize defines the maximum size in bytes for a file. const MaxFileSize = oneTB // File represents a file on a share. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go index 800adf129..0690e85ad 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go @@ -26,6 +26,7 @@ const ( OdataBinary = "Edm.Binary" OdataDateTime = "Edm.DateTime" + OdataDouble = "Edm.Double" OdataGUID = "Edm.Guid" OdataInt64 = "Edm.Int64" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go index c338975ab..dc4199222 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go @@ -22,10 +22,12 @@ import ( // ServiceProperties represents the storage account service properties type ServiceProperties struct { - Logging *Logging - HourMetrics *Metrics - MinuteMetrics *Metrics - Cors *Cors + Logging *Logging + HourMetrics *Metrics + MinuteMetrics *Metrics + Cors *Cors + DeleteRetentionPolicy *RetentionPolicy // blob storage only + StaticWebsite *StaticWebsite // blob storage only } // Logging represents the Azure Analytics Logging settings @@ -65,6 +67,16 @@ type CorsRule struct { AllowedHeaders string } +// StaticWebsite - The properties that enable an account to host a static website +type StaticWebsite struct { + // Enabled - Indicates whether this account is hosting a static website + Enabled bool + // IndexDocument - The default name of the index page under each directory + IndexDocument *string + // ErrorDocument404Path - The absolute path of the custom 404 page + ErrorDocument404Path *string +} + func (c Client) getServiceProperties(service string, auth authentication) (*ServiceProperties, error) { query := url.Values{ "restype": {"service"}, @@ -102,10 +114,12 @@ func (c Client) setServiceProperties(props ServiceProperties, service string, au // Ideally, StorageServiceProperties would be the output struct // This is to avoid golint stuttering, while generating the correct XML type StorageServiceProperties struct { - Logging *Logging - HourMetrics *Metrics - MinuteMetrics *Metrics - Cors *Cors + Logging *Logging + HourMetrics *Metrics + MinuteMetrics *Metrics + Cors *Cors + DeleteRetentionPolicy *RetentionPolicy + StaticWebsite *StaticWebsite } input := StorageServiceProperties{ Logging: props.Logging, @@ -113,6 +127,11 @@ func (c Client) setServiceProperties(props ServiceProperties, service string, au MinuteMetrics: props.MinuteMetrics, Cors: props.Cors, } + // only set these fields for blob storage else it's invalid XML + if service == blobServiceName { + input.DeleteRetentionPolicy = props.DeleteRetentionPolicy + input.StaticWebsite = props.StaticWebsite + } body, length, err := xmlMarshal(input) if err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go index 22d9b4f5c..0febf077f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go @@ -355,8 +355,12 @@ func (t *Table) queryEntities(uri string, headers map[string]string, ml Metadata return nil, err } v := originalURI.Query() - v.Set(nextPartitionKeyQueryParameter, contToken.NextPartitionKey) - v.Set(nextRowKeyQueryParameter, contToken.NextRowKey) + if contToken.NextPartitionKey != "" { + v.Set(nextPartitionKeyQueryParameter, contToken.NextPartitionKey) + } + if contToken.NextRowKey != "" { + v.Set(nextRowKeyQueryParameter, contToken.NextRowKey) + } newURI := t.tsc.client.getEndpoint(tableServiceName, t.buildPath(), v) entities.NextLink = &newURI entities.ml = ml @@ -371,7 +375,7 @@ func extractContinuationTokenFromHeaders(h http.Header) *continuationToken { NextRowKey: h.Get(headerNextRowKey), } - if ct.NextPartitionKey != "" && ct.NextRowKey != "" { + if ct.NextPartitionKey != "" || ct.NextRowKey != "" { return &ct } return nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go index a2159e296..5b05e3e2a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go @@ -25,8 +25,6 @@ import ( "net/textproto" "sort" "strings" - - "github.com/marstr/guid" ) // Operation type. Insert, Delete, Replace etc. @@ -132,8 +130,7 @@ func (t *TableBatch) MergeEntity(entity *Entity) { // As per document https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/performing-entity-group-transactions func (t *TableBatch) ExecuteBatch() error { - // Using `github.com/marstr/guid` is in response to issue #947 (https://github.com/Azure/azure-sdk-for-go/issues/947). - id, err := guid.NewGUIDs(guid.CreationStrategyVersion1) + id, err := newUUID() if err != nil { return err } @@ -145,7 +142,7 @@ func (t *TableBatch) ExecuteBatch() error { return err } - id, err = guid.NewGUIDs(guid.CreationStrategyVersion1) + id, err = newUUID() if err != nil { return err } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go index e8a5dcf8c..677394790 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go @@ -17,6 +17,7 @@ package storage import ( "bytes" "crypto/hmac" + "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/xml" @@ -29,6 +30,8 @@ import ( "strconv" "strings" "time" + + uuid "github.com/satori/go.uuid" ) var ( @@ -242,3 +245,16 @@ func getMetadataFromHeaders(header http.Header) map[string]string { return metadata } + +// newUUID returns a new uuid using RFC 4122 algorithm. +func newUUID() (uuid.UUID, error) { + u := [16]byte{} + // Set all bits to randomly (or pseudo-randomly) chosen values. + _, err := rand.Read(u[:]) + if err != nil { + return uuid.UUID{}, err + } + u[8] = (u[8]&(0xff>>2) | (0x02 << 6)) // u.setVariant(ReservedRFC4122) + u[6] = (u[6] & 0xF) | (uuid.V4 << 4) // u.setVersion(V4) + return uuid.FromBytes(u[:]) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go index 7f0f6f2b6..073281bb8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go @@ -18,4 +18,4 @@ package version // Changes may cause incorrect behavior and will be lost if the code is regenerated. // Number contains the semantic version of this SDK. -const Number = "v21.3.0" +const Number = "v36.2.0" diff --git a/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/LICENSE similarity index 100% rename from vendor/github.com/Azure/go-autorest/LICENSE rename to vendor/github.com/Azure/go-autorest/autorest/LICENSE diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md index 7b0c4bc4d..fec416a9c 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md @@ -135,7 +135,7 @@ resource := "https://management.core.windows.net/" applicationSecret := "APPLICATION_SECRET" spt, err := adal.NewServicePrincipalToken( - oauthConfig, + *oauthConfig, appliationID, applicationSecret, resource, @@ -170,7 +170,7 @@ if err != nil { } spt, err := adal.NewServicePrincipalTokenFromCertificate( - oauthConfig, + *oauthConfig, applicationID, certificate, rsaPrivateKey, @@ -195,7 +195,7 @@ oauthClient := &http.Client{} // Acquire the device code deviceCode, err := adal.InitiateDeviceAuth( oauthClient, - oauthConfig, + *oauthConfig, applicationID, resource) if err != nil { @@ -212,7 +212,7 @@ if err != nil { } spt, err := adal.NewServicePrincipalTokenFromManualToken( - oauthConfig, + *oauthConfig, applicationID, resource, *token, @@ -227,7 +227,7 @@ if (err == nil) { ```Go spt, err := adal.NewServicePrincipalTokenFromUsernamePassword( - oauthConfig, + *oauthConfig, applicationID, username, password, @@ -243,11 +243,11 @@ if (err == nil) { ``` Go spt, err := adal.NewServicePrincipalTokenFromAuthorizationCode( - oauthConfig, + *oauthConfig, applicationID, clientSecret, - authorizationCode, - redirectURI, + authorizationCode, + redirectURI, resource, callbacks...) diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go index bee5e61dd..fa5964742 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go @@ -15,12 +15,13 @@ package adal // limitations under the License. import ( + "errors" "fmt" "net/url" ) const ( - activeDirectoryAPIVersion = "1.0" + activeDirectoryEndpointTemplate = "%s/oauth2/%s%s" ) // OAuthConfig represents the endpoints needed @@ -46,11 +47,24 @@ func validateStringParam(param, name string) error { // NewOAuthConfig returns an OAuthConfig with tenant specific urls func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { + apiVer := "1.0" + return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer) +} + +// NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls. +// If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value. +func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) { if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { return nil, err } + api := "" // it's legal for tenantID to be empty so don't validate it - const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s" + if apiVersion != nil { + if err := validateStringParam(*apiVersion, "apiVersion"); err != nil { + return nil, err + } + api = fmt.Sprintf("?api-version=%s", *apiVersion) + } u, err := url.Parse(activeDirectoryEndpoint) if err != nil { return nil, err @@ -59,15 +73,15 @@ func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, err if err != nil { return nil, err } - authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", activeDirectoryAPIVersion)) + authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api)) if err != nil { return nil, err } - tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", activeDirectoryAPIVersion)) + tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api)) if err != nil { return nil, err } - deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", activeDirectoryAPIVersion)) + deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api)) if err != nil { return nil, err } @@ -79,3 +93,59 @@ func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, err DeviceCodeEndpoint: *deviceCodeURL, }, nil } + +// MultiTenantOAuthConfig provides endpoints for primary and aulixiary tenant IDs. +type MultiTenantOAuthConfig interface { + PrimaryTenant() *OAuthConfig + AuxiliaryTenants() []*OAuthConfig +} + +// OAuthOptions contains optional OAuthConfig creation arguments. +type OAuthOptions struct { + APIVersion string +} + +func (c OAuthOptions) apiVersion() string { + if c.APIVersion != "" { + return fmt.Sprintf("?api-version=%s", c.APIVersion) + } + return "1.0" +} + +// NewMultiTenantOAuthConfig creates an object that support multitenant OAuth configuration. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/authenticate-multi-tenant for more information. +func NewMultiTenantOAuthConfig(activeDirectoryEndpoint, primaryTenantID string, auxiliaryTenantIDs []string, options OAuthOptions) (MultiTenantOAuthConfig, error) { + if len(auxiliaryTenantIDs) == 0 || len(auxiliaryTenantIDs) > 3 { + return nil, errors.New("must specify one to three auxiliary tenants") + } + mtCfg := multiTenantOAuthConfig{ + cfgs: make([]*OAuthConfig, len(auxiliaryTenantIDs)+1), + } + apiVer := options.apiVersion() + pri, err := NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, primaryTenantID, &apiVer) + if err != nil { + return nil, fmt.Errorf("failed to create OAuthConfig for primary tenant: %v", err) + } + mtCfg.cfgs[0] = pri + for i := range auxiliaryTenantIDs { + aux, err := NewOAuthConfig(activeDirectoryEndpoint, auxiliaryTenantIDs[i]) + if err != nil { + return nil, fmt.Errorf("failed to create OAuthConfig for tenant '%s': %v", auxiliaryTenantIDs[i], err) + } + mtCfg.cfgs[i+1] = aux + } + return mtCfg, nil +} + +type multiTenantOAuthConfig struct { + // first config in the slice is the primary tenant + cfgs []*OAuthConfig +} + +func (m multiTenantOAuthConfig) PrimaryTenant() *OAuthConfig { + return m.cfgs[0] +} + +func (m multiTenantOAuthConfig) AuxiliaryTenants() []*OAuthConfig { + return m.cfgs[1:] +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go index b38f4c245..914f8af5e 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go @@ -24,6 +24,7 @@ package adal */ import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -101,7 +102,14 @@ type deviceToken struct { // InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode // that can be used with CheckForUserCompletion or WaitForUserCompletion. +// Deprecated: use InitiateDeviceAuthWithContext() instead. func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { + return InitiateDeviceAuthWithContext(context.Background(), sender, oauthConfig, clientID, resource) +} + +// InitiateDeviceAuthWithContext initiates a device auth flow. It returns a DeviceCode +// that can be used with CheckForUserCompletion or WaitForUserCompletion. +func InitiateDeviceAuthWithContext(ctx context.Context, sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { v := url.Values{ "client_id": []string{clientID}, "resource": []string{resource}, @@ -117,7 +125,7 @@ func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resour req.ContentLength = int64(len(s)) req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) + resp, err := sender.Do(req.WithContext(ctx)) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) } @@ -151,7 +159,14 @@ func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resour // CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint // to see if the device flow has: been completed, timed out, or otherwise failed +// Deprecated: use CheckForUserCompletionWithContext() instead. func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { + return CheckForUserCompletionWithContext(context.Background(), sender, code) +} + +// CheckForUserCompletionWithContext takes a DeviceCode and checks with the Azure AD OAuth endpoint +// to see if the device flow has: been completed, timed out, or otherwise failed +func CheckForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { v := url.Values{ "client_id": []string{code.ClientID}, "code": []string{*code.DeviceCode}, @@ -169,7 +184,7 @@ func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { req.ContentLength = int64(len(s)) req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) + resp, err := sender.Do(req.WithContext(ctx)) if err != nil { return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) } @@ -213,12 +228,19 @@ func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { // WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. // This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. +// Deprecated: use WaitForUserCompletionWithContext() instead. func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { + return WaitForUserCompletionWithContext(context.Background(), sender, code) +} + +// WaitForUserCompletionWithContext calls CheckForUserCompletion repeatedly until a token is granted or an error +// state occurs. This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. +func WaitForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { intervalDuration := time.Duration(*code.Interval) * time.Second waitDuration := intervalDuration for { - token, err := CheckForUserCompletion(sender, code) + token, err := CheckForUserCompletionWithContext(ctx, sender, code) if err == nil { return token, nil @@ -237,6 +259,11 @@ func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) } - time.Sleep(waitDuration) + select { + case <-time.After(waitDuration): + // noop + case <-ctx.Done(): + return nil, ctx.Err() + } } } diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/go.mod b/vendor/github.com/Azure/go-autorest/autorest/adal/go.mod new file mode 100644 index 000000000..fdc5b90ca --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/go.mod @@ -0,0 +1,12 @@ +module github.com/Azure/go-autorest/autorest/adal + +go 1.12 + +require ( + github.com/Azure/go-autorest/autorest v0.9.0 + github.com/Azure/go-autorest/autorest/date v0.2.0 + github.com/Azure/go-autorest/autorest/mocks v0.3.0 + github.com/Azure/go-autorest/tracing v0.5.0 + github.com/dgrijalva/jwt-go v3.2.0+incompatible + golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 +) diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/go.sum b/vendor/github.com/Azure/go-autorest/autorest/adal/go.sum new file mode 100644 index 000000000..f0a018563 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/go.sum @@ -0,0 +1,23 @@ +github.com/Azure/go-autorest/autorest v0.9.0 h1:MRvx8gncNaXJqOoLmhNjUAKh33JJF8LyxPhomEtOsjs= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/date v0.2.0 h1:yW+Zlqf26583pE43KhfnhFcdmSWlm5Ew6bxipnr/tbM= +github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= +github.com/Azure/go-autorest/autorest/mocks v0.1.0 h1:Kx+AUU2Te+A3JIyYn6Dfs+cFgx5XorQKuIXrZGoq/SI= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0 h1:Ww5g4zThfD/6cLb4z6xxgeyDa7QDkizMkJKe0ysZXp0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.3.0 h1:qJumjCaCudz+OcqE9/XtEPfvtOjOmKaui4EOpFI6zZc= +github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go new file mode 100644 index 000000000..28a4bfc4c --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go @@ -0,0 +1,24 @@ +// +build modhack + +package adal + +// Copyright 2017 Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file, and the github.com/Azure/go-autorest/autorest import, won't actually become part of +// the resultant binary. + +// Necessary for safely adding multi-module repo. +// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go index 0e5ad14d3..d7e4372bb 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go @@ -15,7 +15,12 @@ package adal // limitations under the License. import ( + "crypto/tls" "net/http" + "net/http/cookiejar" + "sync" + + "github.com/Azure/go-autorest/tracing" ) const ( @@ -23,6 +28,9 @@ const ( mimeTypeFormPost = "application/x-www-form-urlencoded" ) +var defaultSender Sender +var defaultSenderInit = &sync.Once{} + // Sender is the interface that wraps the Do method to send HTTP requests. // // The standard http.Client conforms to this interface. @@ -38,14 +46,14 @@ func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { return sf(r) } -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the +// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the // http.Request and pass it along or, first, pass the http.Request along then react to the // http.Response result. type SendDecorator func(Sender) Sender // CreateSender creates, decorates, and returns, as a Sender, the default http.Client. func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) + return DecorateSender(sender(), decorators...) } // DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to @@ -58,3 +66,30 @@ func DecorateSender(s Sender, decorators ...SendDecorator) Sender { } return s } + +func sender() Sender { + // note that we can't init defaultSender in init() since it will + // execute before calling code has had a chance to enable tracing + defaultSenderInit.Do(func() { + // Use behaviour compatible with DefaultTransport, but require TLS minimum version. + defaultTransport := http.DefaultTransport.(*http.Transport) + transport := &http.Transport{ + Proxy: defaultTransport.Proxy, + DialContext: defaultTransport.DialContext, + MaxIdleConns: defaultTransport.MaxIdleConns, + IdleConnTimeout: defaultTransport.IdleConnTimeout, + TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout, + ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + }, + } + var roundTripper http.RoundTripper = transport + if tracing.IsEnabled() { + roundTripper = tracing.NewTransport(transport) + } + j, _ := cookiejar.New(nil) + defaultSender = &http.Client{Jar: j, Transport: roundTripper} + }) + return defaultSender +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go index 32aea8389..33bbd6ea1 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go @@ -26,16 +26,14 @@ import ( "fmt" "io/ioutil" "math" - "net" "net/http" "net/url" - "strconv" + "os" "strings" "sync" "time" "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/version" "github.com/dgrijalva/jwt-go" ) @@ -65,6 +63,12 @@ const ( // the default number of attempts to refresh an MSI authentication token defaultMaxMSIRefreshAttempts = 5 + + // asMSIEndpointEnv is the environment variable used to store the endpoint on App Service and Functions + asMSIEndpointEnv = "MSI_ENDPOINT" + + // asMSISecretEnv is the environment variable used to store the request secret on App Service and Functions + asMSISecretEnv = "MSI_SECRET" ) // OAuthTokenProvider is an interface which should be implemented by an access token retriever @@ -72,6 +76,12 @@ type OAuthTokenProvider interface { OAuthToken() string } +// MultitenantOAuthTokenProvider provides tokens used for multi-tenant authorization. +type MultitenantOAuthTokenProvider interface { + PrimaryOAuthToken() string + AuxiliaryOAuthTokens() []string +} + // TokenRefreshError is an interface used by errors returned during token refresh. type TokenRefreshError interface { error @@ -96,19 +106,31 @@ type RefresherWithContext interface { // a successful token refresh type TokenRefreshCallback func(Token) error +// TokenRefresh is a type representing a custom callback to refresh a token +type TokenRefresh func(ctx context.Context, resource string) (*Token, error) + // Token encapsulates the access token used to authorize Azure requests. +// https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow#service-to-service-access-token-response type Token struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` - ExpiresIn string `json:"expires_in"` - ExpiresOn string `json:"expires_on"` - NotBefore string `json:"not_before"` + ExpiresIn json.Number `json:"expires_in"` + ExpiresOn json.Number `json:"expires_on"` + NotBefore json.Number `json:"not_before"` Resource string `json:"resource"` Type string `json:"token_type"` } +func newToken() Token { + return Token{ + ExpiresIn: "0", + ExpiresOn: "0", + NotBefore: "0", + } +} + // IsZero returns true if the token object is zero-initialized. func (t Token) IsZero() bool { return t == Token{} @@ -116,12 +138,12 @@ func (t Token) IsZero() bool { // Expires returns the time.Time when the Token expires. func (t Token) Expires() time.Time { - s, err := strconv.Atoi(t.ExpiresOn) + s, err := t.ExpiresOn.Float64() if err != nil { s = -3600 } - expiration := date.NewUnixTimeFromSeconds(float64(s)) + expiration := date.NewUnixTimeFromSeconds(s) return time.Time(expiration).UTC() } @@ -218,6 +240,8 @@ func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalTo token := jwt.New(jwt.SigningMethodRS256) token.Header["x5t"] = thumbprint + x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)} + token.Header["x5c"] = x5c token.Claims = jwt.MapClaims{ "aud": spt.inner.OauthConfig.TokenEndpoint.String(), "iss": spt.inner.ClientID, @@ -323,10 +347,11 @@ func (secret ServicePrincipalAuthorizationCodeSecret) MarshalJSON() ([]byte, err // ServicePrincipalToken encapsulates a Token created for a Service Principal. type ServicePrincipalToken struct { - inner servicePrincipalToken - refreshLock *sync.RWMutex - sender Sender - refreshCallbacks []TokenRefreshCallback + inner servicePrincipalToken + refreshLock *sync.RWMutex + sender Sender + customRefreshFunc TokenRefresh + refreshCallbacks []TokenRefreshCallback // MaxMSIRefreshAttempts is the maximum number of attempts to refresh an MSI token. MaxMSIRefreshAttempts int } @@ -341,6 +366,11 @@ func (spt *ServicePrincipalToken) SetRefreshCallbacks(callbacks []TokenRefreshCa spt.refreshCallbacks = callbacks } +// SetCustomRefreshFunc sets a custom refresh function used to refresh the token. +func (spt *ServicePrincipalToken) SetCustomRefreshFunc(customRefreshFunc TokenRefresh) { + spt.customRefreshFunc = customRefreshFunc +} + // MarshalJSON implements the json.Marshaler interface. func (spt ServicePrincipalToken) MarshalJSON() ([]byte, error) { return json.Marshal(spt.inner) @@ -375,8 +405,13 @@ func (spt *ServicePrincipalToken) UnmarshalJSON(data []byte) error { if err != nil { return err } - spt.refreshLock = &sync.RWMutex{} - spt.sender = &http.Client{} + // Don't override the refreshLock or the sender if those have been already set. + if spt.refreshLock == nil { + spt.refreshLock = &sync.RWMutex{} + } + if spt.sender == nil { + spt.sender = sender() + } return nil } @@ -414,6 +449,7 @@ func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, reso } spt := &ServicePrincipalToken{ inner: servicePrincipalToken{ + Token: newToken(), OauthConfig: oauthConfig, Secret: secret, ClientID: id, @@ -422,7 +458,7 @@ func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, reso RefreshWithin: defaultRefresh, }, refreshLock: &sync.RWMutex{}, - sender: &http.Client{}, + sender: sender(), refreshCallbacks: callbacks, } return spt, nil @@ -613,6 +649,31 @@ func GetMSIVMEndpoint() (string, error) { return msiEndpoint, nil } +func isAppService() bool { + _, asMSIEndpointEnvExists := os.LookupEnv(asMSIEndpointEnv) + _, asMSISecretEnvExists := os.LookupEnv(asMSISecretEnv) + + return asMSIEndpointEnvExists && asMSISecretEnvExists +} + +// GetMSIAppServiceEndpoint get the MSI endpoint for App Service and Functions +func GetMSIAppServiceEndpoint() (string, error) { + asMSIEndpoint, asMSIEndpointEnvExists := os.LookupEnv(asMSIEndpointEnv) + + if asMSIEndpointEnvExists { + return asMSIEndpoint, nil + } + return "", errors.New("MSI endpoint not found") +} + +// GetMSIEndpoint get the appropriate MSI endpoint depending on the runtime environment +func GetMSIEndpoint() (string, error) { + if isAppService() { + return GetMSIAppServiceEndpoint() + } + return GetMSIVMEndpoint() +} + // NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. // It will use the system assigned identity when creating the token. func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { @@ -645,7 +706,12 @@ func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedI v := url.Values{} v.Set("resource", resource) - v.Set("api-version", "2018-02-01") + // App Service MSI currently only supports token API version 2017-09-01 + if isAppService() { + v.Set("api-version", "2017-09-01") + } else { + v.Set("api-version", "2018-02-01") + } if userAssignedID != nil { v.Set("client_id", *userAssignedID) } @@ -653,6 +719,7 @@ func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedI spt := &ServicePrincipalToken{ inner: servicePrincipalToken{ + Token: newToken(), OauthConfig: OAuthConfig{ TokenEndpoint: *msiEndpointURL, }, @@ -662,7 +729,7 @@ func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedI RefreshWithin: defaultRefresh, }, refreshLock: &sync.RWMutex{}, - sender: &http.Client{}, + sender: sender(), refreshCallbacks: callbacks, MaxMSIRefreshAttempts: defaultMaxMSIRefreshAttempts, } @@ -728,13 +795,13 @@ func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { } // Refresh obtains a fresh token for the Service Principal. -// This method is not safe for concurrent use and should be syncrhonized. +// This method is safe for concurrent use. func (spt *ServicePrincipalToken) Refresh() error { return spt.RefreshWithContext(context.Background()) } // RefreshWithContext obtains a fresh token for the Service Principal. -// This method is not safe for concurrent use and should be syncrhonized. +// This method is safe for concurrent use. func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() @@ -742,13 +809,13 @@ func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error } // RefreshExchange refreshes the token, but for a different resource. -// This method is not safe for concurrent use and should be syncrhonized. +// This method is safe for concurrent use. func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { return spt.RefreshExchangeWithContext(context.Background(), resource) } // RefreshExchangeWithContext refreshes the token, but for a different resource. -// This method is not safe for concurrent use and should be syncrhonized. +// This method is safe for concurrent use. func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { spt.refreshLock.Lock() defer spt.refreshLock.Unlock() @@ -771,15 +838,29 @@ func isIMDS(u url.URL) bool { if err != nil { return false } - return u.Host == imds.Host && u.Path == imds.Path + return (u.Host == imds.Host && u.Path == imds.Path) || isAppService() } func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource string) error { + if spt.customRefreshFunc != nil { + token, err := spt.customRefreshFunc(ctx, resource) + if err != nil { + return err + } + spt.inner.Token = *token + return spt.InvokeRefreshCallbacks(spt.inner.Token) + } + req, err := http.NewRequest(http.MethodPost, spt.inner.OauthConfig.TokenEndpoint.String(), nil) if err != nil { return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) } - req.Header.Add("User-Agent", version.UserAgent()) + req.Header.Add("User-Agent", UserAgent()) + // Add header when runtime is on App Service or Functions + if isAppService() { + asMSISecret, _ := os.LookupEnv(asMSISecretEnv) + req.Header.Add("Secret", asMSISecret) + } req = req.WithContext(ctx) if !isIMDS(spt.inner.OauthConfig.TokenEndpoint) { v := url.Values{} @@ -824,7 +905,8 @@ func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource resp, err = spt.sender.Do(req) } if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Failed to execute the refresh request. Error = '%v'", err), nil) + // don't return a TokenRefreshError here; this will allow retry logic to apply + return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err) } defer resp.Body.Close() @@ -891,10 +973,8 @@ func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http for attempt < maxAttempts { resp, err = sender.Do(req) - // retry on temporary network errors, e.g. transient network failures. - // if we don't receive a response then assume we can't connect to the - // endpoint so we're likely not running on an Azure VM so don't retry. - if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) { + // we want to retry if err is not nil or the status code is in the list of retry codes + if err == nil && !responseHasStatusCode(resp, retries...) { return } @@ -918,20 +998,12 @@ func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http return } -// returns true if the specified error is a temporary network error or false if it's not. -// if the error doesn't implement the net.Error interface the return value is true. -func isTemporaryNetworkError(err error) bool { - if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { - return true - } - return false -} - -// returns true if slice ints contains the value n -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true +func responseHasStatusCode(resp *http.Response, codes ...int) bool { + if resp != nil { + for _, i := range codes { + if i == resp.StatusCode { + return true + } } } return false @@ -966,3 +1038,93 @@ func (spt *ServicePrincipalToken) Token() Token { defer spt.refreshLock.RUnlock() return spt.inner.Token } + +// MultiTenantServicePrincipalToken contains tokens for multi-tenant authorization. +type MultiTenantServicePrincipalToken struct { + PrimaryToken *ServicePrincipalToken + AuxiliaryTokens []*ServicePrincipalToken +} + +// PrimaryOAuthToken returns the primary authorization token. +func (mt *MultiTenantServicePrincipalToken) PrimaryOAuthToken() string { + return mt.PrimaryToken.OAuthToken() +} + +// AuxiliaryOAuthTokens returns one to three auxiliary authorization tokens. +func (mt *MultiTenantServicePrincipalToken) AuxiliaryOAuthTokens() []string { + tokens := make([]string, len(mt.AuxiliaryTokens)) + for i := range mt.AuxiliaryTokens { + tokens[i] = mt.AuxiliaryTokens[i].OAuthToken() + } + return tokens +} + +// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by +// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. +func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { + if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil { + return fmt.Errorf("failed to refresh primary token: %v", err) + } + for _, aux := range mt.AuxiliaryTokens { + if err := aux.EnsureFreshWithContext(ctx); err != nil { + return fmt.Errorf("failed to refresh auxiliary token: %v", err) + } + } + return nil +} + +// RefreshWithContext obtains a fresh token for the Service Principal. +func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error { + if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil { + return fmt.Errorf("failed to refresh primary token: %v", err) + } + for _, aux := range mt.AuxiliaryTokens { + if err := aux.RefreshWithContext(ctx); err != nil { + return fmt.Errorf("failed to refresh auxiliary token: %v", err) + } + } + return nil +} + +// RefreshExchangeWithContext refreshes the token, but for a different resource. +func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { + if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil { + return fmt.Errorf("failed to refresh primary token: %v", err) + } + for _, aux := range mt.AuxiliaryTokens { + if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil { + return fmt.Errorf("failed to refresh auxiliary token: %v", err) + } + } + return nil +} + +// NewMultiTenantServicePrincipalToken creates a new MultiTenantServicePrincipalToken with the specified credentials and resource. +func NewMultiTenantServicePrincipalToken(multiTenantCfg MultiTenantOAuthConfig, clientID string, secret string, resource string) (*MultiTenantServicePrincipalToken, error) { + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(secret, "secret"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + auxTenants := multiTenantCfg.AuxiliaryTenants() + m := MultiTenantServicePrincipalToken{ + AuxiliaryTokens: make([]*ServicePrincipalToken, len(auxTenants)), + } + primary, err := NewServicePrincipalToken(*multiTenantCfg.PrimaryTenant(), clientID, secret, resource) + if err != nil { + return nil, fmt.Errorf("failed to create SPT for primary tenant: %v", err) + } + m.PrimaryToken = primary + for i := range auxTenants { + aux, err := NewServicePrincipalToken(*auxTenants[i], clientID, secret, resource) + if err != nil { + return nil, fmt.Errorf("failed to create SPT for auxiliary tenant: %v", err) + } + m.AuxiliaryTokens[i] = aux + } + return &m, nil +} diff --git a/vendor/github.com/Azure/go-autorest/version/version.go b/vendor/github.com/Azure/go-autorest/autorest/adal/version.go similarity index 65% rename from vendor/github.com/Azure/go-autorest/version/version.go rename to vendor/github.com/Azure/go-autorest/autorest/adal/version.go index ad2d6099f..c867b3484 100644 --- a/vendor/github.com/Azure/go-autorest/version/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/version.go @@ -1,4 +1,9 @@ -package version +package adal + +import ( + "fmt" + "runtime" +) // Copyright 2017 Microsoft Corporation // @@ -14,24 +19,27 @@ package version // See the License for the specific language governing permissions and // limitations under the License. -import ( - "fmt" - "runtime" -) - -// Number contains the semantic version of this SDK. -const Number = "v10.15.4" +const number = "v1.0.0" var ( - userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", + ua = fmt.Sprintf("Go/%s (%s-%s) go-autorest/adal/%s", runtime.Version(), runtime.GOARCH, runtime.GOOS, - Number, + number, ) ) -// UserAgent returns a string containing the Go version, system archityecture and OS, and the go-autorest version. +// UserAgent returns a string containing the Go version, system architecture and OS, and the adal version. func UserAgent() string { - return userAgent + return ua +} + +// AddToUserAgent adds an extension to the current user agent +func AddToUserAgent(extension string) error { + if extension != "" { + ua = fmt.Sprintf("%s %s", ua, extension) + return nil + } + return fmt.Errorf("Extension was empty, User Agent remained as '%s'", ua) } diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go index 77eff45bd..54e87b5b6 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ b/vendor/github.com/Azure/go-autorest/autorest/authorization.go @@ -15,6 +15,8 @@ package autorest // limitations under the License. import ( + "crypto/tls" + "encoding/base64" "fmt" "net/http" "net/url" @@ -30,6 +32,8 @@ const ( apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" bingAPISdkHeader = "X-BingApis-SDK-Client" golangBingAPISdkHeaderValue = "Go-SDK" + authorization = "Authorization" + basic = "Basic" ) // Authorizer is the interface that provides a PrepareDecorator used to supply request @@ -68,7 +72,7 @@ func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[str return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} } -// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Paramaters +// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Parameters. func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { return func(p Preparer) Preparer { return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) @@ -145,11 +149,11 @@ type BearerAuthorizerCallback struct { // NewBearerAuthorizerCallback creates a bearer authorization callback. The callback // is invoked when the HTTP request is submitted. -func NewBearerAuthorizerCallback(sender Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { - if sender == nil { - sender = &http.Client{} +func NewBearerAuthorizerCallback(s Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { + if s == nil { + s = sender(tls.RenegotiateNever) } - return &BearerAuthorizerCallback{sender: sender, callback: callback} + return &BearerAuthorizerCallback{sender: s, callback: callback} } // WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value @@ -257,3 +261,76 @@ func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { } return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() } + +// BasicAuthorizer implements basic HTTP authorization by adding the Authorization HTTP header +// with the value "Basic " where is a base64-encoded username:password tuple. +type BasicAuthorizer struct { + userName string + password string +} + +// NewBasicAuthorizer creates a new BasicAuthorizer with the specified username and password. +func NewBasicAuthorizer(userName, password string) *BasicAuthorizer { + return &BasicAuthorizer{ + userName: userName, + password: password, + } +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose +// value is "Basic " followed by the base64-encoded username:password tuple. +func (ba *BasicAuthorizer) WithAuthorization() PrepareDecorator { + headers := make(map[string]interface{}) + headers[authorization] = basic + " " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.userName, ba.password))) + + return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() +} + +// MultiTenantServicePrincipalTokenAuthorizer provides authentication across tenants. +type MultiTenantServicePrincipalTokenAuthorizer interface { + WithAuthorization() PrepareDecorator +} + +// NewMultiTenantServicePrincipalTokenAuthorizer crates a BearerAuthorizer using the given token provider +func NewMultiTenantServicePrincipalTokenAuthorizer(tp adal.MultitenantOAuthTokenProvider) MultiTenantServicePrincipalTokenAuthorizer { + return &multiTenantSPTAuthorizer{tp: tp} +} + +type multiTenantSPTAuthorizer struct { + tp adal.MultitenantOAuthTokenProvider +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header using the +// primary token along with the auxiliary authorization header using the auxiliary tokens. +// +// By default, the token will be automatically refreshed through the Refresher interface. +func (mt multiTenantSPTAuthorizer) WithAuthorization() PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err != nil { + return r, err + } + if refresher, ok := mt.tp.(adal.RefresherWithContext); ok { + err = refresher.EnsureFreshWithContext(r.Context()) + if err != nil { + var resp *http.Response + if tokError, ok := err.(adal.TokenRefreshError); ok { + resp = tokError.Response() + } + return r, NewErrorWithError(err, "azure.multiTenantSPTAuthorizer", "WithAuthorization", resp, + "Failed to refresh one or more Tokens for request to %s", r.URL) + } + } + r, err = Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", mt.tp.PrimaryOAuthToken()))) + if err != nil { + return r, err + } + auxTokens := mt.tp.AuxiliaryOAuthTokens() + for i := range auxTokens { + auxTokens[i] = fmt.Sprintf("Bearer %s", auxTokens[i]) + } + return Prepare(r, WithHeader(headerAuxAuthorization, strings.Join(auxTokens, "; "))) + }) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go index 9dd7a1d27..1cb41cbeb 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -26,6 +26,7 @@ import ( "time" "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/tracing" ) const ( @@ -44,24 +45,14 @@ var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.Stat // Future provides a mechanism to access the status and results of an asynchronous request. // Since futures are stateful they should be passed by value to avoid race conditions. type Future struct { - req *http.Request // legacy - pt pollingTracker -} - -// NewFuture returns a new Future object initialized with the specified request. -// Deprecated: Please use NewFutureFromResponse instead. -func NewFuture(req *http.Request) Future { - return Future{req: req} + pt pollingTracker } // NewFutureFromResponse returns a new Future object initialized // with the initial response from an asynchronous operation. func NewFutureFromResponse(resp *http.Response) (Future, error) { pt, err := createPollingTracker(resp) - if err != nil { - return Future{}, err - } - return Future{pt: pt}, nil + return Future{pt: pt}, err } // Response returns the last HTTP response. @@ -88,29 +79,25 @@ func (f Future) PollingMethod() PollingMethodType { return f.pt.pollingMethod() } -// Done queries the service to see if the operation has completed. -func (f *Future) Done(sender autorest.Sender) (bool, error) { - // support for legacy Future implementation - if f.req != nil { - resp, err := sender.Do(f.req) - if err != nil { - return false, err +// DoneWithContext queries the service to see if the operation has completed. +func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) { + ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext") + defer func() { + sc := -1 + resp := f.Response() + if resp != nil { + sc = resp.StatusCode } - pt, err := createPollingTracker(resp) - if err != nil { - return false, err - } - f.pt = pt - f.req = nil - } - // end legacy + tracing.EndSpan(ctx, sc, err) + }() + if f.pt == nil { return false, autorest.NewError("Future", "Done", "future is not initialized") } if f.pt.hasTerminated() { return true, f.pt.pollingError() } - if err := f.pt.pollForStatus(sender); err != nil { + if err := f.pt.pollForStatus(ctx, sender); err != nil { return false, err } if err := f.pt.checkForErrors(); err != nil { @@ -154,24 +141,35 @@ func (f Future) GetPollingDelay() (time.Duration, bool) { return d, true } -// WaitForCompletion will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -// Deprecated: Please use WaitForCompletionRef() instead. -func (f Future) WaitForCompletion(ctx context.Context, client autorest.Client) error { - return f.WaitForCompletionRef(ctx, client) -} - // WaitForCompletionRef will return when one of the following conditions is met: the long // running operation has completed, the provided context is cancelled, or the client's // polling duration has been exceeded. It will retry failed polling attempts based on // the retry value defined in the client up to the maximum retry attempts. -func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Client) error { - ctx, cancel := context.WithTimeout(ctx, client.PollingDuration) - defer cancel() - done, err := f.Done(client) - for attempts := 0; !done; done, err = f.Done(client) { +// If no deadline is specified in the context then the client.PollingDuration will be +// used to determine if a default deadline should be used. +// If PollingDuration is greater than zero the value will be used as the context's timeout. +// If PollingDuration is zero then no default deadline will be used. +func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Client) (err error) { + ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.WaitForCompletionRef") + defer func() { + sc := -1 + resp := f.Response() + if resp != nil { + sc = resp.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + cancelCtx := ctx + // if the provided context already has a deadline don't override it + _, hasDeadline := ctx.Deadline() + if d := client.PollingDuration; !hasDeadline && d != 0 { + var cancel context.CancelFunc + cancelCtx, cancel = context.WithTimeout(ctx, d) + defer cancel() + } + + done, err := f.DoneWithContext(ctx, client) + for attempts := 0; !done; done, err = f.DoneWithContext(ctx, client) { if attempts >= client.RetryAttempts { return autorest.NewErrorWithError(err, "Future", "WaitForCompletion", f.pt.latestResponse(), "the number of retries has been exceeded") } @@ -195,12 +193,12 @@ func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Clien attempts++ } // wait until the delay elapses or the context is cancelled - delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, ctx.Done()) + delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, cancelCtx.Done()) if !delayElapsed { - return autorest.NewErrorWithError(ctx.Err(), "Future", "WaitForCompletion", f.pt.latestResponse(), "context has been cancelled") + return autorest.NewErrorWithError(cancelCtx.Err(), "Future", "WaitForCompletion", f.pt.latestResponse(), "context has been cancelled") } } - return err + return } // MarshalJSON implements the json.Marshaler interface. @@ -285,7 +283,7 @@ type pollingTracker interface { initializeState() error // makes an HTTP request to check the status of the LRO - pollForStatus(sender autorest.Sender) error + pollForStatus(ctx context.Context, sender autorest.Sender) error // updates internal tracker state, call this after each call to pollForStatus updatePollingState(provStateApl bool) error @@ -399,6 +397,10 @@ func (pt *pollingTrackerBase) updateRawBody() error { if err != nil { return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to read response body") } + // observed in 204 responses over HTTP/2.0; the content length is -1 but body is empty + if len(b) == 0 { + return nil + } // put the body back so it's available to other callers pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) if err = json.Unmarshal(b, &pt.rawBody); err != nil { @@ -408,14 +410,17 @@ func (pt *pollingTrackerBase) updateRawBody() error { return nil } -func (pt *pollingTrackerBase) pollForStatus(sender autorest.Sender) error { +func (pt *pollingTrackerBase) pollForStatus(ctx context.Context, sender autorest.Sender) error { req, err := http.NewRequest(http.MethodGet, pt.URI, nil) if err != nil { return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to create HTTP request") } - // attach the context from the original request if available (it will be absent for deserialized futures) - if pt.resp != nil { - req = req.WithContext(pt.resp.Request.Context()) + + req = req.WithContext(ctx) + preparer := autorest.CreatePreparer(autorest.GetPrepareDecorators(ctx)...) + req, err = preparer.Prepare(req) + if err != nil { + return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed preparing HTTP request") } pt.resp, err = sender.Do(req) if err != nil { @@ -445,7 +450,7 @@ func (pt *pollingTrackerBase) updateErrorFromResponse() { re := respErr{} defer pt.resp.Body.Close() var b []byte - if b, err = ioutil.ReadAll(pt.resp.Body); err != nil { + if b, err = ioutil.ReadAll(pt.resp.Body); err != nil || len(b) == 0 { goto Default } if err = json.Unmarshal(b, &re); err != nil { @@ -663,7 +668,7 @@ func (pt *pollingTrackerPatch) updatePollingMethod() error { } } // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - // note the absense of the "final GET" mechanism for PATCH + // note the absence of the "final GET" mechanism for PATCH if pt.resp.StatusCode == http.StatusAccepted { ao, err := getURLFromAsyncOpHeader(pt.resp) if err != nil { @@ -794,8 +799,6 @@ func (pt *pollingTrackerPut) updatePollingMethod() error { pt.URI = lh pt.Pm = PollingLocation } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh } // make sure a polling URL was found if pt.URI == "" { @@ -885,43 +888,6 @@ func isValidURL(s string) bool { return err == nil && u.IsAbs() } -// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure -// long-running operation. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled via -// the context associated with the http.Request. -// Deprecated: Prefer using Futures to allow for non-blocking async operations. -func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - return resp, err - } - if !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { - return resp, nil - } - future, err := NewFutureFromResponse(resp) - if err != nil { - return resp, err - } - // retry until either the LRO completes or we receive an error - var done bool - for done, err = future.Done(s); !done && err == nil; done, err = future.Done(s) { - // check for Retry-After delay, if not present use the specified polling delay - if pd, ok := future.GetPollingDelay(); ok { - delay = pd - } - // wait until the delay elapses or the context is cancelled - if delayElapsed := autorest.DelayForBackoff(delay, 0, r.Context().Done()); !delayElapsed { - return future.Response(), - autorest.NewErrorWithError(r.Context().Err(), "azure", "DoPollForAsynchronous", future.Response(), "context has been cancelled") - } - } - return future.Response(), err - }) - } -} - // PollingMethodType defines a type used for enumerating polling mechanisms. type PollingMethodType string diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.mod b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.mod new file mode 100644 index 000000000..cef48f1ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.mod @@ -0,0 +1,10 @@ +module github.com/Azure/go-autorest/autorest/azure/cli + +go 1.12 + +require ( + github.com/Azure/go-autorest/autorest/adal v0.5.0 + github.com/Azure/go-autorest/autorest/date v0.1.0 + github.com/dimchansky/utfbom v1.1.0 + github.com/mitchellh/go-homedir v1.1.0 +) diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.sum b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.sum new file mode 100644 index 000000000..2d6636a33 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go.sum @@ -0,0 +1,17 @@ +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0 h1:Kx+AUU2Te+A3JIyYn6Dfs+cFgx5XorQKuIXrZGoq/SI= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4= +github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go index b62bf03ba..a336b958d 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go @@ -19,6 +19,8 @@ import ( "encoding/json" "fmt" "io/ioutil" + "os" + "path/filepath" "github.com/dimchansky/utfbom" "github.com/mitchellh/go-homedir" @@ -47,9 +49,14 @@ type User struct { Type string `json:"type"` } +const azureProfileJSON = "azureProfile.json" + // ProfilePath returns the path where the Azure Profile is stored from the Azure CLI func ProfilePath() (string, error) { - return homedir.Expand("~/.azure/azureProfile.json") + if cfgDir := os.Getenv("AZURE_CONFIG_DIR"); cfgDir != "" { + return filepath.Join(cfgDir, azureProfileJSON), nil + } + return homedir.Expand("~/.azure/" + azureProfileJSON) } // LoadProfile restores a Profile object from a file located at 'path'. diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go index 83b81c34b..810075ba6 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go @@ -15,9 +15,13 @@ package cli // limitations under the License. import ( + "bytes" "encoding/json" "fmt" "os" + "os/exec" + "regexp" + "runtime" "strconv" "time" @@ -54,7 +58,7 @@ func (t Token) ToADALToken() (converted adal.Token, err error) { AccessToken: t.AccessToken, Type: t.TokenType, ExpiresIn: "3600", - ExpiresOn: strconv.Itoa(int(difference.Seconds())), + ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))), RefreshToken: t.RefreshToken, Resource: t.Resource, } @@ -112,3 +116,55 @@ func LoadTokens(path string) ([]Token, error) { return tokens, nil } + +// GetTokenFromCLI gets a token using Azure CLI 2.0 for local development scenarios. +func GetTokenFromCLI(resource string) (*Token, error) { + // This is the path that a developer can set to tell this class what the install path for Azure CLI is. + const azureCLIPath = "AzureCLIPath" + + // The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI. + azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles")) + + // Default path for non-Windows. + const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin" + + // Validate resource, since it gets sent as a command line argument to Azure CLI + const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed." + match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) + if err != nil { + return nil, err + } + if !match { + return nil, fmt.Errorf(invalidResourceErrorTemplate, resource) + } + + // Execute Azure CLI to get token + var cliCmd *exec.Cmd + if runtime.GOOS == "windows" { + cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir"))) + cliCmd.Env = os.Environ() + cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) + cliCmd.Args = append(cliCmd.Args, "/c", "az") + } else { + cliCmd = exec.Command("az") + cliCmd.Env = os.Environ() + cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath)) + } + cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource) + + var stderr bytes.Buffer + cliCmd.Stderr = &stderr + + output, err := cliCmd.Output() + if err != nil { + return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String()) + } + + tokenResponse := Token{} + err = json.Unmarshal(output, &tokenResponse) + if err != nil { + return nil, err + } + + return &tokenResponse, err +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go index 7e41f7fd9..6c20b8179 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -22,9 +22,14 @@ import ( "strings" ) -// EnvironmentFilepathName captures the name of the environment variable containing the path to the file -// to be used while populating the Azure Environment. -const EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" +const ( + // EnvironmentFilepathName captures the name of the environment variable containing the path to the file + // to be used while populating the Azure Environment. + EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" + + // NotAvailable is used for endpoints and resource IDs that are not available for a given cloud. + NotAvailable = "N/A" +) var environments = map[string]Environment{ "AZURECHINACLOUD": ChinaCloud, @@ -33,28 +38,40 @@ var environments = map[string]Environment{ "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, } +// ResourceIdentifier contains a set of Azure resource IDs. +type ResourceIdentifier struct { + Graph string `json:"graph"` + KeyVault string `json:"keyVault"` + Datalake string `json:"datalake"` + Batch string `json:"batch"` + OperationalInsights string `json:"operationalInsights"` + Storage string `json:"storage"` +} + // Environment represents a set of endpoints for each of Azure's Clouds. type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - ServiceBusEndpoint string `json:"serviceBusEndpoint"` - BatchManagementEndpoint string `json:"batchManagementEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` - ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` - ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` - ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` - TokenAudience string `json:"tokenAudience"` + Name string `json:"name"` + ManagementPortalURL string `json:"managementPortalURL"` + PublishSettingsURL string `json:"publishSettingsURL"` + ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` + ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` + ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` + GalleryEndpoint string `json:"galleryEndpoint"` + KeyVaultEndpoint string `json:"keyVaultEndpoint"` + GraphEndpoint string `json:"graphEndpoint"` + ServiceBusEndpoint string `json:"serviceBusEndpoint"` + BatchManagementEndpoint string `json:"batchManagementEndpoint"` + StorageEndpointSuffix string `json:"storageEndpointSuffix"` + SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` + TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` + KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` + ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` + ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` + ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` + ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` + CosmosDBDNSSuffix string `json:"cosmosDBDNSSuffix"` + TokenAudience string `json:"tokenAudience"` + ResourceIdentifiers ResourceIdentifier `json:"resourceIdentifiers"` } var ( @@ -79,7 +96,16 @@ var ( ServiceManagementVMDNSSuffix: "cloudapp.net", ResourceManagerVMDNSSuffix: "cloudapp.azure.com", ContainerRegistryDNSSuffix: "azurecr.io", + CosmosDBDNSSuffix: "documents.azure.com", TokenAudience: "https://management.azure.com/", + ResourceIdentifiers: ResourceIdentifier{ + Graph: "https://graph.windows.net/", + KeyVault: "https://vault.azure.net", + Datalake: "https://datalake.azure.net/", + Batch: "https://batch.core.windows.net/", + OperationalInsights: "https://api.loganalytics.io", + Storage: "https://storage.azure.com/", + }, } // USGovernmentCloud is the cloud environment for the US Government @@ -102,8 +128,17 @@ var ( ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", ServiceManagementVMDNSSuffix: "usgovcloudapp.net", ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", - ContainerRegistryDNSSuffix: "azurecr.io", + ContainerRegistryDNSSuffix: "azurecr.us", + CosmosDBDNSSuffix: "documents.azure.us", TokenAudience: "https://management.usgovcloudapi.net/", + ResourceIdentifiers: ResourceIdentifier{ + Graph: "https://graph.windows.net/", + KeyVault: "https://vault.usgovcloudapi.net", + Datalake: NotAvailable, + Batch: "https://batch.core.usgovcloudapi.net/", + OperationalInsights: "https://api.loganalytics.us", + Storage: "https://storage.azure.com/", + }, } // ChinaCloud is the cloud environment operated in China @@ -126,8 +161,17 @@ var ( ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", ServiceManagementVMDNSSuffix: "chinacloudapp.cn", ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", - ContainerRegistryDNSSuffix: "azurecr.io", + ContainerRegistryDNSSuffix: "azurecr.cn", + CosmosDBDNSSuffix: "documents.azure.cn", TokenAudience: "https://management.chinacloudapi.cn/", + ResourceIdentifiers: ResourceIdentifier{ + Graph: "https://graph.chinacloudapi.cn/", + KeyVault: "https://vault.azure.cn", + Datalake: NotAvailable, + Batch: "https://batch.chinacloudapi.cn/", + OperationalInsights: NotAvailable, + Storage: "https://storage.azure.com/", + }, } // GermanCloud is the cloud environment operated in Germany @@ -150,8 +194,17 @@ var ( ServiceBusEndpointSuffix: "servicebus.cloudapi.de", ServiceManagementVMDNSSuffix: "azurecloudapp.de", ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", - ContainerRegistryDNSSuffix: "azurecr.io", + ContainerRegistryDNSSuffix: NotAvailable, + CosmosDBDNSSuffix: "documents.microsoftazure.de", TokenAudience: "https://management.microsoftazure.de/", + ResourceIdentifiers: ResourceIdentifier{ + Graph: "https://graph.cloudapi.de/", + KeyVault: "https://vault.microsoftazure.de", + Datalake: NotAvailable, + Batch: "https://batch.cloudapi.de/", + OperationalInsights: NotAvailable, + Storage: "https://storage.azure.com/", + }, } ) diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go index bd34f0ed5..86ce9f2b5 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go @@ -140,8 +140,8 @@ func register(client autorest.Client, originalReq *http.Request, re RequestError } // poll for registered provisioning state - now := time.Now() - for err == nil && time.Since(now) < client.PollingDuration { + registrationStartTime := time.Now() + for err == nil && (client.PollingDuration == 0 || (client.PollingDuration != 0 && time.Since(registrationStartTime) < client.PollingDuration)) { // taken from the resources SDK // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L45 preparer := autorest.CreatePreparer( @@ -183,7 +183,7 @@ func register(client autorest.Client, originalReq *http.Request, re RequestError return originalReq.Context().Err() } } - if !(time.Since(now) < client.PollingDuration) { + if client.PollingDuration != 0 && !(time.Since(registrationStartTime) < client.PollingDuration) { return errors.New("polling for resource provider registration has exceeded the polling duration") } return err diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go index 5c558c83a..1c6a0617a 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -16,17 +16,16 @@ package autorest import ( "bytes" + "crypto/tls" "fmt" "io" "io/ioutil" "log" "net/http" - "net/http/cookiejar" "strings" "time" "github.com/Azure/go-autorest/logger" - "github.com/Azure/go-autorest/version" ) const ( @@ -72,6 +71,22 @@ type Response struct { *http.Response `json:"-"` } +// IsHTTPStatus returns true if the returned HTTP status code matches the provided status code. +// If there was no response (i.e. the underlying http.Response is nil) the return value is false. +func (r Response) IsHTTPStatus(statusCode int) bool { + if r.Response == nil { + return false + } + return r.Response.StatusCode == statusCode +} + +// HasHTTPStatus returns true if the returned HTTP status code matches one of the provided status codes. +// If there was no response (i.e. the underlying http.Response is nil) or not status codes are provided +// the return value is false. +func (r Response) HasHTTPStatus(statusCodes ...int) bool { + return ResponseHasStatusCode(r.Response, statusCodes...) +} + // LoggingInspector implements request and response inspectors that log the full request and // response to a supplied log. type LoggingInspector struct { @@ -147,6 +162,7 @@ type Client struct { PollingDelay time.Duration // PollingDuration sets the maximum polling time after which an error is returned. + // Setting this to zero will use the provided context to control the duration. PollingDuration time.Duration // RetryAttempts sets the default number of retry attempts for client. @@ -168,14 +184,32 @@ type Client struct { // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed // string. func NewClientWithUserAgent(ua string) Client { + return newClient(ua, tls.RenegotiateNever) +} + +// ClientOptions contains various Client configuration options. +type ClientOptions struct { + // UserAgent is an optional user-agent string to append to the default user agent. + UserAgent string + + // Renegotiation is an optional setting to control client-side TLS renegotiation. + Renegotiation tls.RenegotiationSupport +} + +// NewClientWithOptions returns an instance of a Client with the specified values. +func NewClientWithOptions(options ClientOptions) Client { + return newClient(options.UserAgent, options.Renegotiation) +} + +func newClient(ua string, renegotiation tls.RenegotiationSupport) Client { c := Client{ PollingDelay: DefaultPollingDelay, PollingDuration: DefaultPollingDuration, RetryAttempts: DefaultRetryAttempts, RetryDuration: DefaultRetryDuration, - UserAgent: version.UserAgent(), + UserAgent: UserAgent(), } - c.Sender = c.sender() + c.Sender = c.sender(renegotiation) c.AddToUserAgent(ua) return c } @@ -219,17 +253,16 @@ func (c Client) Do(r *http.Request) (*http.Response, error) { return true, v }, }) - resp, err := SendWithSender(c.sender(), r) + resp, err := SendWithSender(c.sender(tls.RenegotiateNever), r) logger.Instance.WriteResponse(resp, logger.Filter{}) Respond(resp, c.ByInspecting()) return resp, err } // sender returns the Sender to which to send requests. -func (c Client) sender() Sender { +func (c Client) sender(renengotiation tls.RenegotiationSupport) Sender { if c.Sender == nil { - j, _ := cookiejar.New(nil) - return &http.Client{Jar: j} + return sender(renengotiation) } return c.Sender } diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/go.mod b/vendor/github.com/Azure/go-autorest/autorest/date/go.mod new file mode 100644 index 000000000..3adc4804c --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/go.mod @@ -0,0 +1,5 @@ +module github.com/Azure/go-autorest/autorest/date + +go 1.12 + +require github.com/Azure/go-autorest/autorest v0.9.0 diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/go.sum b/vendor/github.com/Azure/go-autorest/autorest/date/go.sum new file mode 100644 index 000000000..9e2ee7a94 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/go-autorest/autorest v0.9.0 h1:MRvx8gncNaXJqOoLmhNjUAKh33JJF8LyxPhomEtOsjs= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0 h1:Ww5g4zThfD/6cLb4z6xxgeyDa7QDkizMkJKe0ysZXp0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go new file mode 100644 index 000000000..55adf930f --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go @@ -0,0 +1,24 @@ +// +build modhack + +package date + +// Copyright 2017 Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file, and the github.com/Azure/go-autorest/autorest import, won't actually become part of +// the resultant binary. + +// Necessary for safely adding multi-module repo. +// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/go.mod b/vendor/github.com/Azure/go-autorest/autorest/go.mod new file mode 100644 index 000000000..ab2ae66ac --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/go.mod @@ -0,0 +1,11 @@ +module github.com/Azure/go-autorest/autorest + +go 1.12 + +require ( + github.com/Azure/go-autorest/autorest/adal v0.5.0 + github.com/Azure/go-autorest/autorest/mocks v0.2.0 + github.com/Azure/go-autorest/logger v0.1.0 + github.com/Azure/go-autorest/tracing v0.5.0 + golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 +) diff --git a/vendor/github.com/Azure/go-autorest/autorest/go.sum b/vendor/github.com/Azure/go-autorest/autorest/go.sum new file mode 100644 index 000000000..729b99cd0 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/go.sum @@ -0,0 +1,18 @@ +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0 h1:Kx+AUU2Te+A3JIyYn6Dfs+cFgx5XorQKuIXrZGoq/SI= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0 h1:Ww5g4zThfD/6cLb4z6xxgeyDa7QDkizMkJKe0ysZXp0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go index 6d67bd733..6e8ed64eb 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -16,7 +16,9 @@ package autorest import ( "bytes" + "context" "encoding/json" + "encoding/xml" "fmt" "io" "io/ioutil" @@ -31,11 +33,33 @@ const ( mimeTypeOctetStream = "application/octet-stream" mimeTypeFormPost = "application/x-www-form-urlencoded" - headerAuthorization = "Authorization" - headerContentType = "Content-Type" - headerUserAgent = "User-Agent" + headerAuthorization = "Authorization" + headerAuxAuthorization = "x-ms-authorization-auxiliary" + headerContentType = "Content-Type" + headerUserAgent = "User-Agent" ) +// used as a key type in context.WithValue() +type ctxPrepareDecorators struct{} + +// WithPrepareDecorators adds the specified PrepareDecorators to the provided context. +// If no PrepareDecorators are provided the context is unchanged. +func WithPrepareDecorators(ctx context.Context, prepareDecorator []PrepareDecorator) context.Context { + if len(prepareDecorator) == 0 { + return ctx + } + return context.WithValue(ctx, ctxPrepareDecorators{}, prepareDecorator) +} + +// GetPrepareDecorators returns the PrepareDecorators in the provided context or the provided default PrepareDecorators. +func GetPrepareDecorators(ctx context.Context, defaultPrepareDecorators ...PrepareDecorator) []PrepareDecorator { + inCtx := ctx.Value(ctxPrepareDecorators{}) + if pd, ok := inCtx.([]PrepareDecorator); ok { + return pd + } + return defaultPrepareDecorators +} + // Preparer is the interface that wraps the Prepare method. // // Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations @@ -190,6 +214,9 @@ func AsGet() PrepareDecorator { return WithMethod("GET") } // AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. func AsHead() PrepareDecorator { return WithMethod("HEAD") } +// AsMerge returns a PrepareDecorator that sets the HTTP method to MERGE. +func AsMerge() PrepareDecorator { return WithMethod("MERGE") } + // AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } @@ -225,6 +252,25 @@ func WithBaseURL(baseURL string) PrepareDecorator { } } +// WithBytes returns a PrepareDecorator that takes a list of bytes +// which passes the bytes directly to the body +func WithBytes(input *[]byte) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if input == nil { + return r, fmt.Errorf("Input Bytes was nil") + } + + r.ContentLength = int64(len(*input)) + r.Body = ioutil.NopCloser(bytes.NewReader(*input)) + } + return r, err + }) + } +} + // WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the // request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { @@ -377,6 +423,28 @@ func WithJSON(v interface{}) PrepareDecorator { } } +// WithXML returns a PrepareDecorator that encodes the data passed as XML into the body of the +// request and sets the Content-Length header. +func WithXML(v interface{}) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + b, err := xml.Marshal(v) + if err == nil { + // we have to tack on an XML header + withHeader := xml.Header + string(b) + bytesWithHeader := []byte(withHeader) + + r.ContentLength = int64(len(bytesWithHeader)) + r.Body = ioutil.NopCloser(bytes.NewReader(bytesWithHeader)) + } + } + return r, err + }) + } +} + // WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path // is absolute (that is, it begins with a "/"), it replaces the existing path. func WithPath(path string) PrepareDecorator { @@ -455,7 +523,7 @@ func parseURL(u *url.URL, path string) (*url.URL, error) { // WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters // given in the supplied map (i.e., key=value). func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(queryParameters) + parameters := MapToValues(queryParameters) return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) @@ -463,14 +531,16 @@ func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorato if r.URL == nil { return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") } - v := r.URL.Query() for key, value := range parameters { - d, err := url.QueryUnescape(value) - if err != nil { - return r, err + for i := range value { + d, err := url.QueryUnescape(value[i]) + if err != nil { + return r, err + } + value[i] = d } - v.Add(key, d) + v[key] = value } r.URL.RawQuery = v.Encode() } diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go index a908a0adb..349e1963a 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ b/vendor/github.com/Azure/go-autorest/autorest/responder.go @@ -153,6 +153,25 @@ func ByClosingIfError() RespondDecorator { } } +// ByUnmarshallingBytes returns a RespondDecorator that copies the Bytes returned in the +// response Body into the value pointed to by v. +func ByUnmarshallingBytes(v *[]byte) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil { + bytes, errInner := ioutil.ReadAll(resp.Body) + if errInner != nil { + err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) + } else { + *v = bytes + } + } + return err + }) + } +} + // ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the // response Body into the value pointed to by v. func ByUnmarshallingJSON(v interface{}) RespondDecorator { diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go index cacbd8157..5e595d7b1 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -15,14 +15,40 @@ package autorest // limitations under the License. import ( + "context" + "crypto/tls" "fmt" "log" "math" "net/http" + "net/http/cookiejar" "strconv" "time" + + "github.com/Azure/go-autorest/tracing" ) +// used as a key type in context.WithValue() +type ctxSendDecorators struct{} + +// WithSendDecorators adds the specified SendDecorators to the provided context. +// If no SendDecorators are provided the context is unchanged. +func WithSendDecorators(ctx context.Context, sendDecorator []SendDecorator) context.Context { + if len(sendDecorator) == 0 { + return ctx + } + return context.WithValue(ctx, ctxSendDecorators{}, sendDecorator) +} + +// GetSendDecorators returns the SendDecorators in the provided context or the provided default SendDecorators. +func GetSendDecorators(ctx context.Context, defaultSendDecorators ...SendDecorator) []SendDecorator { + inCtx := ctx.Value(ctxSendDecorators{}) + if sd, ok := inCtx.([]SendDecorator); ok { + return sd + } + return defaultSendDecorators +} + // Sender is the interface that wraps the Do method to send HTTP requests. // // The standard http.Client conforms to this interface. @@ -38,14 +64,14 @@ func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { return sf(r) } -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the +// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the // http.Request and pass it along or, first, pass the http.Request along then react to the // http.Response result. type SendDecorator func(Sender) Sender // CreateSender creates, decorates, and returns, as a Sender, the default http.Client. func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) + return DecorateSender(sender(tls.RenegotiateNever), decorators...) } // DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to @@ -68,7 +94,7 @@ func DecorateSender(s Sender, decorators ...SendDecorator) Sender { // // Send will not poll or retry requests. func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return SendWithSender(&http.Client{}, r, decorators...) + return SendWithSender(sender(tls.RenegotiateNever), r, decorators...) } // SendWithSender sends the passed http.Request, through the provided Sender, returning the @@ -80,6 +106,29 @@ func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*ht return DecorateSender(s, decorators...).Do(r) } +func sender(renengotiation tls.RenegotiationSupport) Sender { + // Use behaviour compatible with DefaultTransport, but require TLS minimum version. + defaultTransport := http.DefaultTransport.(*http.Transport) + transport := &http.Transport{ + Proxy: defaultTransport.Proxy, + DialContext: defaultTransport.DialContext, + MaxIdleConns: defaultTransport.MaxIdleConns, + IdleConnTimeout: defaultTransport.IdleConnTimeout, + TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout, + ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + Renegotiation: renengotiation, + }, + } + var roundTripper http.RoundTripper = transport + if tracing.IsEnabled() { + roundTripper = tracing.NewTransport(transport) + } + j, _ := cookiejar.New(nil) + return &http.Client{Jar: j, Transport: roundTripper} +} + // AfterDelay returns a SendDecorator that delays for the passed time.Duration before // invoking the Sender. The delay may be terminated by closing the optional channel on the // http.Request. If canceled, no further Senders are invoked. @@ -209,54 +258,73 @@ func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { // DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified // number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. +// time.Duration (which may be zero). Retrying may be canceled by cancelling the context on the http.Request. +// NOTE: Code http.StatusTooManyRequests (429) will *not* be counted against the number of attempts. func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - attempts++ - for attempt := 0; attempt < attempts; { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - // if the error isn't temporary don't bother retrying - if err != nil && !IsTemporaryNetworkError(err) { - return nil, err - } - // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication - // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. - if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { - return resp, err - } - delayed := DelayWithRetryAfter(resp, r.Context().Done()) - if !delayed && !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - // don't count a 429 against the number of attempts - // so that we continue to retry until it succeeds - if resp == nil || resp.StatusCode != http.StatusTooManyRequests { - attempt++ - } - } - return resp, err + return SenderFunc(func(r *http.Request) (*http.Response, error) { + return doRetryForStatusCodesImpl(s, r, false, attempts, backoff, 0, codes...) }) } } -// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header in -// responses with status code 429 +// DoRetryForStatusCodesWithCap returns a SendDecorator that retries for specified statusCodes for up to the +// specified number of attempts, exponentially backing off between requests using the supplied backoff +// time.Duration (which may be zero). To cap the maximum possible delay between iterations specify a value greater +// than zero for cap. Retrying may be canceled by cancelling the context on the http.Request. +func DoRetryForStatusCodesWithCap(attempts int, backoff, cap time.Duration, codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + return doRetryForStatusCodesImpl(s, r, true, attempts, backoff, cap, codes...) + }) + } +} + +func doRetryForStatusCodesImpl(s Sender, r *http.Request, count429 bool, attempts int, backoff, cap time.Duration, codes ...int) (resp *http.Response, err error) { + rr := NewRetriableRequest(r) + // Increment to add the first call (attempts denotes number of retries) + for attempt := 0; attempt < attempts+1; { + err = rr.Prepare() + if err != nil { + return + } + resp, err = s.Do(rr.Request()) + // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication + // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. + if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { + return resp, err + } + delayed := DelayWithRetryAfter(resp, r.Context().Done()) + if !delayed && !DelayForBackoffWithCap(backoff, cap, attempt, r.Context().Done()) { + return resp, r.Context().Err() + } + // when count429 == false don't count a 429 against the number + // of attempts so that we continue to retry until it succeeds + if count429 || (resp == nil || resp.StatusCode != http.StatusTooManyRequests) { + attempt++ + } + } + return resp, err +} + +// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header. +// The value of Retry-After can be either the number of seconds or a date in RFC1123 format. +// The function returns true after successfully waiting for the specified duration. If there is +// no Retry-After header or the wait is cancelled the return value is false. func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { if resp == nil { return false } - retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")) - if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 { + var dur time.Duration + ra := resp.Header.Get("Retry-After") + if retryAfter, _ := strconv.Atoi(ra); retryAfter > 0 { + dur = time.Duration(retryAfter) * time.Second + } else if t, err := time.Parse(time.RFC1123, ra); err == nil { + dur = t.Sub(time.Now()) + } + if dur > 0 { select { - case <-time.After(time.Duration(retryAfter) * time.Second): + case <-time.After(dur): return true case <-cancel: return false @@ -316,8 +384,22 @@ func WithLogging(logger *log.Logger) SendDecorator { // Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt // count. func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { + return DelayForBackoffWithCap(backoff, 0, attempt, cancel) +} + +// DelayForBackoffWithCap invokes time.After for the supplied backoff duration raised to the power of +// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set +// to zero for no delay. To cap the maximum possible delay specify a value greater than zero for cap. +// The delay may be canceled by closing the passed channel. If terminated early, returns false. +// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt +// count. +func DelayForBackoffWithCap(backoff, cap time.Duration, attempt int, cancel <-chan struct{}) bool { + d := time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second + if cap > 0 && d > cap { + d = cap + } select { - case <-time.After(time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second): + case <-time.After(d): return true case <-cancel: return false diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go index fdda2ce1a..86694bd25 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go +++ b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go @@ -145,3 +145,8 @@ func Float64(i *float64) float64 { func Float64Ptr(i float64) *float64 { return &i } + +// ByteSlicePtr returns a pointer to the passed byte slice. +func ByteSlicePtr(b []byte) *[]byte { + return &b +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/go.mod b/vendor/github.com/Azure/go-autorest/autorest/to/go.mod new file mode 100644 index 000000000..48fd8c6e5 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/to/go.mod @@ -0,0 +1,5 @@ +module github.com/Azure/go-autorest/autorest/to + +go 1.12 + +require github.com/Azure/go-autorest/autorest v0.9.0 diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/go.sum b/vendor/github.com/Azure/go-autorest/autorest/to/go.sum new file mode 100644 index 000000000..d7ee6b462 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/to/go.sum @@ -0,0 +1,17 @@ +github.com/Azure/go-autorest/autorest v0.9.0 h1:MRvx8gncNaXJqOoLmhNjUAKh33JJF8LyxPhomEtOsjs= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0 h1:Ww5g4zThfD/6cLb4z6xxgeyDa7QDkizMkJKe0ysZXp0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go new file mode 100644 index 000000000..8e8292107 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go @@ -0,0 +1,24 @@ +// +build modhack + +package to + +// Copyright 2017 Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file, and the github.com/Azure/go-autorest/autorest import, won't actually become part of +// the resultant binary. + +// Necessary for safely adding multi-module repo. +// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go index bfddd90b5..08cf11c11 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ b/vendor/github.com/Azure/go-autorest/autorest/utility.go @@ -157,7 +157,7 @@ func AsStringSlice(s interface{}) ([]string, error) { } // String method converts interface v to string. If interface is a list, it -// joins list elements using the seperator. Note that only sep[0] will be used for +// joins list elements using the separator. Note that only sep[0] will be used for // joining if any separator is specified. func String(v interface{}, sep ...string) string { if len(sep) == 0 { diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/go.mod b/vendor/github.com/Azure/go-autorest/autorest/validation/go.mod new file mode 100644 index 000000000..b3f9b6a09 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/go-autorest/autorest/validation + +go 1.12 + +require ( + github.com/Azure/go-autorest/autorest v0.9.0 + github.com/stretchr/testify v1.3.0 +) diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/go.sum b/vendor/github.com/Azure/go-autorest/autorest/validation/go.sum new file mode 100644 index 000000000..6b9010a73 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/go.sum @@ -0,0 +1,24 @@ +github.com/Azure/go-autorest/autorest v0.9.0 h1:MRvx8gncNaXJqOoLmhNjUAKh33JJF8LyxPhomEtOsjs= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0 h1:q2gDruN08/guU9vAjuPWff0+QIrpH6ediguzdAzXAUU= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0 h1:Ww5g4zThfD/6cLb4z6xxgeyDa7QDkizMkJKe0ysZXp0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go new file mode 100644 index 000000000..2b2668581 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go @@ -0,0 +1,24 @@ +// +build modhack + +package validation + +// Copyright 2017 Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file, and the github.com/Azure/go-autorest/autorest import, won't actually become part of +// the resultant binary. + +// Necessary for safely adding multi-module repo. +// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go index ae987f8fa..65899b69b 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go @@ -398,11 +398,3 @@ func toInt64(v interface{}) (int64, bool) { } return 0, false } - -// NewErrorWithValidationError appends package type and method name in -// validation error. -// -// Deprecated: Please use validation.NewError() instead. -func NewErrorWithValidationError(err error, packageType, method string) error { - return NewError(packageType, method, err.Error()) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go index 3c6451546..7a71089c9 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -1,7 +1,5 @@ package autorest -import "github.com/Azure/go-autorest/version" - // Copyright 2017 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,7 +14,28 @@ import "github.com/Azure/go-autorest/version" // See the License for the specific language governing permissions and // limitations under the License. +import ( + "fmt" + "runtime" +) + +const number = "v13.0.2" + +var ( + userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", + runtime.Version(), + runtime.GOARCH, + runtime.GOOS, + number, + ) +) + +// UserAgent returns a string containing the Go version, system architecture and OS, and the go-autorest version. +func UserAgent() string { + return userAgent +} + // Version returns the semantic version (see http://semver.org). func Version() string { - return version.Number + return number } diff --git a/vendor/github.com/Azure/go-autorest/logger/LICENSE b/vendor/github.com/Azure/go-autorest/logger/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/logger/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/logger/go.mod b/vendor/github.com/Azure/go-autorest/logger/go.mod new file mode 100644 index 000000000..f22ed56bc --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/logger/go.mod @@ -0,0 +1,3 @@ +module github.com/Azure/go-autorest/logger + +go 1.12 diff --git a/vendor/github.com/Azure/go-autorest/logger/logger.go b/vendor/github.com/Azure/go-autorest/logger/logger.go index 756fd80ca..da09f394c 100644 --- a/vendor/github.com/Azure/go-autorest/logger/logger.go +++ b/vendor/github.com/Azure/go-autorest/logger/logger.go @@ -162,7 +162,7 @@ type Writer interface { // WriteResponse writes the specified HTTP response to the logger if the log level is greater than // or equal to LogInfo. The response body, if set, is logged at level LogDebug or higher. // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no respone content is excluded. + // By default no response content is excluded. WriteResponse(resp *http.Response, filter Filter) } @@ -318,7 +318,7 @@ func (fl fileLogger) WriteResponse(resp *http.Response, filter Filter) { // returns true if the provided body should be included in the log func (fl fileLogger) shouldLogBody(header http.Header, body io.ReadCloser) bool { ct := header.Get("Content-Type") - return fl.logLevel >= LogDebug && body != nil && strings.Index(ct, "application/octet-stream") == -1 + return fl.logLevel >= LogDebug && body != nil && !strings.Contains(ct, "application/octet-stream") } // creates standard header for log entries, it contains a timestamp and the log level diff --git a/vendor/github.com/Azure/go-autorest/tracing/LICENSE b/vendor/github.com/Azure/go-autorest/tracing/LICENSE new file mode 100644 index 000000000..b9d6a27ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/tracing/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/tracing/go.mod b/vendor/github.com/Azure/go-autorest/tracing/go.mod new file mode 100644 index 000000000..25c34c108 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/tracing/go.mod @@ -0,0 +1,3 @@ +module github.com/Azure/go-autorest/tracing + +go 1.12 diff --git a/vendor/github.com/Azure/go-autorest/tracing/tracing.go b/vendor/github.com/Azure/go-autorest/tracing/tracing.go new file mode 100644 index 000000000..0e7a6e962 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/tracing/tracing.go @@ -0,0 +1,67 @@ +package tracing + +// Copyright 2018 Microsoft Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import ( + "context" + "net/http" +) + +// Tracer represents an HTTP tracing facility. +type Tracer interface { + NewTransport(base *http.Transport) http.RoundTripper + StartSpan(ctx context.Context, name string) context.Context + EndSpan(ctx context.Context, httpStatusCode int, err error) +} + +var ( + tracer Tracer +) + +// Register will register the provided Tracer. Pass nil to unregister a Tracer. +func Register(t Tracer) { + tracer = t +} + +// IsEnabled returns true if a Tracer has been registered. +func IsEnabled() bool { + return tracer != nil +} + +// NewTransport creates a new instrumenting http.RoundTripper for the +// registered Tracer. If no Tracer has been registered it returns nil. +func NewTransport(base *http.Transport) http.RoundTripper { + if tracer != nil { + return tracer.NewTransport(base) + } + return nil +} + +// StartSpan starts a trace span with the specified name, associating it with the +// provided context. Has no effect if a Tracer has not been registered. +func StartSpan(ctx context.Context, name string) context.Context { + if tracer != nil { + return tracer.StartSpan(ctx, name) + } + return ctx +} + +// EndSpan ends a previously started span stored in the context. +// Has no effect if a Tracer has not been registered. +func EndSpan(ctx context.Context, httpStatusCode int, err error) { + if tracer != nil { + tracer.EndSpan(ctx, httpStatusCode, err) + } +} diff --git a/vendor/github.com/dimchansky/utfbom/.travis.yml b/vendor/github.com/dimchansky/utfbom/.travis.yml index df88e37b2..3512c8519 100644 --- a/vendor/github.com/dimchansky/utfbom/.travis.yml +++ b/vendor/github.com/dimchansky/utfbom/.travis.yml @@ -1,8 +1,8 @@ language: go go: - - 1.7 - - tip + - '1.10' + - '1.11' # sudo=false makes the build run using a container sudo: false @@ -15,4 +15,4 @@ before_install: script: - gofiles=$(find ./ -name '*.go') && [ -z "$gofiles" ] || unformatted=$(goimports -l $gofiles) && [ -z "$unformatted" ] || (echo >&2 "Go files must be formatted with gofmt. Following files has problem:\n $unformatted" && false) - golint ./... # This won't break the build, just show warnings - - $HOME/gopath/bin/goveralls -service=travis-ci \ No newline at end of file + - $HOME/gopath/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/dimchansky/utfbom/README.md b/vendor/github.com/dimchansky/utfbom/README.md index 2f06ecacd..8ece28008 100644 --- a/vendor/github.com/dimchansky/utfbom/README.md +++ b/vendor/github.com/dimchansky/utfbom/README.md @@ -37,22 +37,7 @@ func trySkip(byteData []byte) { // skip BOM and detect encoding sr, enc := utfbom.Skip(bytes.NewReader(byteData)) - var encStr string - switch enc { - case utfbom.UTF8: - encStr = "UTF8" - case utfbom.UTF16BigEndian: - encStr = "UTF16 big endian" - case utfbom.UTF16LittleEndian: - encStr = "UTF16 little endian" - case utfbom.UTF32BigEndian: - encStr = "UTF32 big endian" - case utfbom.UTF32LittleEndian: - encStr = "UTF32 little endian" - default: - encStr = "Unknown, no byte-order mark found" - } - fmt.Println("Detected encoding:", encStr) + fmt.Printf("Detected encoding: %s\n", enc) output, err = ioutil.ReadAll(sr) if err != nil { fmt.Println(err) @@ -74,7 +59,7 @@ ReadAll with BOM detection and skipping [104 101 108 108 111] Input: [104 101 108 108 111] ReadAll with BOM skipping [104 101 108 108 111] -Detected encoding: Unknown, no byte-order mark found +Detected encoding: Unknown ReadAll with BOM detection and skipping [104 101 108 108 111] ``` diff --git a/vendor/github.com/dimchansky/utfbom/utfbom.go b/vendor/github.com/dimchansky/utfbom/utfbom.go index 648184a12..77a303e56 100644 --- a/vendor/github.com/dimchansky/utfbom/utfbom.go +++ b/vendor/github.com/dimchansky/utfbom/utfbom.go @@ -32,6 +32,24 @@ const ( UTF32LittleEndian ) +// String returns a user-friendly string representation of the encoding. Satisfies fmt.Stringer interface. +func (e Encoding) String() string { + switch e { + case UTF8: + return "UTF8" + case UTF16BigEndian: + return "UTF16BigEndian" + case UTF16LittleEndian: + return "UTF16LittleEndian" + case UTF32BigEndian: + return "UTF32BigEndian" + case UTF32LittleEndian: + return "UTF32LittleEndian" + default: + return "Unknown" + } +} + const maxConsecutiveEmptyReads = 100 // Skip creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method.go index d599b2eee..d011ec53e 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method.go @@ -2,7 +2,6 @@ package authentication import ( "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" ) type authMethod interface { @@ -10,7 +9,7 @@ type authMethod interface { isApplicable(b Builder) bool - getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) + getAuthorizationToken(sender autorest.Sender, oauthConfig *OAuthConfig, endpoint string) (autorest.Authorizer, error) name() string diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_azure_cli_token.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_azure_cli_token.go index 8f0927527..73816d4bb 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_azure_cli_token.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_azure_cli_token.go @@ -2,6 +2,7 @@ package authentication import ( "bytes" + "context" "encoding/json" "fmt" "os/exec" @@ -14,7 +15,8 @@ import ( ) type azureCliTokenAuth struct { - profile *azureCLIProfile + profile *azureCLIProfile + servicePrincipalAuthDocsLink string } func (a azureCliTokenAuth) build(b Builder) (authMethod, error) { @@ -25,6 +27,7 @@ func (a azureCliTokenAuth) build(b Builder) (authMethod, error) { subscriptionId: b.SubscriptionID, tenantId: b.TenantID, }, + servicePrincipalAuthDocsLink: b.ClientSecretDocsLink, } profilePath, err := cli.ProfilePath() if err != nil { @@ -38,6 +41,17 @@ func (a azureCliTokenAuth) build(b Builder) (authMethod, error) { auth.profile.profile = profile + // Authenticating as a Service Principal doesn't return all of the information we need for authentication purposes + // as such Service Principal authentication is supported using the specific auth method + if authenticatedAsAUser := auth.profile.verifyAuthenticatedAsAUser(); !authenticatedAsAUser { + return nil, fmt.Errorf(`Authenticating using the Azure CLI is only supported as a User (not a Service Principal). + +To authenticate to Azure using a Service Principal, you can use the separate 'Authenticate using a Service Principal' +auth method - instructions for which can be found here: %s + +Alternatively you can authenticate using the Azure CLI by using a User Account.`, auth.servicePrincipalAuthDocsLink) + } + err = auth.profile.populateFields() if err != nil { return nil, fmt.Errorf("Error retrieving the Profile from the Azure CLI: %s Please re-authenticate using `az login`.", err) @@ -55,7 +69,11 @@ func (a azureCliTokenAuth) isApplicable(b Builder) bool { return b.SupportsAzureCliToken } -func (a azureCliTokenAuth) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { +func (a azureCliTokenAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + if oauth.OAuth == nil { + return nil, fmt.Errorf("Error getting Authorization Token for cli auth: an OAuth token wasn't configured correctly; please file a bug with more details") + } + // the Azure CLI appears to cache these, so to maintain compatibility with the interface this method is intentionally not on the pointer token, err := obtainAuthorizationToken(endpoint, a.profile.subscriptionId) if err != nil { @@ -67,11 +85,26 @@ func (a azureCliTokenAuth) getAuthorizationToken(oauthConfig *adal.OAuthConfig, return nil, fmt.Errorf("Error converting Authorization Token to an ADAL Token: %s", err) } - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, a.profile.clientId, endpoint, adalToken) + spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauth.OAuth, a.profile.clientId, endpoint, adalToken) if err != nil { return nil, err } + var refreshFunc adal.TokenRefresh = func(ctx context.Context, resource string) (*adal.Token, error) { + token, err := obtainAuthorizationToken(resource, a.profile.subscriptionId) + if err != nil { + return nil, err + } + + adalToken, err := token.ToADALToken() + if err != nil { + return nil, err + } + + return &adalToken, nil + } + spt.SetCustomRefreshFunc(refreshFunc) + auth := autorest.NewBearerAuthorizer(spt) return auth, nil } @@ -82,9 +115,19 @@ func (a azureCliTokenAuth) name() string { func (a azureCliTokenAuth) populateConfig(c *Config) error { c.ClientID = a.profile.clientId + c.TenantID = a.profile.tenantId c.Environment = a.profile.environment c.SubscriptionID = a.profile.subscriptionId - c.TenantID = a.profile.tenantId + + c.GetAuthenticatedObjectID = func(ctx context.Context) (string, error) { + objectId, err := obtainAuthenticatedObjectID() + if err != nil { + return "", err + } + + return objectId, nil + } + return nil } @@ -112,35 +155,56 @@ func (a azureCliTokenAuth) validate() error { return err.ErrorOrNil() } +func obtainAuthenticatedObjectID() (string, error) { + + var json struct { + ObjectId string `json:"objectId"` + } + + err := jsonUnmarshalAzCmd(&json, "ad", "signed-in-user", "show", "-o=json") + if err != nil { + return "", fmt.Errorf("Error parsing json result from the Azure CLI: %v", err) + } + + return json.ObjectId, nil +} + func obtainAuthorizationToken(endpoint string, subscriptionId string) (*cli.Token, error) { + var token cli.Token + err := jsonUnmarshalAzCmd(&token, "account", "get-access-token", "--resource", endpoint, "--subscription", subscriptionId, "-o=json") + if err != nil { + return nil, fmt.Errorf("Error parsing json result from the Azure CLI: %v", err) + } + + return &token, nil +} + +func jsonUnmarshalAzCmd(i interface{}, arg ...string) error { var stderr bytes.Buffer var stdout bytes.Buffer - cmd := exec.Command("az", "account", "get-access-token", "--resource", endpoint, "--subscription", subscriptionId, "-o=json") + cmd := exec.Command("az", arg...) cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Start(); err != nil { - return nil, fmt.Errorf("Error launching Azure CLI: %+v", err) + return fmt.Errorf("Error launching Azure CLI: %+v", err) } if err := cmd.Wait(); err != nil { - return nil, fmt.Errorf("Error waiting for the Azure CLI: %+v", err) + return fmt.Errorf("Error waiting for the Azure CLI: %+v", err) } stdOutStr := stdout.String() stdErrStr := stderr.String() - if stdErrStr != "" { - return nil, fmt.Errorf("Error retrieving access token from Azure CLI: %s", strings.TrimSpace(stdErrStr)) + return fmt.Errorf("Error retrieving running Azure CLI: %s", strings.TrimSpace(stdErrStr)) } - var token *cli.Token - err := json.Unmarshal([]byte(stdOutStr), &token) - if err != nil { - return nil, fmt.Errorf("Error unmarshaling Access Token from the Azure CLI: %s", err) + if err := json.Unmarshal([]byte(stdOutStr), &i); err != nil { + return fmt.Errorf("Error unmarshaling the result of Azure CLI: %v", err) } - return token, nil + return nil } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_cert.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_cert.go index 00a0d2794..14e455cc0 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_cert.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_cert.go @@ -41,7 +41,11 @@ func (a servicePrincipalClientCertificateAuth) name() string { return "Service Principal / Client Certificate" } -func (a servicePrincipalClientCertificateAuth) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { +func (a servicePrincipalClientCertificateAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + if oauth.OAuth == nil { + return nil, fmt.Errorf("Error getting Authorization Token for client cert: an OAuth token wasn't configured correctly; please file a bug with more details") + } + certificateData, err := ioutil.ReadFile(a.clientCertPath) if err != nil { return nil, fmt.Errorf("Error reading Client Certificate %q: %v", a.clientCertPath, err) @@ -53,11 +57,13 @@ func (a servicePrincipalClientCertificateAuth) getAuthorizationToken(oauthConfig return nil, fmt.Errorf("Error decoding pkcs12 certificate: %v", err) } - spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, a.clientId, certificate, rsaPrivateKey, endpoint) + spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauth.OAuth, a.clientId, certificate, rsaPrivateKey, endpoint) if err != nil { return nil, err } + spt.SetSender(sender) + err = spt.Refresh() if err != nil { return nil, err @@ -69,6 +75,7 @@ func (a servicePrincipalClientCertificateAuth) getAuthorizationToken(oauthConfig func (a servicePrincipalClientCertificateAuth) populateConfig(c *Config) error { c.AuthenticatedAsAServicePrincipal = true + c.GetAuthenticatedObjectID = buildServicePrincipalObjectIDFunc(c) return nil } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret.go index 4e41d5a93..36aaed352 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret.go @@ -33,18 +33,23 @@ func (a servicePrincipalClientSecretAuth) name() string { return "Service Principal / Client Secret" } -func (a servicePrincipalClientSecretAuth) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, a.clientId, a.clientSecret, endpoint) +func (a servicePrincipalClientSecretAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + if oauth.OAuth == nil { + return nil, fmt.Errorf("Error getting Authorization Token for client secret auth: an OAuth token wasn't configured correctly; please file a bug with more details") + } + + spt, err := adal.NewServicePrincipalToken(*oauth.OAuth, a.clientId, a.clientSecret, endpoint) if err != nil { return nil, err } + spt.SetSender(sender) - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil + return autorest.NewBearerAuthorizer(spt), nil } func (a servicePrincipalClientSecretAuth) populateConfig(c *Config) error { c.AuthenticatedAsAServicePrincipal = true + c.GetAuthenticatedObjectID = buildServicePrincipalObjectIDFunc(c) return nil } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret_multi_tenant.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret_multi_tenant.go new file mode 100644 index 000000000..c435a74f4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_client_secret_multi_tenant.go @@ -0,0 +1,84 @@ +package authentication + +import ( + "fmt" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" + "github.com/hashicorp/go-multierror" +) + +type servicePrincipalClientSecretMultiTenantAuth struct { + clientId string + clientSecret string + subscriptionId string + tenantId string + auxiliaryTenantIDs []string +} + +func (a servicePrincipalClientSecretMultiTenantAuth) build(b Builder) (authMethod, error) { + method := servicePrincipalClientSecretMultiTenantAuth{ + clientId: b.ClientID, + clientSecret: b.ClientSecret, + subscriptionId: b.SubscriptionID, + tenantId: b.TenantID, + auxiliaryTenantIDs: b.AuxiliaryTenantIDs, + } + return method, nil +} + +func (a servicePrincipalClientSecretMultiTenantAuth) isApplicable(b Builder) bool { + return b.SupportsClientSecretAuth && b.ClientSecret != "" && b.SupportsAuxiliaryTenants && (len(b.AuxiliaryTenantIDs) > 0) +} + +func (a servicePrincipalClientSecretMultiTenantAuth) name() string { + return "Multi Tenant Service Principal / Client Secret" +} + +func (a servicePrincipalClientSecretMultiTenantAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + if oauth.MultiTenantOauth == nil { + return nil, fmt.Errorf("Error getting Authorization Token for client cert: an MultiTenantOauth token wasn't configured correctly; please file a bug with more details") + } + + spt, err := adal.NewMultiTenantServicePrincipalToken(*oauth.MultiTenantOauth, a.clientId, a.clientSecret, endpoint) + if err != nil { + return nil, err + } + + spt.PrimaryToken.SetSender(sender) + for _, t := range spt.AuxiliaryTokens { + t.SetSender(sender) + } + + auth := autorest.NewMultiTenantServicePrincipalTokenAuthorizer(spt) + return auth, nil +} + +func (a servicePrincipalClientSecretMultiTenantAuth) populateConfig(c *Config) error { + c.AuthenticatedAsAServicePrincipal = true + c.GetAuthenticatedObjectID = buildServicePrincipalObjectIDFunc(c) + return nil +} + +func (a servicePrincipalClientSecretMultiTenantAuth) validate() error { + var err *multierror.Error + + fmtErrorMessage := "A %s must be configured when authenticating as a Service Principal using a Multi Tenant Client Secret." + + if a.subscriptionId == "" { + err = multierror.Append(err, fmt.Errorf(fmtErrorMessage, "Subscription ID")) + } + if a.clientId == "" { + err = multierror.Append(err, fmt.Errorf(fmtErrorMessage, "Client ID")) + } + if a.clientSecret == "" { + err = multierror.Append(err, fmt.Errorf(fmtErrorMessage, "Client Secret")) + } + if a.tenantId == "" { + err = multierror.Append(err, fmt.Errorf(fmtErrorMessage, "Tenant ID")) + } + if len(a.auxiliaryTenantIDs) == 0 { + err = multierror.Append(err, fmt.Errorf(fmtErrorMessage, "Auxiliary Tenant IDs")) + } + return err.ErrorOrNil() +} diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_msi.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_msi.go index 9b0de8f5d..7d68271d0 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_msi.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/auth_method_msi.go @@ -10,23 +10,25 @@ import ( ) type managedServiceIdentityAuth struct { - endpoint string + msiEndpoint string + clientID string } func (a managedServiceIdentityAuth) build(b Builder) (authMethod, error) { - endpoint := b.MsiEndpoint - if endpoint == "" { - msiEndpoint, err := adal.GetMSIVMEndpoint() + msiEndpoint := b.MsiEndpoint + if msiEndpoint == "" { + ep, err := adal.GetMSIVMEndpoint() if err != nil { return nil, fmt.Errorf("Error determining MSI Endpoint: ensure the VM has MSI enabled, or configure the MSI Endpoint. Error: %s", err) } - endpoint = msiEndpoint + msiEndpoint = ep } - log.Printf("[DEBUG] Using MSI endpoint %q", endpoint) + log.Printf("[DEBUG] Using MSI msiEndpoint %q", msiEndpoint) auth := managedServiceIdentityAuth{ - endpoint: endpoint, + msiEndpoint: msiEndpoint, + clientID: b.ClientID, } return auth, nil } @@ -39,11 +41,28 @@ func (a managedServiceIdentityAuth) name() string { return "Managed Service Identity" } -func (a managedServiceIdentityAuth) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - spt, err := adal.NewServicePrincipalTokenFromMSI(a.endpoint, endpoint) - if err != nil { - return nil, err +func (a managedServiceIdentityAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + log.Printf("[DEBUG] getAuthorizationToken with MSI msiEndpoint %q, ClientID %q for msiEndpoint %q", a.msiEndpoint, a.clientID, endpoint) + + if oauth.OAuth == nil { + return nil, fmt.Errorf("Error getting Authorization Token for MSI auth: an OAuth token wasn't configured correctly; please file a bug with more details") } + + var spt *adal.ServicePrincipalToken + var err error + if a.clientID == "" { + spt, err = adal.NewServicePrincipalTokenFromMSI(a.msiEndpoint, endpoint) + if err != nil { + return nil, err + } + } else { + spt, err = adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(a.msiEndpoint, endpoint, a.clientID) + if err != nil { + return nil, fmt.Errorf("failed to get an oauth token from MSI for user assigned identity from MSI endpoint %q with client ID %q for endpoint %q: %v", a.msiEndpoint, a.clientID, endpoint, err) + } + } + + spt.SetSender(sender) auth := autorest.NewBearerAuthorizer(spt) return auth, nil } @@ -56,7 +75,7 @@ func (a managedServiceIdentityAuth) populateConfig(c *Config) error { func (a managedServiceIdentityAuth) validate() error { var err *multierror.Error - if a.endpoint == "" { + if a.msiEndpoint == "" { err = multierror.Append(err, fmt.Errorf("An MSI Endpoint must be configured")) } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_access_token.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_access_token.go index 822fb2d77..bc826d557 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_access_token.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_access_token.go @@ -10,8 +10,8 @@ import ( ) type azureCliAccessToken struct { - ClientID string - AccessToken *adal.Token + ClientID string + AccessToken *adal.Token } func findValidAccessTokenForTenant(tokens []cli.Token, tenantId string) (*azureCliAccessToken, error) { @@ -32,8 +32,8 @@ func findValidAccessTokenForTenant(tokens []cli.Token, tenantId string) (*azureC } validAccessToken := azureCliAccessToken{ - ClientID: accessToken.ClientID, - AccessToken: &token, + ClientID: accessToken.ClientID, + AccessToken: &token, } return &validAccessToken, nil } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_profile.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_profile.go index 39fb30ddd..1f6a0b6af 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_profile.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_cli_profile.go @@ -1,16 +1,18 @@ package authentication import ( + "strings" + "github.com/Azure/go-autorest/autorest/azure/cli" ) type azureCLIProfile struct { profile cli.Profile - clientId string - environment string - subscriptionId string - tenantId string + clientId string + environment string + subscriptionId string + tenantId string } func (a *azureCLIProfile) populateFields() error { @@ -33,3 +35,18 @@ func (a *azureCLIProfile) populateFields() error { // always pull the environment from the Azure CLI, since the Access Token's associated with it return a.populateEnvironment() } + +func (a *azureCLIProfile) verifyAuthenticatedAsAUser() bool { + for _, subscription := range a.profile.Subscriptions { + if subscription.User == nil { + continue + } + + authenticatedAsAUser := strings.EqualFold(subscription.User.Type, "user") + if authenticatedAsAUser { + return true + } + } + + return false +} diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_sp_objectid.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_sp_objectid.go new file mode 100644 index 000000000..97c5bc874 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/azure_sp_objectid.go @@ -0,0 +1,49 @@ +package authentication + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/hashicorp/go-azure-helpers/sender" +) + +func buildServicePrincipalObjectIDFunc(c *Config) func(ctx context.Context) (string, error) { + return func(ctx context.Context) (string, error) { + env, err := DetermineEnvironment(c.Environment) + if err != nil { + return "", err + } + + s := sender.BuildSender("GoAzureHelpers") + + oauthConfig, err := c.BuildOAuthConfig(env.ActiveDirectoryEndpoint) + if err != nil { + return "", err + } + + // Graph Endpoints + graphEndpoint := env.GraphEndpoint + graphAuth, err := c.GetAuthorizationToken(s, oauthConfig, env.GraphEndpoint) + if err != nil { + return "", err + } + + client := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, c.TenantID) + client.Authorizer = graphAuth + client.Sender = s + + filter := fmt.Sprintf("appId eq '%s'", c.ClientID) + listResult, listErr := client.List(ctx, filter) + + if listErr != nil { + return "", fmt.Errorf("Error listing Service Principals: %#v", listErr) + } + + if listResult.Values() == nil || len(listResult.Values()) != 1 || listResult.Values()[0].ObjectID == nil { + return "", fmt.Errorf("Unexpected Service Principal query result: %#v", listResult.Values()) + } + + return *listResult.Values()[0].ObjectID, nil + } +} diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/builder.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/builder.go index e37e8b137..9b5c1a114 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/builder.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/builder.go @@ -1,10 +1,15 @@ package authentication import ( + "context" "fmt" "log" ) +var ( + authenticatedObjectCache = "" +) + // Builder supports all of the possible Authentication values and feature toggles // required to build a working Config for Authentication purposes. type Builder struct { @@ -14,6 +19,10 @@ type Builder struct { TenantID string Environment string + // Auxiliary tenant IDs used for multi tenant auth + SupportsAuxiliaryTenants bool + AuxiliaryTenantIDs []string + // The custom Resource Manager Endpoint which should be used // only applicable for Azure Stack at this time. CustomResourceManagerEndpoint string @@ -33,6 +42,7 @@ type Builder struct { // Service Principal (Client Secret) Auth SupportsClientSecretAuth bool ClientSecret string + ClientSecretDocsLink string } // Build takes the configuration from the Builder and builds up a validated Config @@ -42,6 +52,7 @@ func (b Builder) Build() (*Config, error) { ClientID: b.ClientID, SubscriptionID: b.SubscriptionID, TenantID: b.TenantID, + AuxiliaryTenantIDs: b.AuxiliaryTenantIDs, Environment: b.Environment, CustomResourceManagerEndpoint: b.CustomResourceManagerEndpoint, } @@ -50,6 +61,7 @@ func (b Builder) Build() (*Config, error) { // since the Azure CLI Parsing should always be the last thing checked supportedAuthenticationMethods := []authMethod{ servicePrincipalClientCertificateAuth{}, + servicePrincipalClientSecretMultiTenantAuth{}, servicePrincipalClientSecretAuth{}, managedServiceIdentityAuth{}, azureCliTokenAuth{}, @@ -58,23 +70,44 @@ func (b Builder) Build() (*Config, error) { for _, method := range supportedAuthenticationMethods { name := method.name() log.Printf("Testing if %s is applicable for Authentication..", name) - if method.isApplicable(b) { - log.Printf("Using %s for Authentication", name) - auth, err := method.build(b) - if err != nil { - return nil, err - } - // populate authentication specific fields on the Config - // (e.g. is service principal, fields parsed from the azure cli) - err = auth.populateConfig(&config) - if err != nil { - return nil, err - } - - config.authMethod = auth - return config.validate() + // does not support it via validate? + if !method.isApplicable(b) { + continue } + + log.Printf("Using %s for Authentication", name) + auth, err := method.build(b) + if err != nil { + return nil, err + } + + // populate authentication specific fields on the Config + // (e.g. is service principal, fields parsed from the azure cli) + err = auth.populateConfig(&config) + if err != nil { + return nil, err + } + + config.authMethod = auth + + // Authenticated Object ID Cache + if config.GetAuthenticatedObjectID != nil { + uncachedFunction := config.GetAuthenticatedObjectID + config.GetAuthenticatedObjectID = func(ctx context.Context) (string, error) { + if authenticatedObjectCache == "" { + authenticatedObjectCache, err = uncachedFunction(ctx) + if err != nil { + return "", err + } + log.Printf("authenticated object ID cache miss, populting with: %q", authenticatedObjectCache) + } + + return authenticatedObjectCache, nil + } + } + + return &config, config.authMethod.validate() } return nil, fmt.Errorf("No supported authentication methods were found!") diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/config.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/config.go index c3068152f..20eb61adc 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/config.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/config.go @@ -1,6 +1,11 @@ package authentication import ( + "context" + "fmt" + "log" + "strings" + "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" ) @@ -8,10 +13,13 @@ import ( // Config is the configuration structure used to instantiate a // new Azure management client. type Config struct { - ClientID string - SubscriptionID string - TenantID string - Environment string + ClientID string + SubscriptionID string + TenantID string + AuxiliaryTenantIDs []string + Environment string + + GetAuthenticatedObjectID func(context.Context) (string, error) AuthenticatedAsAServicePrincipal bool // A Custom Resource Manager Endpoint @@ -21,16 +29,96 @@ type Config struct { authMethod authMethod } -// GetAuthorizationToken returns an authorization token for the authentication method defined in the Config -func (c Config) GetAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - return c.authMethod.getAuthorizationToken(oauthConfig, endpoint) +type OAuthConfig struct { + OAuth *adal.OAuthConfig + MultiTenantOauth *adal.MultiTenantOAuthConfig } -func (c Config) validate() (*Config, error) { - err := c.authMethod.validate() +// GetAuthorizationToken returns an authorization token for the authentication method defined in the Config +func (c Config) GetOAuthConfig(activeDirectoryEndpoint string) (*adal.OAuthConfig, error) { + log.Printf("Getting OAuth config for endpoint %s with tenant %s", activeDirectoryEndpoint, c.TenantID) + + // fix for ADFS environments, if the login endpoint ends in `/adfs` it's an adfs environment + // the login endpoint ends up residing in `ActiveDirectoryEndpoint` + oAuthTenant := c.TenantID + if strings.HasSuffix(strings.ToLower(activeDirectoryEndpoint), "/adfs") { + log.Printf("[DEBUG] ADFS environment detected - overriding Tenant ID to `adfs`!") + oAuthTenant = "adfs" + } + + oauth, err := adal.NewOAuthConfig(activeDirectoryEndpoint, oAuthTenant) if err != nil { return nil, err } - return &c, nil + // OAuthConfigForTenant returns a pointer, which can be nil. + if oauth == nil { + return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) + } + + return oauth, nil +} + +// GetMultiTenantOAuthConfig returns a multi-tenant authorization token for the authentication method defined in the Config +func (c Config) GetMultiTenantOAuthConfig(activeDirectoryEndpoint string) (*adal.MultiTenantOAuthConfig, error) { + log.Printf("Getting multi OAuth config for endpoint %s with tenant %s (aux tenants: %v)", activeDirectoryEndpoint, c.TenantID, c.AuxiliaryTenantIDs) + oauth, err := adal.NewMultiTenantOAuthConfig(activeDirectoryEndpoint, c.TenantID, c.AuxiliaryTenantIDs, adal.OAuthOptions{}) + if err != nil { + return nil, err + } + + // OAuthConfigForTenant returns a pointer, which can be nil. + if oauth == nil { + return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s (auxiliary tenants %v)", c.TenantID, c.AuxiliaryTenantIDs) + } + + return &oauth, nil +} + +// BuildOAuthConfig builds the authorization configuration for the specified Active Directory Endpoint +func (c Config) BuildOAuthConfig(activeDirectoryEndpoint string) (*OAuthConfig, error) { + multiAuth := OAuthConfig{} + var err error + + multiAuth.OAuth, err = c.GetOAuthConfig(activeDirectoryEndpoint) + if err != nil { + return nil, err + } + + if len(c.AuxiliaryTenantIDs) > 0 { + multiAuth.MultiTenantOauth, err = c.GetMultiTenantOAuthConfig(activeDirectoryEndpoint) + if err != nil { + return nil, err + } + } + + return &multiAuth, nil +} + +// BearerAuthorizerCallback returns a BearerAuthorizer valid only for the Primary Tenant +// this signs a request using the AccessToken returned from the primary Resource Manager authorizer +func (c Config) BearerAuthorizerCallback(sender autorest.Sender, oauthConfig *OAuthConfig) *autorest.BearerAuthorizerCallback { + return autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { + // a BearerAuthorizer is only valid for the primary tenant + newAuthConfig := &OAuthConfig{ + OAuth: oauthConfig.OAuth, + } + + storageSpt, err := c.GetAuthorizationToken(sender, newAuthConfig, resource) + if err != nil { + return nil, err + } + + cast, ok := storageSpt.(*autorest.BearerAuthorizer) + if !ok { + return nil, fmt.Errorf("Error converting %+v to a BearerAuthorizer", storageSpt) + } + + return cast, nil + }) +} + +// GetAuthorizationToken returns an authorization token for the authentication method defined in the Config +func (c Config) GetAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) { + return c.authMethod.getAuthorizationToken(sender, oauth, endpoint) } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/sender/sender.go b/vendor/github.com/hashicorp/go-azure-helpers/sender/sender.go new file mode 100644 index 000000000..b3301598b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-helpers/sender/sender.go @@ -0,0 +1,57 @@ +package sender + +import ( + "log" + "net/http" + "net/http/httputil" + + "github.com/Azure/go-autorest/autorest" +) + +func BuildSender(providerName string) autorest.Sender { + return autorest.DecorateSender(&http.Client{ + Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + }, + }, withRequestLogging(providerName)) +} + +func withRequestLogging(providerName string) autorest.SendDecorator { + return func(s autorest.Sender) autorest.Sender { + return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { + // strip the authorization header prior to printing + authHeaderName := "Authorization" + auth := r.Header.Get(authHeaderName) + if auth != "" { + r.Header.Del(authHeaderName) + } + + // dump request to wire format + if dump, err := httputil.DumpRequestOut(r, true); err == nil { + log.Printf("[DEBUG] %s Request: \n%s\n", providerName, dump) + } else { + // fallback to basic message + log.Printf("[DEBUG] %s Request: %s to %s\n", providerName, r.Method, r.URL) + } + + // add the auth header back + if auth != "" { + r.Header.Add(authHeaderName, auth) + } + + resp, err := s.Do(r) + if resp != nil { + // dump response to wire format + if dump, err2 := httputil.DumpResponse(resp, true); err2 == nil { + log.Printf("[DEBUG] %s Response for %s: \n%s\n", providerName, r.URL, dump) + } else { + // fallback to basic message + log.Printf("[DEBUG] %s Response: %s for %s\n", providerName, resp.Status, r.URL) + } + } else { + log.Printf("[DEBUG] Request to %s completed with no response", r.URL) + } + return resp, err + }) + } +} diff --git a/vendor/github.com/hashicorp/go-azure-helpers/storage/sas_token.go b/vendor/github.com/hashicorp/go-azure-helpers/storage/sas_token.go index 205baaeee..80e228a77 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/storage/sas_token.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/storage/sas_token.go @@ -7,11 +7,14 @@ import ( "fmt" "net/url" "strings" + + "github.com/Azure/go-autorest/autorest/azure" ) const ( - connStringAccountKeyKey = "AccountKey" - connStringAccountNameKey = "AccountName" + connStringAccountKeyKey = "AccountKey" + connStringAccountNameKey = "AccountName" + blobContainerSignedVersion = "2018-11-09" ) // ComputeAccountSASToken computes the SAS Token for a Storage Account based on the @@ -67,6 +70,117 @@ func ComputeAccountSASToken(accountName string, return sasToken, nil } +// ComputeAccountSASConnectionString computes the composed SAS Connection String for a Storage Account based on the +// sas token +func ComputeAccountSASConnectionString(env *azure.Environment, accountName string, sasToken string) string { + return fmt.Sprintf( + "BlobEndpoint=https://%[1]s.blob.%[2]s/;"+ + "FileEndpoint=https://%[1]s.file.%[2]s/;"+ + "QueueEndpoint=https://%[1]s.queue.%[2]s/;"+ + "TableEndpoint=https://%[1]s.table.%[2]s/;"+ + "SharedAccessSignature=%[3]s", accountName, env.StorageEndpointSuffix, sasToken[1:]) // need to cut the first character '?' from the sas token +} + +// ComputeAccountSASConnectionUrlForType computes the SAS Connection String for a Storage Account based on the +// sas token and the storage type +func ComputeAccountSASConnectionUrlForType(env *azure.Environment, accountName string, sasToken string, storageType string) (*string, error) { + if !strings.EqualFold(storageType, "blob") && !strings.EqualFold(storageType, "file") && !strings.EqualFold(storageType, "queue") && !strings.EqualFold(storageType, "table") { + return nil, fmt.Errorf("Unexpected storage type %s!", storageType) + } + + url := fmt.Sprintf("https://%s.%s.%s%s", accountName, strings.ToLower(storageType), env.StorageEndpointSuffix, sasToken) + return &url, nil +} + +func ComputeContainerSASToken(signedPermissions string, + signedStart string, + signedExpiry string, + accountName string, + accountKey string, + containerName string, + signedIdentifier string, + signedIp string, + signedProtocol string, + signedSnapshotTime string, + cacheControl string, + contentDisposition string, + contentEncoding string, + contentLanguage string, + contentType string, +) (string, error) { + + canonicalizedResource := "/blob/" + accountName + "/" + containerName + signedVersion := blobContainerSignedVersion + signedResource := "c" // c for container + + // UTF-8 by default... + stringToSign := signedPermissions + "\n" + stringToSign += signedStart + "\n" + stringToSign += signedExpiry + "\n" + stringToSign += canonicalizedResource + "\n" + stringToSign += signedIdentifier + "\n" + stringToSign += signedIp + "\n" + stringToSign += signedProtocol + "\n" + stringToSign += signedVersion + "\n" + stringToSign += signedResource + "\n" + stringToSign += signedSnapshotTime + "\n" + stringToSign += cacheControl + "\n" + stringToSign += contentDisposition + "\n" + stringToSign += contentEncoding + "\n" + stringToSign += contentLanguage + "\n" + stringToSign += contentType + + binaryKey, err := base64.StdEncoding.DecodeString(accountKey) + if err != nil { + return "", err + } + hasher := hmac.New(sha256.New, binaryKey) + hasher.Write([]byte(stringToSign)) + signature := hasher.Sum(nil) + + sasToken := "?sv=" + signedVersion + sasToken += "&sr=" + signedResource + sasToken += "&st=" + url.QueryEscape(signedStart) + sasToken += "&se=" + url.QueryEscape(signedExpiry) + sasToken += "&sp=" + signedPermissions + + if len(signedIp) > 0 { + sasToken += "&sip=" + signedIp + } + + if len(signedProtocol) > 0 { + sasToken += "&spr=" + signedProtocol + } + + if len(signedIdentifier) > 0 { + sasToken += "&si=" + signedIdentifier + } + + if len(cacheControl) > 0 { + sasToken += "&rscc=" + url.QueryEscape(cacheControl) + } + + if len(contentDisposition) > 0 { + sasToken += "&rscd=" + url.QueryEscape(contentDisposition) + } + + if len(contentEncoding) > 0 { + sasToken += "&rsce=" + url.QueryEscape(contentEncoding) + } + + if len(contentLanguage) > 0 { + sasToken += "&rscl=" + url.QueryEscape(contentLanguage) + } + + if len(contentType) > 0 { + sasToken += "&rsct=" + url.QueryEscape(contentType) + } + + sasToken += "&sig=" + url.QueryEscape(base64.StdEncoding.EncodeToString(signature)) + + return sasToken, nil +} + // ParseAccountSASConnectionString parses the Connection String for a Storage Account func ParseAccountSASConnectionString(connString string) (map[string]string, error) { // This connection string was for a real storage account which has been deleted diff --git a/vendor/github.com/marstr/guid/.travis.yml b/vendor/github.com/marstr/guid/.travis.yml deleted file mode 100644 index 35158ec53..000000000 --- a/vendor/github.com/marstr/guid/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false - -language: go - -go: - - 1.7 - - 1.8 - -install: - - go get -u github.com/golang/lint/golint - - go get -u github.com/HewlettPackard/gas - -script: - - golint --set_exit_status - - go vet - - go test -v -cover -race - - go test -bench . - - gas ./... \ No newline at end of file diff --git a/vendor/github.com/marstr/guid/LICENSE.txt b/vendor/github.com/marstr/guid/LICENSE.txt deleted file mode 100644 index e18a0841a..000000000 --- a/vendor/github.com/marstr/guid/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Martin Strobel - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/marstr/guid/README.md b/vendor/github.com/marstr/guid/README.md deleted file mode 100644 index 355fad16d..000000000 --- a/vendor/github.com/marstr/guid/README.md +++ /dev/null @@ -1,27 +0,0 @@ -[![Build Status](https://travis-ci.org/marstr/guid.svg?branch=master)](https://travis-ci.org/marstr/guid) -[![GoDoc](https://godoc.org/github.com/marstr/guid?status.svg)](https://godoc.org/github.com/marstr/guid) -[![Go Report Card](https://goreportcard.com/badge/github.com/marstr/guid)](https://goreportcard.com/report/github.com/marstr/guid) - -# Guid -Globally unique identifiers offer a quick means of generating non-colliding values across a distributed system. For this implemenation, [RFC 4122](http://ietf.org/rfc/rfc4122.txt) governs the desired behavior. - -## What's in a name? -You have likely already noticed that RFC and some implementations refer to these structures as UUIDs (Universally Unique Identifiers), where as this project is annotated as GUIDs (Globally Unique Identifiers). The name Guid was selected to make clear this project's ties to the [.NET struct Guid.](https://msdn.microsoft.com/en-us/library/system.guid(v=vs.110).aspx) The most obvious relationship is the desire to have the same format specifiers available in this library's Format and Parse methods as .NET would have in its ToString and Parse methods. - -# Installation -- Ensure you have the [Go Programming Language](https://golang.org/) installed on your system. -- Run the command: `go get -u github.com/marstr/guid` - -# Contribution -Contributions are welcome! Feel free to send Pull Requests. Continuous Integration will ensure that you have conformed to Go conventions. Please remember to add tests for your changes. - -# Versioning -This library will adhere to the -[Semantic Versioning 2.0.0](http://semver.org/spec/v2.0.0.html) specification. It may be worth noting this should allow for tools like [glide](https://glide.readthedocs.io/en/latest/) to pull in this library with ease. - -The Release Notes portion of this file will be updated to reflect the most recent major/minor updates, with the option to tag particular bug-fixes as well. Updates to the Release Notes for patches should be addative, where as major/minor updates should replace the previous version. If one desires to see the release notes for an older version, checkout that version of code and open this file. - -# Release Notes 1.1.* - -## v1.1.0 -Adding support for JSON marshaling and unmarshaling. diff --git a/vendor/github.com/marstr/guid/guid.go b/vendor/github.com/marstr/guid/guid.go deleted file mode 100644 index 51b038b75..000000000 --- a/vendor/github.com/marstr/guid/guid.go +++ /dev/null @@ -1,301 +0,0 @@ -package guid - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "net" - "strings" - "sync" - "time" -) - -// GUID is a unique identifier designed to virtually guarantee non-conflict between values generated -// across a distributed system. -type GUID struct { - timeHighAndVersion uint16 - timeMid uint16 - timeLow uint32 - clockSeqHighAndReserved uint8 - clockSeqLow uint8 - node [6]byte -} - -// Format enumerates the values that are supported by Parse and Format -type Format string - -// These constants define the possible string formats available via this implementation of Guid. -const ( - FormatB Format = "B" // {00000000-0000-0000-0000-000000000000} - FormatD Format = "D" // 00000000-0000-0000-0000-000000000000 - FormatN Format = "N" // 00000000000000000000000000000000 - FormatP Format = "P" // (00000000-0000-0000-0000-000000000000) - FormatX Format = "X" // {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} - FormatDefault Format = FormatD -) - -// CreationStrategy enumerates the values that are supported for populating the bits of a new Guid. -type CreationStrategy string - -// These constants define the possible creation strategies available via this implementation of Guid. -const ( - CreationStrategyVersion1 CreationStrategy = "version1" - CreationStrategyVersion2 CreationStrategy = "version2" - CreationStrategyVersion3 CreationStrategy = "version3" - CreationStrategyVersion4 CreationStrategy = "version4" - CreationStrategyVersion5 CreationStrategy = "version5" -) - -var emptyGUID GUID - -// NewGUID generates and returns a new globally unique identifier -func NewGUID() GUID { - result, err := version4() - if err != nil { - panic(err) //Version 4 (pseudo-random GUID) doesn't use anything that could fail. - } - return result -} - -var knownStrategies = map[CreationStrategy]func() (GUID, error){ - CreationStrategyVersion1: version1, - CreationStrategyVersion4: version4, -} - -// NewGUIDs generates and returns a new globally unique identifier that conforms to the given strategy. -func NewGUIDs(strategy CreationStrategy) (GUID, error) { - if creator, present := knownStrategies[strategy]; present { - result, err := creator() - return result, err - } - return emptyGUID, errors.New("Unsupported CreationStrategy") -} - -// Empty returns a copy of the default and empty GUID. -func Empty() GUID { - return emptyGUID -} - -var knownFormats = map[Format]string{ - FormatN: "%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x", - FormatD: "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", - FormatB: "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", - FormatP: "(%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x)", - FormatX: "{0x%08x,0x%04x,0x%04x,{0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x}}", -} - -// MarshalJSON writes a GUID as a JSON string. -func (guid GUID) MarshalJSON() (marshaled []byte, err error) { - buf := bytes.Buffer{} - - _, err = buf.WriteRune('"') - buf.WriteString(guid.String()) - buf.WriteRune('"') - - marshaled = buf.Bytes() - return -} - -// Parse instantiates a GUID from a text representation of the same GUID. -// This is the inverse of function family String() -func Parse(value string) (GUID, error) { - var guid GUID - for _, fullFormat := range knownFormats { - parity, err := fmt.Sscanf( - value, - fullFormat, - &guid.timeLow, - &guid.timeMid, - &guid.timeHighAndVersion, - &guid.clockSeqHighAndReserved, - &guid.clockSeqLow, - &guid.node[0], - &guid.node[1], - &guid.node[2], - &guid.node[3], - &guid.node[4], - &guid.node[5]) - if parity == 11 && err == nil { - return guid, err - } - } - return emptyGUID, fmt.Errorf("\"%s\" is not in a recognized format", value) -} - -// String returns a text representation of a GUID in the default format. -func (guid GUID) String() string { - return guid.Stringf(FormatDefault) -} - -// Stringf returns a text representation of a GUID that conforms to the specified format. -// If an unrecognized format is provided, the empty string is returned. -func (guid GUID) Stringf(format Format) string { - if format == "" { - format = FormatDefault - } - fullFormat, present := knownFormats[format] - if !present { - return "" - } - return fmt.Sprintf( - fullFormat, - guid.timeLow, - guid.timeMid, - guid.timeHighAndVersion, - guid.clockSeqHighAndReserved, - guid.clockSeqLow, - guid.node[0], - guid.node[1], - guid.node[2], - guid.node[3], - guid.node[4], - guid.node[5]) -} - -// UnmarshalJSON parses a GUID from a JSON string token. -func (guid *GUID) UnmarshalJSON(marshaled []byte) (err error) { - if len(marshaled) < 2 { - err = errors.New("JSON GUID must be surrounded by quotes") - return - } - stripped := marshaled[1 : len(marshaled)-1] - *guid, err = Parse(string(stripped)) - return -} - -// Version reads a GUID to parse which mechanism of generating GUIDS was employed. -// Values returned here are documented in rfc4122.txt. -func (guid GUID) Version() uint { - return uint(guid.timeHighAndVersion >> 12) -} - -var unixToGregorianOffset = time.Date(1970, 01, 01, 0, 0, 00, 0, time.UTC).Sub(time.Date(1582, 10, 15, 0, 0, 0, 0, time.UTC)) - -// getRFC4122Time returns a 60-bit count of 100-nanosecond intervals since 00:00:00.00 October 15th, 1582 -func getRFC4122Time() int64 { - currentTime := time.Now().UTC().Add(unixToGregorianOffset).UnixNano() - currentTime /= 100 - return currentTime & 0x0FFFFFFFFFFFFFFF -} - -var clockSeqVal uint16 -var clockSeqKey sync.Mutex - -func getClockSequence() (uint16, error) { - clockSeqKey.Lock() - defer clockSeqKey.Unlock() - - if 0 == clockSeqVal { - var temp [2]byte - if parity, err := rand.Read(temp[:]); !(2 == parity && nil == err) { - return 0, err - } - clockSeqVal = uint16(temp[0])<<8 | uint16(temp[1]) - } - clockSeqVal++ - return clockSeqVal, nil -} - -func getMACAddress() (mac [6]byte, err error) { - var hostNICs []net.Interface - - hostNICs, err = net.Interfaces() - if err != nil { - return - } - - for _, nic := range hostNICs { - var parity int - - parity, err = fmt.Sscanf( - strings.ToLower(nic.HardwareAddr.String()), - "%02x:%02x:%02x:%02x:%02x:%02x", - &mac[0], - &mac[1], - &mac[2], - &mac[3], - &mac[4], - &mac[5]) - - if parity == len(mac) { - return - } - } - - err = fmt.Errorf("No suitable address found") - - return -} - -func version1() (result GUID, err error) { - var localMAC [6]byte - var clockSeq uint16 - - currentTime := getRFC4122Time() - - result.timeLow = uint32(currentTime) - result.timeMid = uint16(currentTime >> 32) - result.timeHighAndVersion = uint16(currentTime >> 48) - if err = result.setVersion(1); err != nil { - return emptyGUID, err - } - - if localMAC, err = getMACAddress(); nil != err { - if parity, err := rand.Read(localMAC[:]); !(len(localMAC) != parity && err == nil) { - return emptyGUID, err - } - localMAC[0] |= 0x1 - } - copy(result.node[:], localMAC[:]) - - if clockSeq, err = getClockSequence(); nil != err { - return emptyGUID, err - } - - result.clockSeqLow = uint8(clockSeq) - result.clockSeqHighAndReserved = uint8(clockSeq >> 8) - - result.setReservedBits() - - return -} - -func version4() (GUID, error) { - var retval GUID - var bits [10]byte - - if parity, err := rand.Read(bits[:]); !(len(bits) == parity && err == nil) { - return emptyGUID, err - } - retval.timeHighAndVersion |= uint16(bits[0]) | uint16(bits[1])<<8 - retval.timeMid |= uint16(bits[2]) | uint16(bits[3])<<8 - retval.timeLow |= uint32(bits[4]) | uint32(bits[5])<<8 | uint32(bits[6])<<16 | uint32(bits[7])<<24 - retval.clockSeqHighAndReserved = uint8(bits[8]) - retval.clockSeqLow = uint8(bits[9]) - - //Randomly set clock-sequence, reserved, and node - if written, err := rand.Read(retval.node[:]); !(nil == err && written == len(retval.node)) { - retval = emptyGUID - return retval, err - } - - if err := retval.setVersion(4); nil != err { - return emptyGUID, err - } - retval.setReservedBits() - - return retval, nil -} - -func (guid *GUID) setVersion(version uint16) error { - if version > 5 || version == 0 { - return fmt.Errorf("While setting GUID version, unsupported version: %d", version) - } - guid.timeHighAndVersion = (guid.timeHighAndVersion & 0x0fff) | version<<12 - return nil -} - -func (guid *GUID) setReservedBits() { - guid.clockSeqHighAndReserved = (guid.clockSeqHighAndReserved & 0x3f) | 0x80 -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 92d451b92..5832c9c93 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -6,23 +6,31 @@ cloud.google.com/go/internal/optional cloud.google.com/go/internal/trace cloud.google.com/go/internal/version cloud.google.com/go/compute/metadata -# github.com/Azure/azure-sdk-for-go v21.3.0+incompatible +# github.com/Azure/azure-sdk-for-go v36.2.0+incompatible github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/storage/mgmt/storage github.com/Azure/azure-sdk-for-go/storage github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-02-01/resources github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2016-01-01/storage github.com/Azure/azure-sdk-for-go/version -# github.com/Azure/go-autorest v10.15.4+incompatible +github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac +# github.com/Azure/go-autorest/autorest v0.9.2 github.com/Azure/go-autorest/autorest -github.com/Azure/go-autorest/autorest/adal github.com/Azure/go-autorest/autorest/azure -github.com/Azure/go-autorest/logger -github.com/Azure/go-autorest/version -github.com/Azure/go-autorest/autorest/date +# github.com/Azure/go-autorest/autorest/adal v0.8.1-0.20191028180845-3492b2aff503 +github.com/Azure/go-autorest/autorest/adal +# github.com/Azure/go-autorest/autorest/azure/cli v0.2.0 github.com/Azure/go-autorest/autorest/azure/cli +# github.com/Azure/go-autorest/autorest/date v0.2.0 +github.com/Azure/go-autorest/autorest/date +# github.com/Azure/go-autorest/autorest/to v0.3.0 github.com/Azure/go-autorest/autorest/to +# github.com/Azure/go-autorest/autorest/validation v0.2.0 github.com/Azure/go-autorest/autorest/validation +# github.com/Azure/go-autorest/logger v0.1.0 +github.com/Azure/go-autorest/logger +# github.com/Azure/go-autorest/tracing v0.5.0 +github.com/Azure/go-autorest/tracing # github.com/Azure/go-ntlmssp v0.0.0-20180810175552-4a21cbd618b4 github.com/Azure/go-ntlmssp # github.com/ChrisTrenkamp/goxpath v0.0.0-20170922090931-c385f95c6022 @@ -153,7 +161,7 @@ github.com/coreos/go-semver/semver github.com/davecgh/go-spew/spew # github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/dgrijalva/jwt-go -# github.com/dimchansky/utfbom v1.0.0 +# github.com/dimchansky/utfbom v1.1.0 github.com/dimchansky/utfbom # github.com/dylanmei/iso8601 v0.1.0 github.com/dylanmei/iso8601 @@ -293,8 +301,9 @@ github.com/hashicorp/consul/lib/freeport github.com/hashicorp/consul/testutil/retry # github.com/hashicorp/errwrap v1.0.0 github.com/hashicorp/errwrap -# github.com/hashicorp/go-azure-helpers v0.0.0-20190129193224-166dfd221bb2 +# github.com/hashicorp/go-azure-helpers v0.10.0 github.com/hashicorp/go-azure-helpers/authentication +github.com/hashicorp/go-azure-helpers/sender github.com/hashicorp/go-azure-helpers/storage # github.com/hashicorp/go-checkpoint v0.5.0 github.com/hashicorp/go-checkpoint @@ -404,8 +413,6 @@ github.com/lib/pq github.com/lib/pq/oid # github.com/lusis/go-artifactory v0.0.0-20160115162124-7e4ce345df82 github.com/lusis/go-artifactory/src/artifactory.v401 -# github.com/marstr/guid v1.1.0 -github.com/marstr/guid # github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9 github.com/masterzen/simplexml/dom # github.com/masterzen/winrm v0.0.0-20190223112901-5e5c9a7fe54b