From 19408a1e39e9f001a6c10dc63e2dc4ce7370eae4 Mon Sep 17 00:00:00 2001 From: Javier Darsie <44655727+jadarsie@users.noreply.github.com> Date: Wed, 1 May 2024 10:26:03 -0700 Subject: [PATCH] chore: remove support for CLI & DEVICE auth methods (#244) --- Makefile | 2 +- cmd/deploy.go | 29 +- cmd/deploy_test.go | 57 - cmd/root.go | 11 +- docs/topics/addpool.md | 2 +- docs/topics/creating_new_clusters.md | 2 +- docs/topics/scale.md | 2 +- docs/topics/upgrade.md | 2 +- docs/tutorials/cli-overview.md | 8 +- go.mod | 5 +- go.sum | 9 - pkg/armhelpers/azureclient.go | 290 +- pkg/armhelpers/azurestack/azureclient.go | 126 +- pkg/armhelpers/azurestack/compute.go | 13 - pkg/armhelpers/azurestack/graph.go | 77 - pkg/armhelpers/azurestack/msi.go | 15 - pkg/armhelpers/graph.go | 154 - pkg/armhelpers/interfaces.go | 24 - pkg/armhelpers/mockclients.go | 70 - pkg/armhelpers/msi.go | 25 - pkg/operations/deletevm.go | 24 - .../kubernetesupgrade/upgradecluster_test.go | 26 - test/e2e/config/config.go | 1 - test/e2e/go.mod | 3 - test/e2e/go.sum | 9 - test/e2e/kubernetes/kubernetes_test.go | 363 -- .../kubernetes/scripts/vmss-health-check.sh | 82 - .../graphrbac/1.6/graphrbac/applications.go | 1164 ---- .../graphrbac/1.6/graphrbac/client.go | 52 - .../1.6/graphrbac/deletedapplications.go | 363 -- .../graphrbac/1.6/graphrbac/domains.go | 192 - .../graphrbac/1.6/graphrbac/groups.go | 1211 ----- .../graphrbac/1.6/graphrbac/models.go | 4679 ----------------- .../1.6/graphrbac/oauth2permissiongrant.go | 367 -- .../graphrbac/1.6/graphrbac/objects.go | 215 - .../1.6/graphrbac/serviceprincipals.go | 933 ---- .../graphrbac/1.6/graphrbac/signedinuser.go | 281 - .../services/graphrbac/1.6/graphrbac/users.go | 612 --- .../graphrbac/1.6/graphrbac/version.go | 30 - .../go-autorest/autorest/azure/cli/LICENSE | 191 - .../autorest/azure/cli/go_mod_tidy_hack.go | 24 - .../go-autorest/autorest/azure/cli/profile.go | 79 - .../go-autorest/autorest/azure/cli/token.go | 170 - .../github.com/dimchansky/utfbom/.gitignore | 37 - .../github.com/dimchansky/utfbom/.travis.yml | 18 - vendor/github.com/dimchansky/utfbom/LICENSE | 201 - vendor/github.com/dimchansky/utfbom/README.md | 66 - vendor/github.com/dimchansky/utfbom/utfbom.go | 192 - .../github.com/mitchellh/go-homedir/LICENSE | 21 - .../github.com/mitchellh/go-homedir/README.md | 14 - .../mitchellh/go-homedir/homedir.go | 167 - vendor/modules.txt | 10 - 52 files changed, 91 insertions(+), 12629 deletions(-) delete mode 100644 pkg/armhelpers/azurestack/graph.go delete mode 100644 pkg/armhelpers/azurestack/msi.go delete mode 100644 pkg/armhelpers/graph.go delete mode 100644 pkg/armhelpers/msi.go delete mode 100755 test/e2e/kubernetes/scripts/vmss-health-check.sh delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/applications.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/deletedapplications.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/domains.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/groups.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/oauth2permissiongrant.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/objects.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/serviceprincipals.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/signedinuser.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/users.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/version.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go delete mode 100644 vendor/github.com/dimchansky/utfbom/.gitignore delete mode 100644 vendor/github.com/dimchansky/utfbom/.travis.yml delete mode 100644 vendor/github.com/dimchansky/utfbom/LICENSE delete mode 100644 vendor/github.com/dimchansky/utfbom/README.md delete mode 100644 vendor/github.com/dimchansky/utfbom/utfbom.go delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.go diff --git a/Makefile b/Makefile index 28f33978e..9d09e15da 100644 --- a/Makefile +++ b/Makefile @@ -133,7 +133,7 @@ ginkgoBuild: generate make -C ./test/e2e ginkgo-build test: generate - ginkgo -mod=vendor -junit-report test/junit/junit.xml -skip-package test/e2e -fail-fast -r -v -tags=fast . + ginkgo -mod=vendor -junit-report junit.xml -skip-package test/e2e -fail-fast -r -v -tags=fast . .PHONY: test-style test-style: validate-go validate-shell validate-copyright-headers diff --git a/cmd/deploy.go b/cmd/deploy.go index cdbb54250..b9ff4f588 100644 --- a/cmd/deploy.go +++ b/cmd/deploy.go @@ -28,7 +28,6 @@ import ( "github.com/Azure/aks-engine-azurestack/pkg/engine/transform" "github.com/Azure/aks-engine-azurestack/pkg/helpers" "github.com/Azure/aks-engine-azurestack/pkg/i18n" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" "github.com/Azure/go-autorest/autorest/to" "github.com/pkg/errors" ) @@ -348,33 +347,7 @@ func autofillApimodel(dc *deployCmd) error { if !useManagedIdentity { spp := dc.containerService.Properties.ServicePrincipalProfile if spp != nil && spp.ClientID == "" && spp.Secret == "" && spp.KeyvaultSecretRef == nil && (dc.getAuthArgs().ClientID.String() == "" || dc.getAuthArgs().ClientID.String() == "00000000-0000-0000-0000-000000000000") && dc.getAuthArgs().ClientSecret == "" { - log.Warnln("apimodel: ServicePrincipalProfile was missing or empty, creating application...") - - // TODO: consider caching the creds here so they persist between subsequent runs of 'deploy' - appName := dc.containerService.Properties.MasterProfile.DNSPrefix - appURL := fmt.Sprintf("https://%s/", appName) - var replyURLs *[]string - var requiredResourceAccess *[]graphrbac.RequiredResourceAccess - applicationResp, servicePrincipalObjectID, secret, createErr := dc.client.CreateApp(ctx, appName, appURL, replyURLs, requiredResourceAccess) - if createErr != nil { - return errors.Wrap(createErr, "apimodel invalid: ServicePrincipalProfile was empty, and we failed to create valid credentials") - } - applicationID := to.String(applicationResp.AppID) - log.Warnf("created application with applicationID (%s) and servicePrincipalObjectID (%s).", applicationID, servicePrincipalObjectID) - - log.Warnln("apimodel: ServicePrincipalProfile was empty, assigning role to application...") - - err = dc.client.CreateRoleAssignmentSimple(ctx, dc.resourceGroup, servicePrincipalObjectID) - if err != nil { - return errors.Wrap(err, "apimodel: could not create or assign ServicePrincipal") - - } - - dc.containerService.Properties.ServicePrincipalProfile = &api.ServicePrincipalProfile{ - ClientID: applicationID, - Secret: secret, - ObjectID: servicePrincipalObjectID, - } + log.Warnln("apimodel: ServicePrincipalProfile missing or empty...") } else if (dc.containerService.Properties.ServicePrincipalProfile == nil || ((dc.containerService.Properties.ServicePrincipalProfile.ClientID == "" || dc.containerService.Properties.ServicePrincipalProfile.ClientID == "00000000-0000-0000-0000-000000000000") && dc.containerService.Properties.ServicePrincipalProfile.Secret == "")) && dc.getAuthArgs().ClientID.String() != "" && dc.getAuthArgs().ClientSecret != "" { dc.containerService.Properties.ServicePrincipalProfile = &api.ServicePrincipalProfile{ ClientID: dc.getAuthArgs().ClientID.String(), diff --git a/cmd/deploy_test.go b/cmd/deploy_test.go index 48afa15ee..32625b081 100644 --- a/cmd/deploy_test.go +++ b/cmd/deploy_test.go @@ -266,12 +266,6 @@ func TestValidate(t *testing.T) { } } -func TestAutofillApimodelWithoutManagedIdentityCreatesCreds(t *testing.T) { - t.Parallel() - - testAutodeployCredentialHandling(t, false, "", "") -} - func TestAutofillApimodelWithManagedIdentitySkipsCreds(t *testing.T) { t.Parallel() @@ -480,57 +474,6 @@ func TestAPIModelWithoutServicePrincipalProfileAndWithoutClientIdAndSecretInCmd( } -func TestAPIModelWithEmptyServicePrincipalProfileAndWithoutClientIdAndSecretInCmd(t *testing.T) { - t.Parallel() - - apiloader := &api.Apiloader{ - Translator: nil, - } - - apimodel := getAPIModel(ExampleAPIModelWithDNSPrefix, false, "", "") - - cs, ver, err := apiloader.DeserializeContainerService([]byte(apimodel), false, false, nil) - if err != nil { - t.Fatalf("unexpected error deserializing the example apimodel: %s", err) - } - - outDir, del := makeTmpDir(t) - defer del() - - deployCmd := &deployCmd{ - apimodelPath: "./this/is/unused.json", - outputDirectory: outDir, - forceOverwrite: true, - location: "westus", - containerService: cs, - apiVersion: ver, - - client: &armhelpers.MockAKSEngineClient{}, - authProvider: &mockAuthProvider{ - authArgs: &authArgs{}, - }, - } - err = autofillApimodel(deployCmd) - if err != nil { - t.Fatalf("unexpected error autofilling the example apimodel: %s", err) - } - - if deployCmd.containerService.Properties.ServicePrincipalProfile == nil { - t.Fatalf("expected service principal profile to be Empty and not nil for unmanaged identity, where client id and secret are not supplied in api model and deployment command") - } - - // mockclient returns "app-id" for ClientID when empty - if deployCmd.containerService.Properties.ServicePrincipalProfile.ClientID != "app-id" { - t.Fatalf("expected service principal profile client id to be empty but got %s", deployCmd.containerService.Properties.ServicePrincipalProfile.ClientID) - } - - // mockcliet returns "client-secret" when empty - if deployCmd.containerService.Properties.ServicePrincipalProfile.Secret != "client-secret" { - t.Fatalf("expected service principal profile client secret to be empty but got %s", deployCmd.containerService.Properties.ServicePrincipalProfile.Secret) - } - -} - func testAutodeployCredentialHandling(t *testing.T, useManagedIdentity bool, clientID, clientSecret string) { apiloader := &api.Apiloader{ Translator: nil, diff --git a/cmd/root.go b/cmd/root.go index c44278e88..b5bd3c72a 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -122,7 +122,7 @@ type authArgs struct { func addAuthFlags(authArgs *authArgs, f *flag.FlagSet) { f.StringVar(&authArgs.RawAzureEnvironment, "azure-env", "AzurePublicCloud", "the target Azure cloud") f.StringVarP(&authArgs.rawSubscriptionID, "subscription-id", "s", "", "azure subscription id (required)") - f.StringVar(&authArgs.AuthMethod, "auth-method", "cli", "auth method (default:`client_secret`, `cli`, `client_certificate`, `device`)") + f.StringVar(&authArgs.AuthMethod, "auth-method", "client_secret", "auth method (default:`client_secret`, `client_certificate`)") f.StringVar(&authArgs.rawClientID, "client-id", "", "client id (used with --auth-method=[client_secret|client_certificate])") f.StringVar(&authArgs.ClientSecret, "client-secret", "", "client secret (used with --auth-method=client_secret)") f.StringVar(&authArgs.CertificatePath, "certificate-path", "", "path to client certificate (used with --auth-method=client_certificate)") @@ -146,11 +146,6 @@ func (authArgs *authArgs) validateAuthArgs() error { return errors.New("--auth-method is a required parameter") } - // Back-compat to accommodate existing client usage patterns that assume that "client-secret" is the default - if authArgs.AuthMethod == "cli" && authArgs.rawClientID != "" && authArgs.ClientSecret != "" { - authArgs.AuthMethod = "client_secret" - } - if authArgs.AuthMethod == "client_secret" || authArgs.AuthMethod == "client_certificate" { authArgs.ClientID, err = uuid.Parse(authArgs.rawClientID) if err != nil { @@ -237,10 +232,6 @@ func (authArgs *authArgs) getAzureClient() (armhelpers.AKSEngineClient, error) { return nil, err } switch authArgs.AuthMethod { - case "cli": - client, err = armhelpers.NewAzureClientWithCLI(env, authArgs.SubscriptionID.String()) - case "device": - client, err = armhelpers.NewAzureClientWithDeviceAuth(env, authArgs.SubscriptionID.String()) case "client_secret": client, err = armhelpers.NewAzureClientWithClientSecret(env, authArgs.SubscriptionID.String(), authArgs.ClientID.String(), authArgs.ClientSecret) case "client_certificate": diff --git a/docs/topics/addpool.md b/docs/topics/addpool.md index 9edb6de03..e1a490f8d 100644 --- a/docs/topics/addpool.md +++ b/docs/topics/addpool.md @@ -60,7 +60,7 @@ Some important considerations: |--client-secret|depends| The Service Principal Client secret. This is required if the auth-method is set to client_secret| |--certificate-path|depends| The path to the file which contains the client certificate. This is required if the auth-method is set to client_certificate| |--node-pool|yes|Path to JSON file expressing the `agentPoolProfile` spec of the new node pool.| -|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `cli`, `client_certificate`, and `device`.| +|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `client_certificate`.| |--language|no|Language to return error message in. Default value is "en-us").| ## Frequently Asked Questions diff --git a/docs/topics/creating_new_clusters.md b/docs/topics/creating_new_clusters.md index bb0a7080e..412cbc595 100644 --- a/docs/topics/creating_new_clusters.md +++ b/docs/topics/creating_new_clusters.md @@ -36,7 +36,7 @@ A more detailed walk-through of `aks-engine-azurestack deploy` is in the [quicks |--client-secret|depends| The Service Principal Client secret. This is required if the auth-method is set to client_secret| |--certificate-path|depends| The path to the file which contains the client certificate. This is required if the auth-method is set to client_certificate| |--identity-system|no|Identity system (default is azure_ad)| -|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `cli`, `client_certificate`, and `device`.| +|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `client_certificate`.| |--private-key-path|no|Path to private key (used with --auth-method=client_certificate).| |--language|no|Language to return error message in. Default value is "en-us").| diff --git a/docs/topics/scale.md b/docs/topics/scale.md index b67b58e75..867639872 100644 --- a/docs/topics/scale.md +++ b/docs/topics/scale.md @@ -39,7 +39,7 @@ This command will re-use the `apimodel.json` file inside the output directory as |--node-pool|depends|Required if there is more than one node pool. Which node pool should be scaled.| |--new-node-count|yes|Desired number of nodes in the node pool.| |--apiserver|when scaling down|apiserver endpoint (required to cordon and drain nodes). This should be output as part of the create template or it can be found by looking at the public ip addresses in the resource group.| -|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `cli`, `client_certificate`, and `device`.| +|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `client_certificate`.| |--language|no|Language to return error message in. Default value is "en-us").| ## Frequently Asked Questions diff --git a/docs/topics/upgrade.md b/docs/topics/upgrade.md index cb59b97ac..003eaf262 100644 --- a/docs/topics/upgrade.md +++ b/docs/topics/upgrade.md @@ -72,7 +72,7 @@ In summary, using `aks-engine-azurestack upgrade` means you will freshen and re- |--client-secret|depends| The Service Principal Client secret. This is required if the auth-method is set to client_secret| |--certificate-path|depends| The path to the file which contains the client certificate. This is required if the auth-method is set to client_certificate| |--identity-system|no|Identity system (default is azure_ad)| -|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `cli`, `client_certificate`, and `device`.| +|--auth-method|no|The authentication method used. Default value is `client_secret`. Other supported values are: `client_certificate`.| |--private-key-path|no|Path to private key (used with --auth-method=client_certificate).| |--language|no|Language to return error message in. Default value is "en-us").| diff --git a/docs/tutorials/cli-overview.md b/docs/tutorials/cli-overview.md index 20a9fed6d..3eead4fc5 100644 --- a/docs/tutorials/cli-overview.md +++ b/docs/tutorials/cli-overview.md @@ -50,7 +50,7 @@ Usage: Flags: -m, --api-model string path to your cluster definition file - --auth-method client_secret auth method (default:client_secret, `cli`, `client_certificate`, `device`) (default "cli") + --auth-method client_secret auth method (default:client_secret, `client_certificate`) --auto-suffix automatically append a compressed timestamp to the dnsPrefix to ensure unique cluster name automatically --azure-env string the target Azure cloud (default "AzurePublicCloud") --ca-certificate-path string path to the CA certificate to use for Kubernetes PKI assets @@ -90,7 +90,7 @@ Usage: Flags: -m, --api-model string path to the generated apimodel.json file --apiserver string apiserver endpoint (required to cordon and drain nodes) - --auth-method client_secret auth method (default:client_secret, `cli`, `client_certificate`, `device`) (default "cli") + --auth-method client_secret auth method (default:client_secret, `client_certificate`) --azure-env string the target Azure cloud (default "AzurePublicCloud") --certificate-path string path to client certificate (used with --auth-method=client_certificate) --client-id string client id (used with --auth-method=[client_secret|client_certificate]) @@ -131,7 +131,7 @@ Usage: Flags: -m, --api-model string path to the generated apimodel.json file - --auth-method client_secret auth method (default:client_secret, `cli`, `client_certificate`, `device`) (default "cli") + --auth-method client_secret auth method (default:client_secret, `client_certificate`) --azure-env string the target Azure cloud (default "AzurePublicCloud") --certificate-path string path to client certificate (used with --auth-method=client_certificate) --client-id string client id (used with --auth-method=[client_secret|client_certificate]) @@ -164,7 +164,7 @@ Usage: Flags: -m, --api-model string path to the generated apimodel.json file - --auth-method client_secret auth method (default:client_secret, `cli`, `client_certificate`, `device`) (default "cli") + --auth-method client_secret auth method (default:client_secret, `client_certificate`) --azure-env string the target Azure cloud (default "AzurePublicCloud") --certificate-path string path to client certificate (used with --auth-method=client_certificate) --client-id string client id (used with --auth-method=[client_secret|client_certificate]) diff --git a/go.mod b/go.mod index 4018b7fa9..5967a9492 100644 --- a/go.mod +++ b/go.mod @@ -7,8 +7,6 @@ require ( github.com/Azure/azure-storage-blob-go v0.7.0 github.com/Azure/go-autorest/autorest v0.11.12 github.com/Azure/go-autorest/autorest/adal v0.9.10 - github.com/Azure/go-autorest/autorest/azure/cli v0.3.0 - github.com/Azure/go-autorest/autorest/date v0.3.0 github.com/Azure/go-autorest/autorest/to v0.3.0 github.com/BurntSushi/toml v0.3.1 github.com/Jeffail/gabs v1.1.1 @@ -22,7 +20,6 @@ require ( github.com/jarcoal/httpmock v1.0.1 github.com/leonelquinteros/gotext v1.4.0 github.com/mattn/go-colorable v0.0.9 - github.com/mitchellh/go-homedir v1.1.0 github.com/onsi/ginkgo/v2 v2.17.1 github.com/onsi/gomega v1.30.0 github.com/pkg/errors v0.9.1 @@ -43,10 +40,10 @@ require ( require ( github.com/Azure/azure-pipeline-go v0.2.1 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect + github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.2.0 // indirect github.com/Azure/go-autorest/logger v0.2.0 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect - github.com/dimchansky/utfbom v1.1.0 // indirect github.com/dnaeon/go-vcr v1.0.1 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/form3tech-oss/jwt-go v3.2.2+incompatible // indirect diff --git a/go.sum b/go.sum index 2037a3c2a..931f43028 100644 --- a/go.sum +++ b/go.sum @@ -11,19 +11,14 @@ github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+B github.com/Azure/go-autorest/autorest v0.11.12 h1:gI8ytXbxMfI+IVbI9mP2JGCTXIuhHLgRlvQ9X4PsnHE= github.com/Azure/go-autorest/autorest v0.11.12/go.mod h1:eipySxLmqSyC5s5k1CLupqet0PSENBEDP93LQ9a8QYw= github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= -github.com/Azure/go-autorest/autorest/adal v0.6.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= github.com/Azure/go-autorest/autorest/adal v0.9.10 h1:r6fZHMaHD8B6LDCn0o5vyBFHIHrM6Ywwx7mb49lPItI= github.com/Azure/go-autorest/autorest/adal v0.9.10/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= -github.com/Azure/go-autorest/autorest/azure/cli v0.3.0 h1:5PAqnv+CSTwW9mlZWZAizmzrazFWEgZykEZXpr2hDtY= -github.com/Azure/go-autorest/autorest/azure/cli v0.3.0/go.mod h1:rNYMNAefZMRowqCV0cVhr/YDW5dD7afFq9nXAXL4ykE= 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/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= 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/mocks v0.4.1 h1:K0laFcLE6VLTOwNgSxaGbUcLPuGXlNkbVvq4cW4nIHk= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/to v0.3.0 h1:zebkZaadz7+wIQYgC7GXaz3Wb28yKYfVkkBKwc38VF8= @@ -52,8 +47,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/dnaeon/go-vcr v1.0.1 h1:r8L/HqC0Hje5AXMu1ooW8oyQyOFv4GxqpL0nRP7SLLY= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= @@ -161,8 +154,6 @@ github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW1 github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= diff --git a/pkg/armhelpers/azureclient.go b/pkg/armhelpers/azureclient.go index 9c4ffaa90..2bc48fc97 100644 --- a/pkg/armhelpers/azureclient.go +++ b/pkg/armhelpers/azureclient.go @@ -11,18 +11,14 @@ import ( "fmt" "net/http" "os" - "path/filepath" "strings" "time" "github.com/Azure/aks-engine-azurestack/pkg/engine" "github.com/Azure/aks-engine-azurestack/pkg/kubernetes" - "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2017-03-01/apimanagement" "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-08-01/network" - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" @@ -30,9 +26,7 @@ import ( "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/autorest/azure/cli" "github.com/Azure/go-autorest/autorest/to" - homedir "github.com/mitchellh/go-homedir" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -55,28 +49,19 @@ type AzureClient struct { environment azure.Environment subscriptionID string - authorizationClient authorization.RoleAssignmentsClient - deploymentsClient resources.DeploymentsClient - deploymentOperationsClient resources.DeploymentOperationsClient - msiClient msi.UserAssignedIdentitiesClient - resourcesClient apimanagement.GroupClient - resourceSkusClient compute.ResourceSkusClient - storageAccountsClient storage.AccountsClient - interfacesClient network.InterfacesClient - groupsClient resources.GroupsClient - subscriptionsClient subscriptions.Client - providersClient resources.ProvidersClient - virtualMachinesClient compute.VirtualMachinesClient - virtualMachineScaleSetsClient compute.VirtualMachineScaleSetsClient - virtualMachineScaleSetVMsClient compute.VirtualMachineScaleSetVMsClient - virtualMachineExtensionsClient compute.VirtualMachineExtensionsClient - disksClient compute.DisksClient - availabilitySetsClient compute.AvailabilitySetsClient - workspacesClient operationalinsights.WorkspacesClient - virtualMachineImagesClient compute.VirtualMachineImagesClient - - applicationsClient graphrbac.ApplicationsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient + authorizationClient authorization.RoleAssignmentsClient + deploymentsClient resources.DeploymentsClient + deploymentOperationsClient resources.DeploymentOperationsClient + storageAccountsClient storage.AccountsClient + interfacesClient network.InterfacesClient + groupsClient resources.GroupsClient + subscriptionsClient subscriptions.Client + providersClient resources.ProvidersClient + virtualMachinesClient compute.VirtualMachinesClient + disksClient compute.DisksClient + availabilitySetsClient compute.AvailabilitySetsClient + workspacesClient operationalinsights.WorkspacesClient + virtualMachineImagesClient compute.VirtualMachineImagesClient } // GetKubernetesClient returns a KubernetesClient hooked up to the api server at the apiserverURL. @@ -84,109 +69,9 @@ func (az *AzureClient) GetKubernetesClient(apiserverURL, kubeConfig string, inte return kubernetes.NewClient(apiserverURL, kubeConfig, interval, timeout) } -// NewAzureClientWithCLI creates an AzureClient configured from Azure CLI 2.0 for local development scenarios. -func NewAzureClientWithCLI(env azure.Environment, subscriptionID string) (*AzureClient, error) { - _, tenantID, err := getOAuthConfig(env, subscriptionID) - if err != nil { - return nil, err - } - - token, err := cli.GetTokenFromCLI(env.ResourceManagerEndpoint) - if err != nil { - return nil, err - } - - adalToken, err := token.ToADALToken() - if err != nil { - return nil, err - } - - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(&adalToken), autorest.NewBearerAuthorizer(&adalToken)), nil -} - -// NewAzureClientWithDeviceAuth returns an AzureClient by having a user complete a device authentication flow -func NewAzureClientWithDeviceAuth(env azure.Environment, subscriptionID string) (*AzureClient, error) { - oauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID) - if err != nil { - return nil, err - } - - // aksEngineClientID is the AAD ClientID for the CLI native application - aksEngineClientID := getAksEngineClientID(env.Name) - - home, err := homedir.Dir() - if err != nil { - return nil, errors.Wrap(err, "Failed to get user home directory to look for cached token") - } - cachePath := filepath.Join(home, ApplicationDir, "cache", fmt.Sprintf("%s_%s.token.json", tenantID, aksEngineClientID)) - - rawToken, err := tryLoadCachedToken(cachePath) - if err != nil { - return nil, err - } - - var armSpt *adal.ServicePrincipalToken - if rawToken != nil { - armSpt, err = adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, aksEngineClientID, env.ServiceManagementEndpoint, *rawToken, tokenCallback(cachePath)) - if err != nil { - return nil, err - } - err = armSpt.Refresh() - if err != nil { - log.Warnf("Refresh token failed. Will fallback to device auth. %q", err) - } else { - var graphSpt *adal.ServicePrincipalToken - graphSpt, err = adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, aksEngineClientID, env.GraphEndpoint, armSpt.Token()) - if err != nil { - return nil, err - } - err = graphSpt.Refresh() - if err != nil { - return nil, err - } - - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil - } - } - - client := &autorest.Client{ - PollingDuration: DefaultARMOperationTimeout, - } - - deviceCode, err := adal.InitiateDeviceAuth(client, *oauthConfig, aksEngineClientID, env.ServiceManagementEndpoint) - if err != nil { - return nil, err - } - log.Warnln(*deviceCode.Message) - deviceToken, err := adal.WaitForUserCompletion(client, deviceCode) - if err != nil { - return nil, err - } - - armSpt, err = adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, aksEngineClientID, env.ServiceManagementEndpoint, *deviceToken, tokenCallback(cachePath)) - if err != nil { - return nil, err - } - if err = armSpt.Refresh(); err != nil { - log.Error(err) - } - - adRawToken := armSpt.Token() - adRawToken.Resource = env.GraphEndpoint - graphSpt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, aksEngineClientID, env.GraphEndpoint, adRawToken) - if err != nil { - return nil, err - } - if err = graphSpt.Refresh(); err != nil { - log.Error(err) - } - - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil -} - // NewAzureClientWithClientSecret returns an AzureClient via client_id and client_secret func NewAzureClientWithClientSecret(env azure.Environment, subscriptionID, clientID, clientSecret string) (*AzureClient, error) { - oauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID) + oauthConfig, err := getOAuthConfig(env, subscriptionID) if err != nil { return nil, err } @@ -203,7 +88,7 @@ func NewAzureClientWithClientSecret(env azure.Environment, subscriptionID, clien log.Error(err) } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } // NewAzureClientWithClientSecretExternalTenant returns an AzureClient via client_id and client_secret from a tenant @@ -217,15 +102,8 @@ func NewAzureClientWithClientSecretExternalTenant(env azure.Environment, subscri if err != nil { return nil, err } - graphSpt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, env.GraphEndpoint) - if err != nil { - return nil, err - } - if err = graphSpt.Refresh(); err != nil { - log.Error(err) - } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } // NewAzureClientWithClientCertificateFile returns an AzureClient via client_id and jwt certificate assertion @@ -255,12 +133,12 @@ func NewAzureClientWithClientCertificateFile(env azure.Environment, subscription // NewAzureClientWithClientCertificate returns an AzureClient via client_id and jwt certificate assertion func NewAzureClientWithClientCertificate(env azure.Environment, subscriptionID, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { - oauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID) + oauthConfig, err := getOAuthConfig(env, subscriptionID) if err != nil { return nil, err } - return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, tenantID, certificate, privateKey) + return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, certificate, privateKey) } // NewAzureClientWithClientCertificateExternalTenant returns an AzureClient via client_id and jwt certificate assertion against a 3rd party tenant @@ -270,10 +148,10 @@ func NewAzureClientWithClientCertificateExternalTenant(env azure.Environment, su return nil, err } - return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, tenantID, certificate, privateKey) + return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, certificate, privateKey) } -func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAuthConfig, subscriptionID, clientID, tenantID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { +func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAuthConfig, subscriptionID, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { if certificate == nil { return nil, errors.New("certificate should not be nil") } @@ -286,98 +164,42 @@ func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAut if err != nil { return nil, err } - graphSpt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, clientID, certificate, privateKey, env.GraphEndpoint) - if err != nil { - return nil, err - } - if err = graphSpt.Refresh(); err != nil { - log.Error(err) - } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil -} - -func tokenCallback(path string) func(t adal.Token) error { - return func(token adal.Token) error { - err := adal.SaveToken(path, 0600, token) - if err != nil { - return err - } - log.Debugf("Saved token to cache. path=%q", path) - return nil - } + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } -func tryLoadCachedToken(cachePath string) (*adal.Token, error) { - log.Debugf("Attempting to load token from cache. path=%q", cachePath) - - // Check for file not found so we can suppress the file not found error - // LoadToken doesn't discern and returns error either way - if _, err := os.Stat(cachePath); err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, err - } - - token, err := adal.LoadToken(cachePath) - if err != nil { - return nil, errors.Wrap(err, "Failed to load token from file") - } - - return token, nil -} - -func getOAuthConfig(env azure.Environment, subscriptionID string) (*adal.OAuthConfig, string, error) { +func getOAuthConfig(env azure.Environment, subscriptionID string) (*adal.OAuthConfig, error) { tenantID, err := engine.GetTenantID(env.ResourceManagerEndpoint, subscriptionID) if err != nil { - return nil, "", err + return nil, err } oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, tenantID) if err != nil { - return nil, "", err + return nil, err } - return oauthConfig, tenantID, nil + return oauthConfig, nil } -func getAksEngineClientID(envName string) string { - switch envName { - case "AzureUSGovernmentCloud": - return "e8b7f94b-85c9-47f4-964a-98dafd7fc2d8" - default: - return "76e0feec-6b7f-41f0-81a7-b1b944520261" - } -} - -func getClient(env azure.Environment, subscriptionID, tenantID string, armAuthorizer autorest.Authorizer, graphAuthorizer autorest.Authorizer) *AzureClient { +func getClient(env azure.Environment, subscriptionID string, armAuthorizer autorest.Authorizer) *AzureClient { c := &AzureClient{ environment: env, subscriptionID: subscriptionID, - authorizationClient: authorization.NewRoleAssignmentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - deploymentsClient: resources.NewDeploymentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - deploymentOperationsClient: resources.NewDeploymentOperationsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - msiClient: msi.NewUserAssignedIdentitiesClient(subscriptionID), - resourcesClient: apimanagement.NewGroupClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - resourceSkusClient: compute.NewResourceSkusClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - storageAccountsClient: storage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - interfacesClient: network.NewInterfacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - groupsClient: resources.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - subscriptionsClient: subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint), - providersClient: resources.NewProvidersClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachinesClient: compute.NewVirtualMachinesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineScaleSetsClient: compute.NewVirtualMachineScaleSetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineScaleSetVMsClient: compute.NewVirtualMachineScaleSetVMsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineExtensionsClient: compute.NewVirtualMachineExtensionsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - disksClient: compute.NewDisksClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - availabilitySetsClient: compute.NewAvailabilitySetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - workspacesClient: operationalinsights.NewWorkspacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineImagesClient: compute.NewVirtualMachineImagesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - - applicationsClient: graphrbac.NewApplicationsClientWithBaseURI(env.GraphEndpoint, tenantID), - servicePrincipalsClient: graphrbac.NewServicePrincipalsClientWithBaseURI(env.GraphEndpoint, tenantID), + authorizationClient: authorization.NewRoleAssignmentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + deploymentsClient: resources.NewDeploymentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + deploymentOperationsClient: resources.NewDeploymentOperationsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + storageAccountsClient: storage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + interfacesClient: network.NewInterfacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + groupsClient: resources.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + subscriptionsClient: subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint), + providersClient: resources.NewProvidersClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + virtualMachinesClient: compute.NewVirtualMachinesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + disksClient: compute.NewDisksClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + availabilitySetsClient: compute.NewAvailabilitySetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + workspacesClient: operationalinsights.NewWorkspacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + virtualMachineImagesClient: compute.NewVirtualMachineImagesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), } c.authorizationClient.Authorizer = armAuthorizer @@ -387,27 +209,16 @@ func getClient(env azure.Environment, subscriptionID, tenantID string, armAuthor c.disksClient.Authorizer = armAuthorizer c.groupsClient.Authorizer = armAuthorizer c.interfacesClient.Authorizer = armAuthorizer - c.msiClient.Authorizer = armAuthorizer c.providersClient.Authorizer = armAuthorizer - c.resourcesClient.Authorizer = armAuthorizer - c.resourceSkusClient.Authorizer = armAuthorizer c.storageAccountsClient.Authorizer = armAuthorizer c.subscriptionsClient.Authorizer = armAuthorizer - c.virtualMachineExtensionsClient.Authorizer = armAuthorizer c.virtualMachineImagesClient.Authorizer = armAuthorizer - c.virtualMachineScaleSetsClient.Authorizer = armAuthorizer - c.virtualMachineScaleSetVMsClient.Authorizer = armAuthorizer c.virtualMachinesClient.Authorizer = armAuthorizer c.workspacesClient.Authorizer = armAuthorizer - c.applicationsClient.Authorizer = graphAuthorizer - c.servicePrincipalsClient.Authorizer = graphAuthorizer - c.deploymentsClient.PollingDelay = time.Second * 5 - c.resourcesClient.PollingDelay = time.Second * 5 // Set permissive timeouts to accommodate long-running operations - c.applicationsClient.PollingDuration = DefaultARMOperationTimeout c.authorizationClient.PollingDuration = DefaultARMOperationTimeout c.availabilitySetsClient.PollingDuration = DefaultARMOperationTimeout c.deploymentOperationsClient.PollingDuration = DefaultARMOperationTimeout @@ -416,16 +227,9 @@ func getClient(env azure.Environment, subscriptionID, tenantID string, armAuthor c.groupsClient.PollingDuration = DefaultARMOperationTimeout c.subscriptionsClient.PollingDuration = DefaultARMOperationTimeout c.interfacesClient.PollingDuration = DefaultARMOperationTimeout - c.msiClient.PollingDuration = DefaultARMOperationTimeout c.providersClient.PollingDuration = DefaultARMOperationTimeout - c.resourcesClient.PollingDuration = DefaultARMOperationTimeout - c.resourceSkusClient.PollingDuration = DefaultARMOperationTimeout - c.servicePrincipalsClient.PollingDuration = DefaultARMOperationTimeout c.storageAccountsClient.PollingDuration = DefaultARMOperationTimeout - c.virtualMachineExtensionsClient.PollingDuration = DefaultARMOperationTimeout c.virtualMachineImagesClient.PollingDuration = DefaultARMOperationTimeout - c.virtualMachineScaleSetsClient.PollingDuration = DefaultARMOperationTimeout - c.virtualMachineScaleSetVMsClient.PollingDuration = DefaultARMOperationTimeout c.virtualMachinesClient.PollingDuration = DefaultARMOperationTimeout c.workspacesClient.PollingDuration = DefaultARMOperationTimeout @@ -498,7 +302,6 @@ func parseRsaPrivateKey(path string) (*rsa.PrivateKey, error) { func (az *AzureClient) AddAcceptLanguages(languages []string) { az.acceptLanguages = languages - az.applicationsClient.Client.RequestInspector = az.addAcceptLanguages() az.authorizationClient.Client.RequestInspector = az.addAcceptLanguages() az.availabilitySetsClient.Client.RequestInspector = az.addAcceptLanguages() az.deploymentOperationsClient.Client.RequestInspector = az.addAcceptLanguages() @@ -506,17 +309,10 @@ func (az *AzureClient) AddAcceptLanguages(languages []string) { az.disksClient.Client.RequestInspector = az.addAcceptLanguages() az.groupsClient.Client.RequestInspector = az.addAcceptLanguages() az.interfacesClient.Client.RequestInspector = az.addAcceptLanguages() - az.msiClient.Client.RequestInspector = az.addAcceptLanguages() az.providersClient.Client.RequestInspector = az.addAcceptLanguages() - az.resourcesClient.Client.RequestInspector = az.addAcceptLanguages() - az.resourceSkusClient.Client.RequestInspector = az.addAcceptLanguages() - az.servicePrincipalsClient.Client.RequestInspector = az.addAcceptLanguages() az.storageAccountsClient.Client.RequestInspector = az.addAcceptLanguages() az.subscriptionsClient.Client.RequestInspector = az.addAcceptLanguages() - az.virtualMachineExtensionsClient.Client.RequestInspector = az.addAcceptLanguages() az.virtualMachineImagesClient.Client.RequestInspector = az.addAcceptLanguages() - az.virtualMachineScaleSetsClient.Client.RequestInspector = az.addAcceptLanguages() - az.virtualMachineScaleSetVMsClient.Client.RequestInspector = az.addAcceptLanguages() az.virtualMachinesClient.Client.RequestInspector = az.addAcceptLanguages() az.workspacesClient.Client.RequestInspector = az.addAcceptLanguages() } @@ -567,7 +363,6 @@ func (az *AzureClient) AddAuxiliaryTokens(tokens []string) { az.auxiliaryTokens = tokens requestWithTokens := az.setAuxiliaryTokens() - az.applicationsClient.Client.RequestInspector = requestWithTokens az.authorizationClient.Client.RequestInspector = requestWithTokens az.availabilitySetsClient.Client.RequestInspector = requestWithTokens az.deploymentOperationsClient.Client.RequestInspector = requestWithTokens @@ -575,16 +370,9 @@ func (az *AzureClient) AddAuxiliaryTokens(tokens []string) { az.disksClient.Client.RequestInspector = requestWithTokens az.groupsClient.Client.RequestInspector = requestWithTokens az.interfacesClient.Client.RequestInspector = requestWithTokens - az.msiClient.Client.RequestInspector = requestWithTokens az.providersClient.Client.RequestInspector = requestWithTokens - az.resourcesClient.Client.RequestInspector = requestWithTokens - az.resourceSkusClient.Client.RequestInspector = requestWithTokens - az.servicePrincipalsClient.Client.RequestInspector = requestWithTokens az.storageAccountsClient.Client.RequestInspector = requestWithTokens az.subscriptionsClient.Client.RequestInspector = requestWithTokens - az.virtualMachineExtensionsClient.Client.RequestInspector = requestWithTokens - az.virtualMachineScaleSetsClient.Client.RequestInspector = requestWithTokens - az.virtualMachineScaleSetVMsClient.Client.RequestInspector = requestWithTokens az.virtualMachinesClient.Client.RequestInspector = requestWithTokens az.workspacesClient.Client.RequestInspector = requestWithTokens } diff --git a/pkg/armhelpers/azurestack/azureclient.go b/pkg/armhelpers/azurestack/azureclient.go index 6b3e38054..2c54bef56 100644 --- a/pkg/armhelpers/azurestack/azureclient.go +++ b/pkg/armhelpers/azurestack/azureclient.go @@ -19,9 +19,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2017-03-01/apimanagement" "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-03-30/compute" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-10-01/network" - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" @@ -52,27 +50,20 @@ type AzureClient struct { environment azure.Environment subscriptionID string - authorizationClient authorization.RoleAssignmentsClient - deploymentsClient resources.DeploymentsClient - deploymentOperationsClient resources.DeploymentOperationsClient - msiClient msi.UserAssignedIdentitiesClient - resourcesClient apimanagement.GroupClient - storageAccountsClient storage.AccountsClient - interfacesClient network.InterfacesClient - groupsClient resources.GroupsClient - subscriptionsClient subscriptions.Client - providersClient resources.ProvidersClient - virtualMachinesClient compute.VirtualMachinesClient - virtualMachineScaleSetsClient compute.VirtualMachineScaleSetsClient - virtualMachineScaleSetVMsClient compute.VirtualMachineScaleSetVMsClient - virtualMachineExtensionsClient compute.VirtualMachineExtensionsClient - disksClient compute.DisksClient - availabilitySetsClient compute.AvailabilitySetsClient - workspacesClient operationalinsights.WorkspacesClient - virtualMachineImagesClient compute.VirtualMachineImagesClient - - applicationsClient graphrbac.ApplicationsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient + authorizationClient authorization.RoleAssignmentsClient + deploymentsClient resources.DeploymentsClient + deploymentOperationsClient resources.DeploymentOperationsClient + apimanagement.GroupClient + storageAccountsClient storage.AccountsClient + interfacesClient network.InterfacesClient + groupsClient resources.GroupsClient + subscriptionsClient subscriptions.Client + providersClient resources.ProvidersClient + virtualMachinesClient compute.VirtualMachinesClient + disksClient compute.DisksClient + availabilitySetsClient compute.AvailabilitySetsClient + workspacesClient operationalinsights.WorkspacesClient + virtualMachineImagesClient compute.VirtualMachineImagesClient } // GetKubernetesClient returns a KubernetesClient hooked up to the api server at the apiserverURL. @@ -82,7 +73,7 @@ func (az *AzureClient) GetKubernetesClient(apiserverURL, kubeConfig string, inte // NewAzureClientWithClientSecret returns an AzureClient via client_id and client_secret func NewAzureClientWithClientSecret(env azure.Environment, subscriptionID, clientID, clientSecret string) (*AzureClient, error) { - oauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID) + oauthConfig, err := getOAuthConfig(env, subscriptionID) if err != nil { return nil, err } @@ -99,7 +90,7 @@ func NewAzureClientWithClientSecret(env azure.Environment, subscriptionID, clien log.Error(err) } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } // NewAzureClientWithClientSecretExternalTenant returns an AzureClient via client_id and client_secret from a tenant @@ -113,15 +104,8 @@ func NewAzureClientWithClientSecretExternalTenant(env azure.Environment, subscri if err != nil { return nil, err } - graphSpt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, env.GraphEndpoint) - if err != nil { - return nil, err - } - if err = graphSpt.Refresh(); err != nil { - log.Error(err) - } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } // NewAzureClientWithClientCertificateFile returns an AzureClient via client_id and jwt certificate assertion @@ -156,12 +140,12 @@ func NewAzureClientWithClientCertificateFileExternalTenant(env azure.Environment // NewAzureClientWithClientCertificate returns an AzureClient via client_id and jwt certificate assertion func NewAzureClientWithClientCertificate(env azure.Environment, subscriptionID, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { - oauthConfig, tenantID, err := getOAuthConfig(env, subscriptionID) + oauthConfig, err := getOAuthConfig(env, subscriptionID) if err != nil { return nil, err } - return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, tenantID, certificate, privateKey) + return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, certificate, privateKey) } // NewAzureClientWithClientCertificateExternalTenant returns an AzureClient via client_id and jwt certificate assertion against a 3rd party tenant @@ -171,10 +155,10 @@ func NewAzureClientWithClientCertificateExternalTenant(env azure.Environment, su return nil, err } - return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, tenantID, certificate, privateKey) + return newAzureClientWithCertificate(env, oauthConfig, subscriptionID, clientID, certificate, privateKey) } -func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAuthConfig, subscriptionID, clientID, tenantID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { +func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAuthConfig, subscriptionID, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey) (*AzureClient, error) { if certificate == nil { return nil, errors.New("certificate should not be nil") } @@ -195,92 +179,72 @@ func newAzureClientWithCertificate(env azure.Environment, oauthConfig *adal.OAut log.Error(err) } - return getClient(env, subscriptionID, tenantID, autorest.NewBearerAuthorizer(armSpt), autorest.NewBearerAuthorizer(graphSpt)), nil + return getClient(env, subscriptionID, autorest.NewBearerAuthorizer(armSpt)), nil } -func getOAuthConfig(env azure.Environment, subscriptionID string) (*adal.OAuthConfig, string, error) { +func getOAuthConfig(env azure.Environment, subscriptionID string) (*adal.OAuthConfig, error) { tenantID, err := engine.GetTenantID(env.ResourceManagerEndpoint, subscriptionID) if err != nil { - return nil, "", err + return nil, err } oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, tenantID) if err != nil { - return nil, "", err + return nil, err } - return oauthConfig, tenantID, nil + return oauthConfig, nil } -func getClient(env azure.Environment, subscriptionID, tenantID string, armAuthorizer autorest.Authorizer, graphAuthorizer autorest.Authorizer) *AzureClient { +func getClient(env azure.Environment, subscriptionID string, armAuthorizer autorest.Authorizer) *AzureClient { c := &AzureClient{ environment: env, subscriptionID: subscriptionID, - authorizationClient: authorization.NewRoleAssignmentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - deploymentsClient: resources.NewDeploymentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - deploymentOperationsClient: resources.NewDeploymentOperationsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - msiClient: msi.NewUserAssignedIdentitiesClient(subscriptionID), - resourcesClient: apimanagement.NewGroupClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - storageAccountsClient: storage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - interfacesClient: network.NewInterfacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - groupsClient: resources.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - subscriptionsClient: subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint), - providersClient: resources.NewProvidersClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachinesClient: compute.NewVirtualMachinesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineScaleSetsClient: compute.NewVirtualMachineScaleSetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineScaleSetVMsClient: compute.NewVirtualMachineScaleSetVMsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineExtensionsClient: compute.NewVirtualMachineExtensionsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - disksClient: compute.NewDisksClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - availabilitySetsClient: compute.NewAvailabilitySetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - workspacesClient: operationalinsights.NewWorkspacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - virtualMachineImagesClient: compute.NewVirtualMachineImagesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), - - applicationsClient: graphrbac.NewApplicationsClientWithBaseURI(env.GraphEndpoint, tenantID), - servicePrincipalsClient: graphrbac.NewServicePrincipalsClientWithBaseURI(env.GraphEndpoint, tenantID), + authorizationClient: authorization.NewRoleAssignmentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + deploymentsClient: resources.NewDeploymentsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + deploymentOperationsClient: resources.NewDeploymentOperationsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + storageAccountsClient: storage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + interfacesClient: network.NewInterfacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + groupsClient: resources.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + subscriptionsClient: subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint), + providersClient: resources.NewProvidersClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + virtualMachinesClient: compute.NewVirtualMachinesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + disksClient: compute.NewDisksClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + availabilitySetsClient: compute.NewAvailabilitySetsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + workspacesClient: operationalinsights.NewWorkspacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), + virtualMachineImagesClient: compute.NewVirtualMachineImagesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID), } c.authorizationClient.Authorizer = armAuthorizer c.deploymentsClient.Authorizer = armAuthorizer c.deploymentOperationsClient.Authorizer = armAuthorizer - c.msiClient.Authorizer = armAuthorizer - c.resourcesClient.Authorizer = armAuthorizer c.storageAccountsClient.Authorizer = armAuthorizer c.interfacesClient.Authorizer = armAuthorizer c.groupsClient.Authorizer = armAuthorizer c.subscriptionsClient.Authorizer = armAuthorizer c.providersClient.Authorizer = armAuthorizer c.virtualMachinesClient.Authorizer = armAuthorizer - c.virtualMachineScaleSetsClient.Authorizer = armAuthorizer - c.virtualMachineScaleSetVMsClient.Authorizer = armAuthorizer c.disksClient.Authorizer = armAuthorizer c.availabilitySetsClient.Authorizer = armAuthorizer c.workspacesClient.Authorizer = armAuthorizer c.virtualMachineImagesClient.Authorizer = armAuthorizer c.deploymentsClient.PollingDelay = time.Second * 5 - c.resourcesClient.PollingDelay = time.Second * 5 // Set permissive timeouts to accommodate long-running operations c.deploymentsClient.PollingDuration = DefaultARMOperationTimeout c.deploymentOperationsClient.PollingDuration = DefaultARMOperationTimeout - c.applicationsClient.PollingDuration = DefaultARMOperationTimeout c.authorizationClient.PollingDuration = DefaultARMOperationTimeout c.disksClient.PollingDuration = DefaultARMOperationTimeout c.groupsClient.PollingDuration = DefaultARMOperationTimeout c.subscriptionsClient.PollingDuration = DefaultARMOperationTimeout c.interfacesClient.PollingDuration = DefaultARMOperationTimeout c.providersClient.PollingDuration = DefaultARMOperationTimeout - c.resourcesClient.PollingDuration = DefaultARMOperationTimeout c.storageAccountsClient.PollingDuration = DefaultARMOperationTimeout - c.virtualMachineScaleSetsClient.PollingDuration = DefaultARMOperationTimeout - c.virtualMachineScaleSetVMsClient.PollingDuration = DefaultARMOperationTimeout c.virtualMachinesClient.PollingDuration = DefaultARMOperationTimeout c.availabilitySetsClient.PollingDuration = DefaultARMOperationTimeout - c.applicationsClient.Authorizer = graphAuthorizer - c.servicePrincipalsClient.Authorizer = graphAuthorizer - return c } @@ -371,18 +335,13 @@ func (az *AzureClient) AddAcceptLanguages(languages []string) { az.deploymentOperationsClient.Client.RequestInspector = az.addAcceptLanguages() az.deploymentsClient.Client.RequestInspector = az.addAcceptLanguages() az.deploymentOperationsClient.Client.RequestInspector = az.addAcceptLanguages() - az.resourcesClient.Client.RequestInspector = az.addAcceptLanguages() az.storageAccountsClient.Client.RequestInspector = az.addAcceptLanguages() az.interfacesClient.Client.RequestInspector = az.addAcceptLanguages() az.groupsClient.Client.RequestInspector = az.addAcceptLanguages() az.subscriptionsClient.Client.RequestInspector = az.addAcceptLanguages() az.providersClient.Client.RequestInspector = az.addAcceptLanguages() az.virtualMachinesClient.Client.RequestInspector = az.addAcceptLanguages() - az.virtualMachineScaleSetsClient.Client.RequestInspector = az.addAcceptLanguages() az.disksClient.Client.RequestInspector = az.addAcceptLanguages() - - az.applicationsClient.Client.RequestInspector = az.addAcceptLanguages() - az.servicePrincipalsClient.Client.RequestInspector = az.addAcceptLanguages() } func (az *AzureClient) addAcceptLanguages() autorest.PrepareDecorator { @@ -435,16 +394,11 @@ func (az *AzureClient) AddAuxiliaryTokens(tokens []string) { az.deploymentOperationsClient.Client.RequestInspector = requestWithTokens az.deploymentsClient.Client.RequestInspector = requestWithTokens az.deploymentOperationsClient.Client.RequestInspector = requestWithTokens - az.resourcesClient.Client.RequestInspector = requestWithTokens az.storageAccountsClient.Client.RequestInspector = requestWithTokens az.interfacesClient.Client.RequestInspector = requestWithTokens az.groupsClient.Client.RequestInspector = requestWithTokens az.subscriptionsClient.Client.RequestInspector = requestWithTokens az.providersClient.Client.RequestInspector = requestWithTokens az.virtualMachinesClient.Client.RequestInspector = requestWithTokens - az.virtualMachineScaleSetsClient.Client.RequestInspector = requestWithTokens az.disksClient.Client.RequestInspector = requestWithTokens - - az.applicationsClient.Client.RequestInspector = requestWithTokens - az.servicePrincipalsClient.Client.RequestInspector = requestWithTokens } diff --git a/pkg/armhelpers/azurestack/compute.go b/pkg/armhelpers/azurestack/compute.go index 3284e5901..6731874c1 100644 --- a/pkg/armhelpers/azurestack/compute.go +++ b/pkg/armhelpers/azurestack/compute.go @@ -69,19 +69,6 @@ func (az *AzureClient) DeleteVirtualMachine(ctx context.Context, resourceGroup, return err } -// DeleteVirtualMachineScaleSet deletes an entire VM Scale Set. -func (az *AzureClient) DeleteVirtualMachineScaleSet(ctx context.Context, resourceGroup, vmssName string) error { - future, err := az.virtualMachineScaleSetsClient.Delete(ctx, resourceGroup, vmssName) - if err != nil { - return err - } - if err = future.WaitForCompletionRef(ctx, az.virtualMachineScaleSetsClient.Client); err != nil { - return err - } - _, err = future.Result(az.virtualMachineScaleSetsClient) - return err -} - // GetAvailabilitySet retrieves the specified VM availability set. func (az *AzureClient) GetAvailabilitySet(ctx context.Context, resourceGroup, availabilitySetName string) (azcompute.AvailabilitySet, error) { azVMAS := azcompute.AvailabilitySet{} diff --git a/pkg/armhelpers/azurestack/graph.go b/pkg/armhelpers/azurestack/graph.go deleted file mode 100644 index 5bf08462f..000000000 --- a/pkg/armhelpers/azurestack/graph.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -package azurestack - -import ( - "context" - - "github.com/Azure/aks-engine-azurestack/pkg/armhelpers" - "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/go-autorest/autorest" - "github.com/pkg/errors" -) - -const ( - // AADContributorRoleID is the role id that exists in every subscription for 'Contributor' - AADContributorRoleID = "b24988ac-6180-42a0-ab88-20f7382dd24c" - // AADRoleReferenceTemplate is a template for a roleDefinitionId - AADRoleReferenceTemplate = "/subscriptions/%s/providers/Microsoft.Authorization/roleDefinitions/%s" - // AADRoleResourceGroupScopeTemplate is a template for a roleDefinition scope - AADRoleResourceGroupScopeTemplate = "/subscriptions/%s/resourceGroups/%s" -) - -// CreateGraphApplication creates an application via the graphrbac client -func (az *AzureClient) CreateGraphApplication(ctx context.Context, applicationCreateParameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) { - errorMessage := "error azure stack does not support creating application" - return graphrbac.Application{}, errors.New(errorMessage) -} - -// DeleteGraphApplication deletes an application via the graphrbac client -func (az *AzureClient) DeleteGraphApplication(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) { - errorMessage := "error azure stack does not support deleting application" - return autorest.Response{}, errors.New(errorMessage) -} - -// CreateGraphPrincipal creates a service principal via the graphrbac client -func (az *AzureClient) CreateGraphPrincipal(ctx context.Context, servicePrincipalCreateParameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) { - errorMessage := "error azure stack does not support creating service principal" - return graphrbac.ServicePrincipal{}, errors.New(errorMessage) -} - -// CreateRoleAssignment creates a role assignment via the authorization client -func (az *AzureClient) CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) { - errorMessage := "error azure stack does not support creating role assignement" - return authorization.RoleAssignment{}, errors.New(errorMessage) -} - -// DeleteRoleAssignmentByID deletes a roleAssignment via its unique identifier -func (az *AzureClient) DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentID string) (authorization.RoleAssignment, error) { - errorMessage := "error azure stack does not support deleting role assignement" - return authorization.RoleAssignment{}, errors.New(errorMessage) -} - -// ListRoleAssignmentsForPrincipal (e.g. a VM) via the scope and the unique identifier of the principal -func (az *AzureClient) ListRoleAssignmentsForPrincipal(ctx context.Context, scope string, principalID string) (armhelpers.RoleAssignmentListResultPage, error) { - errorMessage := "error azure stack does not support listing role assignement" - return nil, errors.New(errorMessage) -} - -// CreateApp is a simpler method for creating an application -func (az *AzureClient) CreateApp(ctx context.Context, appName, appURL string, replyURLs *[]string, requiredResourceAccess *[]graphrbac.RequiredResourceAccess) (applicationResp graphrbac.Application, servicePrincipalObjectID, servicePrincipalClientSecret string, err error) { - errorMessage := "error azure stack does not support creating application" - return graphrbac.Application{}, "", "", errors.New(errorMessage) -} - -// DeleteApp is a simpler method for deleting an application and the associated spn -func (az *AzureClient) DeleteApp(ctx context.Context, applicationName, applicationObjectID string) (autorest.Response, error) { - errorMessage := "error azure stack does not support deleting application" - return autorest.Response{}, errors.New(errorMessage) -} - -// CreateRoleAssignmentSimple is a wrapper around RoleAssignmentsClient.Create -func (az *AzureClient) CreateRoleAssignmentSimple(ctx context.Context, resourceGroup, servicePrincipalObjectID string) error { - errorMessage := "error azure stack does not support creating role assignment" - return errors.New(errorMessage) -} diff --git a/pkg/armhelpers/azurestack/msi.go b/pkg/armhelpers/azurestack/msi.go deleted file mode 100644 index 72aee30d4..000000000 --- a/pkg/armhelpers/azurestack/msi.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -package azurestack - -import ( - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" - "github.com/pkg/errors" -) - -// CreateUserAssignedID - Creates a user assigned msi. -func (az *AzureClient) CreateUserAssignedID(location string, resourceGroup string, userAssignedID string) (id *msi.Identity, err error) { - errorMessage := "error azure stack does not support creating user assigned msi" - return &msi.Identity{}, errors.New(errorMessage) -} diff --git a/pkg/armhelpers/graph.go b/pkg/armhelpers/graph.go deleted file mode 100644 index ed8ed7457..000000000 --- a/pkg/armhelpers/graph.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -package armhelpers - -import ( - "context" - "fmt" - "regexp" - "time" - - "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/google/uuid" - log "github.com/sirupsen/logrus" -) - -const ( - // AADContributorRoleID is the role id that exists in every subscription for 'Contributor' - AADContributorRoleID = "b24988ac-6180-42a0-ab88-20f7382dd24c" - // AADRoleReferenceTemplate is a template for a roleDefinitionId - AADRoleReferenceTemplate = "/subscriptions/%s/providers/Microsoft.Authorization/roleDefinitions/%s" - // AADRoleResourceGroupScopeTemplate is a template for a roleDefinition scope - AADRoleResourceGroupScopeTemplate = "/subscriptions/%s/resourceGroups/%s" -) - -// CreateGraphApplication creates an application via the graphrbac client -func (az *AzureClient) CreateGraphApplication(ctx context.Context, applicationCreateParameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) { - return az.applicationsClient.Create(ctx, applicationCreateParameters) -} - -// DeleteGraphApplication deletes an application via the graphrbac client -func (az *AzureClient) DeleteGraphApplication(ctx context.Context, applicationObjectID string) (result autorest.Response, err error) { - return az.applicationsClient.Delete(ctx, applicationObjectID) -} - -// CreateGraphPrincipal creates a service principal via the graphrbac client -func (az *AzureClient) CreateGraphPrincipal(ctx context.Context, servicePrincipalCreateParameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) { - return az.servicePrincipalsClient.Create(ctx, servicePrincipalCreateParameters) -} - -// CreateRoleAssignment creates a role assignment via the authorization client -func (az *AzureClient) CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) { - return az.authorizationClient.Create(ctx, scope, roleAssignmentName, parameters) -} - -// DeleteRoleAssignmentByID deletes a roleAssignment via its unique identifier -func (az *AzureClient) DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentID string) (authorization.RoleAssignment, error) { - return az.authorizationClient.DeleteByID(ctx, roleAssignmentID) -} - -// ListRoleAssignmentsForPrincipal (e.g. a VM) via the scope and the unique identifier of the principal -func (az *AzureClient) ListRoleAssignmentsForPrincipal(ctx context.Context, scope string, principalID string) (RoleAssignmentListResultPage, error) { - page, err := az.authorizationClient.ListForScope(ctx, scope, fmt.Sprintf("principalId eq '%s'", principalID)) - return &page, err -} - -// CreateApp is a simpler method for creating an application -func (az *AzureClient) CreateApp(ctx context.Context, appName, appURL string, replyURLs *[]string, requiredResourceAccess *[]graphrbac.RequiredResourceAccess) (applicationResp graphrbac.Application, servicePrincipalObjectID, servicePrincipalClientSecret string, err error) { - notBefore := time.Now() - notAfter := time.Now().Add(10000 * 24 * time.Hour) - - startDate := date.Time{Time: notBefore} - endDate := date.Time{Time: notAfter} - - servicePrincipalClientSecret = uuid.Must(uuid.NewRandom()).String() - - log.Debugf("ad: creating application with name=%q identifierURL=%q", appName, appURL) - applicationReq := graphrbac.ApplicationCreateParameters{ - AvailableToOtherTenants: to.BoolPtr(false), - DisplayName: to.StringPtr(appName), - Homepage: to.StringPtr(appURL), - IdentifierUris: to.StringSlicePtr([]string{appURL}), - ReplyUrls: replyURLs, - PasswordCredentials: &[]graphrbac.PasswordCredential{ - { - KeyID: to.StringPtr(uuid.Must(uuid.NewRandom()).String()), - StartDate: &startDate, - EndDate: &endDate, - Value: to.StringPtr(servicePrincipalClientSecret), - }, - }, - RequiredResourceAccess: requiredResourceAccess, - } - applicationResp, err = az.CreateGraphApplication(ctx, applicationReq) - if err != nil { - return applicationResp, "", "", err - } - applicationID := to.String(applicationResp.AppID) - - log.Debugf("ad: creating servicePrincipal for applicationID: %q", applicationID) - - servicePrincipalReq := graphrbac.ServicePrincipalCreateParameters{ - AppID: applicationResp.AppID, - AccountEnabled: to.BoolPtr(true), - } - servicePrincipalResp, err := az.servicePrincipalsClient.Create(ctx, servicePrincipalReq) - if err != nil { - return applicationResp, "", "", err - } - - servicePrincipalObjectID = to.String(servicePrincipalResp.ObjectID) - - return applicationResp, servicePrincipalObjectID, servicePrincipalClientSecret, nil -} - -// DeleteApp is a simpler method for deleting an application and the associated spn -func (az *AzureClient) DeleteApp(ctx context.Context, applicationName, applicationObjectID string) (autorest.Response, error) { - log.Debugf("ad: deleting application with name=%q", applicationName) - return az.DeleteGraphApplication(ctx, applicationObjectID) -} - -// CreateRoleAssignmentSimple is a wrapper around RoleAssignmentsClient.Create -func (az *AzureClient) CreateRoleAssignmentSimple(ctx context.Context, resourceGroup, servicePrincipalObjectID string) error { - roleAssignmentName := uuid.Must(uuid.NewRandom()).String() - - roleDefinitionID := fmt.Sprintf(AADRoleReferenceTemplate, az.subscriptionID, AADContributorRoleID) - scope := fmt.Sprintf(AADRoleResourceGroupScopeTemplate, az.subscriptionID, resourceGroup) - - roleAssignmentParameters := authorization.RoleAssignmentCreateParameters{ - Properties: &authorization.RoleAssignmentProperties{ - RoleDefinitionID: to.StringPtr(roleDefinitionID), - PrincipalID: to.StringPtr(servicePrincipalObjectID), - }, - } - - re := regexp.MustCompile(`(?i)status=(\d+)`) - for { - _, err := az.CreateRoleAssignment( - ctx, - scope, - roleAssignmentName, - roleAssignmentParameters, - ) - if err != nil { - match := re.FindStringSubmatch(err.Error()) - if match != nil && (match[1] == "403") { - //insufficient permissions. stop now - log.Debugf("Failed to create role assignment (will abort now): %q", err) - return err - } - // TODO: Should we handle 409 errors as well here ? - log.Debugf("Failed to create role assignment (will retry): %q", err) - time.Sleep(3 * time.Second) - continue - } - break - } - - return nil -} diff --git a/pkg/armhelpers/interfaces.go b/pkg/armhelpers/interfaces.go index 2dfe1a2cf..83d413334 100644 --- a/pkg/armhelpers/interfaces.go +++ b/pkg/armhelpers/interfaces.go @@ -10,12 +10,9 @@ import ( "github.com/Azure/aks-engine-azurestack/pkg/kubernetes" "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" azStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" ) // ResourceSkusResultPage @@ -136,27 +133,6 @@ type AKSEngineClient interface { // DeleteNetworkInterface deletes the specified network interface. DeleteNetworkInterface(ctx context.Context, resourceGroup, nicName string) error - // GRAPH - - // CreateGraphAppliction creates an application via the graphrbac client - CreateGraphApplication(ctx context.Context, applicationCreateParameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) - - // CreateGraphPrincipal creates a service principal via the graphrbac client - CreateGraphPrincipal(ctx context.Context, servicePrincipalCreateParameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) - CreateApp(ctx context.Context, applicationName, applicationURL string, replyURLs *[]string, requiredResourceAccess *[]graphrbac.RequiredResourceAccess) (result graphrbac.Application, servicePrincipalObjectID, secret string, err error) - DeleteApp(ctx context.Context, applicationName, applicationObjectID string) (autorest.Response, error) - - // User Assigned MSI - - // CreateUserAssignedID - Creates a user assigned msi. - CreateUserAssignedID(location string, resourceGroup string, userAssignedID string) (*msi.Identity, error) - - // RBAC - CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) - CreateRoleAssignmentSimple(ctx context.Context, applicationID, roleID string) error - DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentNameID string) (authorization.RoleAssignment, error) - ListRoleAssignmentsForPrincipal(ctx context.Context, scope string, principalID string) (RoleAssignmentListResultPage, error) - // MANAGED DISKS DeleteManagedDisk(ctx context.Context, resourceGroupName string, diskName string) error ListManagedDisksByResourceGroup(ctx context.Context, resourceGroupName string) (result DiskListPage, err error) diff --git a/pkg/armhelpers/mockclients.go b/pkg/armhelpers/mockclients.go index 2659237b7..850d7fead 100644 --- a/pkg/armhelpers/mockclients.go +++ b/pkg/armhelpers/mockclients.go @@ -18,8 +18,6 @@ import ( "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" azStorage "github.com/Azure/azure-sdk-for-go/storage" "github.com/Azure/go-autorest/autorest" @@ -676,47 +674,6 @@ var validNicResourceName = "/subscriptions/DEC923E3-1EF1-4745-9516-37906D56DEC4/ // Graph Mocks -// CreateGraphApplication creates an application via the graphrbac client -func (mc *MockAKSEngineClient) CreateGraphApplication(ctx context.Context, applicationCreateParameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) { - return graphrbac.Application{}, nil -} - -// CreateGraphPrincipal creates a service principal via the graphrbac client -func (mc *MockAKSEngineClient) CreateGraphPrincipal(ctx context.Context, servicePrincipalCreateParameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) { - return graphrbac.ServicePrincipal{}, nil -} - -// CreateApp is a simpler method for creating an application -func (mc *MockAKSEngineClient) CreateApp(ctx context.Context, applicationName, applicationURL string, replyURLs *[]string, requiredResourceAccess *[]graphrbac.RequiredResourceAccess) (result graphrbac.Application, servicePrincipalObjectID, secret string, err error) { - return graphrbac.Application{ - AppID: to.StringPtr("app-id"), - }, "client-id", "client-secret", nil -} - -// DeleteApp is a simpler method for deleting an application -func (mc *MockAKSEngineClient) DeleteApp(ctx context.Context, appName, applicationObjectID string) (response autorest.Response, err error) { - return response, nil -} - -// User Assigned MSI - -// CreateUserAssignedID - Creates a user assigned msi. -func (mc *MockAKSEngineClient) CreateUserAssignedID(location string, resourceGroup string, userAssignedID string) (*msi.Identity, error) { - return &msi.Identity{}, nil -} - -// RBAC Mocks - -// CreateRoleAssignment creates a role assignment via the authorization client -func (mc *MockAKSEngineClient) CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) { - return authorization.RoleAssignment{}, nil -} - -// CreateRoleAssignmentSimple is a wrapper around RoleAssignmentsClient.Create -func (mc *MockAKSEngineClient) CreateRoleAssignmentSimple(ctx context.Context, applicationID, roleID string) error { - return nil -} - // DeleteManagedDisk is a wrapper around disksClient.Delete func (mc *MockAKSEngineClient) DeleteManagedDisk(ctx context.Context, resourceGroupName string, diskName string) error { return nil @@ -816,33 +773,6 @@ func (mc *MockAKSEngineClient) ListDeploymentOperationsNextResults(lastResults r return resources.DeploymentOperationsListResult{}, nil } -// DeleteRoleAssignmentByID deletes a roleAssignment via its unique identifier -func (mc *MockAKSEngineClient) DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentID string) (authorization.RoleAssignment, error) { - if mc.FailDeleteRoleAssignment { - return authorization.RoleAssignment{}, errors.New("DeleteRoleAssignmentByID failed") - } - - return authorization.RoleAssignment{}, nil -} - -// ListRoleAssignmentsForPrincipal (e.g. a VM) via the scope and the unique identifier of the principal -func (mc *MockAKSEngineClient) ListRoleAssignmentsForPrincipal(ctx context.Context, scope string, principalID string) (RoleAssignmentListResultPage, error) { - roleAssignments := []authorization.RoleAssignment{} - - if mc.ShouldSupportVMIdentity { - var assignmentID = "role-assignment-id" - var assignment = authorization.RoleAssignment{ - ID: &assignmentID} - roleAssignments = append(roleAssignments, assignment) - } - - return &MockRoleAssignmentListResultPage{ - Ralr: authorization.RoleAssignmentListResult{ - Value: &roleAssignments, - }, - }, nil -} - // EnsureDefaultLogAnalyticsWorkspace mock func (mc *MockAKSEngineClient) EnsureDefaultLogAnalyticsWorkspace(ctx context.Context, resourceGroup, location string) (workspaceResourceID string, err error) { if mc.FailEnsureDefaultLogAnalyticsWorkspace { diff --git a/pkg/armhelpers/msi.go b/pkg/armhelpers/msi.go deleted file mode 100644 index 7cab766f3..000000000 --- a/pkg/armhelpers/msi.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -package armhelpers - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" - "github.com/Azure/go-autorest/autorest/to" - log "github.com/sirupsen/logrus" -) - -// CreateUserAssignedID - Creates a user assigned msi. -func (az *AzureClient) CreateUserAssignedID(location string, resourceGroup string, userAssignedID string) (id *msi.Identity, err error) { - idCreated, err := az.msiClient.CreateOrUpdate(context.Background(), resourceGroup, userAssignedID, msi.Identity{ - Location: to.StringPtr(location), - }) - if err != nil { - log.Error(err) - return nil, err - } - log.Infof("Created %s in rg %s", userAssignedID, resourceGroup) - return &idCreated, nil -} diff --git a/pkg/operations/deletevm.go b/pkg/operations/deletevm.go index 3ebe371a1..caf9d5005 100644 --- a/pkg/operations/deletevm.go +++ b/pkg/operations/deletevm.go @@ -5,7 +5,6 @@ package operations import ( "context" - "fmt" "github.com/Azure/aks-engine-azurestack/pkg/armhelpers" "github.com/Azure/aks-engine-azurestack/pkg/armhelpers/utils" @@ -93,28 +92,5 @@ func CleanDeleteVirtualMachine(az armhelpers.AKSEngineClient, logger *log.Entry, } } - if vm.Identity != nil && vm.Identity.PrincipalID != nil { - // Role assignments are not deleted if the VM is destroyed, so we must cleanup ourselves! - // The role assignments should only be relevant if managed identities are used, - // but always cleaning them up is easier than adding rule based logic here and there. - scope := fmt.Sprintf(AADRoleResourceGroupScopeTemplate, subscriptionID, resourceGroup) - logger.Debugf("fetching role assignments: %s with principal %s", scope, *vm.Identity.PrincipalID) - for vmRoleAssignmentsPage, err := az.ListRoleAssignmentsForPrincipal(ctx, scope, *vm.Identity.PrincipalID); vmRoleAssignmentsPage.NotDone(); err = vmRoleAssignmentsPage.Next() { - if err != nil { - logger.Errorf("failed to list role assignments: %s/%s: %s", scope, *vm.Identity.PrincipalID, err) - return err - } - - for _, roleAssignment := range vmRoleAssignmentsPage.Values() { - logger.Infof("deleting role assignment %s ...", *roleAssignment.ID) - _, deleteRoleAssignmentErr := az.DeleteRoleAssignmentByID(ctx, *roleAssignment.ID) - if deleteRoleAssignmentErr != nil { - logger.Errorf("failed to delete role assignment: %s: %s", *roleAssignment.ID, deleteRoleAssignmentErr.Error()) - return deleteRoleAssignmentErr - } - } - } - } - return nil } diff --git a/pkg/operations/kubernetesupgrade/upgradecluster_test.go b/pkg/operations/kubernetesupgrade/upgradecluster_test.go index 90f9212c7..274c77ca5 100644 --- a/pkg/operations/kubernetesupgrade/upgradecluster_test.go +++ b/pkg/operations/kubernetesupgrade/upgradecluster_test.go @@ -235,32 +235,6 @@ var _ = Describe("Upgrade Kubernetes cluster tests", Serial, func() { Expect(err.Error()).To(Equal("DeleteNetworkInterface failed")) }) - It("Should return error message when failing to delete role assignment during upgrade operation", func() { - cs := api.CreateMockContainerService("testcluster", upgradeVersion, 3, 2, false) - cs.Properties.OrchestratorProfile.KubernetesConfig = &api.KubernetesConfig{} - cs.Properties.OrchestratorProfile.KubernetesConfig.UseManagedIdentity = to.BoolPtr(true) - uc := UpgradeCluster{ - Translator: &i18n.Translator{}, - Logger: log.NewEntry(log.New()), - } - - mockClient := armhelpers.MockAKSEngineClient{} - mockClient.FailDeleteRoleAssignment = true - mockClient.ShouldSupportVMIdentity = true - uc.Client = &mockClient - - uc.ClusterTopology = ClusterTopology{} - uc.SubscriptionID = "DEC923E3-1EF1-4745-9516-37906D56DEC4" - uc.ResourceGroup = "TestRg" - uc.DataModel = cs - uc.NameSuffix = "12345678" - uc.AgentPoolsToUpgrade = map[string]bool{"agentpool1": true} - - err := uc.UpgradeCluster(&mockClient, "kubeConfig", TestAKSEngineVersion) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(Equal("DeleteRoleAssignmentByID failed")) - }) - Context("When upgrading a cluster with AvailibilitySets VMs", func() { var ( cs *api.ContainerService diff --git a/test/e2e/config/config.go b/test/e2e/config/config.go index c3bda36c6..9d1e89efc 100644 --- a/test/e2e/config/config.go +++ b/test/e2e/config/config.go @@ -56,7 +56,6 @@ type Config struct { GinkgoParallel bool `envconfig:"GINKGO_PARALLEL" default:"false"` GinkgoJUnitReportPath string `envconfig:"GINKGO_JUNIT_PATH" default:""` DebugAfterSuite bool `envconfig:"DEBUG_AFTERSUITE" default:"false"` - RunVMSSHygiene bool `envconfig:"RUN_VMSS_HYGIENE" default:"false"` BlockSSHPort bool `envconfig:"BLOCK_SSH" default:"false"` BlockOutboundInternet bool `envconfig:"BLOCK_OUTBOUND_INTERNET" default:"false"` RebootControlPlaneNodes bool `envconfig:"REBOOT_CONTROL_PLANE_NODES" default:"false"` diff --git a/test/e2e/go.mod b/test/e2e/go.mod index 952d77fea..0d4af5dbe 100644 --- a/test/e2e/go.mod +++ b/test/e2e/go.mod @@ -18,7 +18,6 @@ require ( require ( github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/adal v0.9.10 // indirect - github.com/Azure/go-autorest/autorest/azure/cli v0.3.0 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.2.0 // indirect github.com/Azure/go-autorest/logger v0.2.0 // indirect @@ -26,7 +25,6 @@ require ( github.com/BurntSushi/toml v0.3.1 // indirect github.com/blang/semver v3.5.1+incompatible // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dimchansky/utfbom v1.1.0 // indirect github.com/emicklei/go-restful/v3 v3.9.0 // indirect github.com/fatih/structs v1.1.0 // indirect github.com/form3tech-oss/jwt-go v3.2.2+incompatible // indirect @@ -51,7 +49,6 @@ require ( github.com/leonelquinteros/gotext v1.4.0 // indirect github.com/magefile/mage v1.10.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect diff --git a/test/e2e/go.sum b/test/e2e/go.sum index e6f79cb5d..45c1e3a7b 100644 --- a/test/e2e/go.sum +++ b/test/e2e/go.sum @@ -7,19 +7,14 @@ github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+B github.com/Azure/go-autorest/autorest v0.11.12 h1:gI8ytXbxMfI+IVbI9mP2JGCTXIuhHLgRlvQ9X4PsnHE= github.com/Azure/go-autorest/autorest v0.11.12/go.mod h1:eipySxLmqSyC5s5k1CLupqet0PSENBEDP93LQ9a8QYw= github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= -github.com/Azure/go-autorest/autorest/adal v0.6.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= github.com/Azure/go-autorest/autorest/adal v0.9.10 h1:r6fZHMaHD8B6LDCn0o5vyBFHIHrM6Ywwx7mb49lPItI= github.com/Azure/go-autorest/autorest/adal v0.9.10/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= -github.com/Azure/go-autorest/autorest/azure/cli v0.3.0 h1:5PAqnv+CSTwW9mlZWZAizmzrazFWEgZykEZXpr2hDtY= -github.com/Azure/go-autorest/autorest/azure/cli v0.3.0/go.mod h1:rNYMNAefZMRowqCV0cVhr/YDW5dD7afFq9nXAXL4ykE= 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/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= 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/mocks v0.4.1 h1:K0laFcLE6VLTOwNgSxaGbUcLPuGXlNkbVvq4cW4nIHk= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/to v0.3.0 h1:zebkZaadz7+wIQYgC7GXaz3Wb28yKYfVkkBKwc38VF8= @@ -47,8 +42,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/dnaeon/go-vcr v1.0.1 h1:r8L/HqC0Hje5AXMu1ooW8oyQyOFv4GxqpL0nRP7SLLY= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= @@ -137,8 +130,6 @@ github.com/magefile/mage v1.10.0 h1:3HiXzCUY12kh9bIuyXShaVe529fJfyqoVM42o/uom2g= github.com/magefile/mage v1.10.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= diff --git a/test/e2e/kubernetes/kubernetes_test.go b/test/e2e/kubernetes/kubernetes_test.go index eac544804..09861cd39 100644 --- a/test/e2e/kubernetes/kubernetes_test.go +++ b/test/e2e/kubernetes/kubernetes_test.go @@ -49,7 +49,6 @@ import ( "github.com/Azure/aks-engine-azurestack/test/e2e/kubernetes/storageclass" "github.com/Azure/aks-engine-azurestack/test/e2e/kubernetes/util" "github.com/Azure/aks-engine-azurestack/test/e2e/remote" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -191,25 +190,9 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) } } - - if cfg.RunVMSSHygiene { - vmssHealthCommand, err = RunVMSSHealthCheck(cfg) - Expect(err).NotTo(HaveOccurred()) - vmssHealthCommandStdOut = fmt.Sprintf("./vmss-health-check-%s.out", cfg.ResourceGroup) - } }) var _ = AfterSuite(func() { - if cfg.RunVMSSHygiene { - if err := vmssHealthCommand.Process.Kill(); err != nil { - log.Fatal(fmt.Sprintf("failed to kill process ID %d: ", vmssHealthCommand.Process.Pid), err) - } - stdout, err := os.ReadFile(vmssHealthCommandStdOut) - if err != nil { - fmt.Printf("Unable to read file %s", vmssHealthCommandStdOut) - } - fmt.Println(string(stdout)) - } if cfg.DebugAfterSuite { cmd := exec.Command("k", "get", "deployments,pods,svc,daemonsets,configmaps,endpoints,jobs,clusterroles,clusterrolebindings,roles,rolebindings,storageclasses", "--all-namespaces", "-o", "wide") out, err := cmd.CombinedOutput() @@ -2514,115 +2497,6 @@ var _ = Describe("Azure Container Cluster using the Kubernetes Orchestrator", fu Skip("No windows agent was provisioned for this Cluster Definition") } }) - // This test is not parallelizable due to tainting nodes with NoSchedule - It("should expect containers to be recreated after node restart", func() { - if eng.HasWindowsAgents() { - for _, profile := range eng.ExpandedDefinition.Properties.AgentPoolProfiles { - if profile.IsWindows() { - if profile.AvailabilityProfile == api.AvailabilitySet { - Skip("AvailabilitySet is configured for this Cluster Definition") - } - } - } - - if eng.HasNetworkPlugin(api.NetworkPluginKubenet) { - Skip("This tests is not enabled for kubenet CNI on windows") - } - - windowsImages, err := eng.GetWindowsTestImages() - Expect(err).NotTo(HaveOccurred()) - r := rand.New(rand.NewSource(time.Now().UnixNano())) - deploymentPrefix := fmt.Sprintf("iis-%s", cfg.Name) - deploymentName := fmt.Sprintf("%s-%v", deploymentPrefix, r.Intn(99999)) - By("Creating a deployment with 1 pod running IIS") - iisDeploy, err := deployment.CreateWindowsDeployWithHostportDeleteIfExist(deploymentPrefix, windowsImages.IIS, deploymentName, "default", 80, -1) - Expect(err).NotTo(HaveOccurred()) - - By("Waiting on pod to be Ready") - running, err := pod.WaitOnSuccesses(deploymentName, "default", 4, true, sleepBetweenRetriesWhenWaitingForPodReady, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - Expect(running).To(Equal(true)) - - By("Exposing a LoadBalancer for the pod") - err = iisDeploy.ExposeDeleteIfExist(deploymentPrefix, "default", "LoadBalancer", 80, 80) - Expect(err).NotTo(HaveOccurred()) - iisService, err := service.Get(deploymentName, "default") - Expect(err).NotTo(HaveOccurred()) - err = iisService.WaitForIngress(cfg.LBTimeout, 5*time.Second) - Expect(err).NotTo(HaveOccurred()) - - By("Verifying that the service is reachable and returns the default IIS start page") - err = iisService.ValidateWithRetry("(IIS Windows Server)", sleepBetweenRetriesWhenWaitingForPodReady, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - - pods, err := iisDeploy.Pods() - Expect(err).NotTo(HaveOccurred()) - nodeName := pods[0].Spec.NodeName - ctx, cancel := context.WithTimeout(context.Background(), 6000*time.Second) - defer cancel() - - By("Adding taint to all other Windows nodes") - nodeList, err := node.Get() - for _, n := range nodeList.Nodes { - if n.IsWindows() && n.Metadata.Name != nodeName { - n.AddTaint(node.Taint{Key: "key", Value: "value", Effect: "NoSchedule"}) - } - } - - // Removing taints - defer func(nodeList *node.List, nodeName string) { - for _, n := range nodeList.Nodes { - if n.IsWindows() && n.Metadata.Name != nodeName { - n.RemoveTaint(node.Taint{Key: "key", Value: "value", Effect: "NoSchedule"}) - } - } - }(nodeList, nodeName) - - By("Restarting VM " + nodeName + " in resource group " + cfg.ResourceGroup) - - // Getting vmss for the vm - vmssPage, err := azureClient.ListVirtualMachineScaleSets(ctx, cfg.ResourceGroup) - vmssList := vmssPage.Values() - - // Name of VMSS of nodeName - var vmssName string - // InstanceID of VM in its VMSS - var instanceID string - for _, vmss := range vmssList { - if !strings.Contains(nodeName, *vmss.Name) { - continue - } - vmName := *vmss.Name + "_" + nodeName[len(nodeName)-1:] - vmPage, err := azureClient.ListVirtualMachineScaleSetVMs(ctx, cfg.ResourceGroup, *vmss.Name) - Expect(err).NotTo(HaveOccurred()) - - vmList := vmPage.Values() - for _, vm := range vmList { - if vmName == *vm.Name { - vmssName = *vmss.Name - instanceID = *vm.InstanceID - break - } - } - if instanceID != "" { - break - } - } - // TODO refactor to remove the "compute" usage so the test can be run on Azure Stack - instanceIDs := &compute.VirtualMachineScaleSetVMInstanceIDs{&[]string{instanceID}} - err = azureClient.RestartVirtualMachineScaleSets(ctx, cfg.ResourceGroup, vmssName, instanceIDs) - Expect(err).NotTo(HaveOccurred()) - - //Wait for VM to come up - time.Sleep(30 * time.Second) - - By("Verifying that the service is still reachable and returns the default IIS start page") - err = iisService.ValidateWithRetry("(IIS Windows Server)", sleepBetweenRetriesWhenWaitingForPodReady, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - } else { - Skip("No windows agent was provisioned for this Cluster Definition") - } - }) // metrics endpoints failing in 1.18+ // https://github.com/kubernetes/kubernetes/issues/95735 @@ -2972,242 +2846,5 @@ var _ = Describe("Azure Container Cluster using the Kubernetes Orchestrator", fu Skip("Skip per-node tests in low-priority VMSS cluster configuration scenario") } }) - - It("should be able to install vmss node prototype", func() { - if cfg.RunVMSSNodePrototype { - if eng.ExpandedDefinition.Properties.HasVMSSAgentPool() { - newKaminoNodes, err := strconv.Atoi(cfg.KaminoVMSSNewNodes) - Expect(err).NotTo(HaveOccurred()) - By("Installing kured with node annotations configuration") - var kuredCommand *exec.Cmd - if cfg.KuredLocalChartPath == "" { - kuredCommand = exec.Command("helm", "install", "--wait", "--generate-name", "--repo", "https://weaveworks.github.io/kured", "kured", "--set", "configuration.annotateNodes=true", "--set", "configuration.period=1m") - } else { - kuredCommand = exec.Command("helm", "install", "--wait", "kured", cfg.KuredLocalChartPath, "--set", "configuration.annotateNodes=true", "--set", "configuration.period=1m") - } - util.PrintCommand(kuredCommand) - out, err := kuredCommand.CombinedOutput() - log.Printf("%s\n", out) - Expect(err).NotTo(HaveOccurred()) - nodes, err := node.GetReadyWithRetry(1*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - var numAgentNodes, numControlPlaneNodes int - controlPlaneNodeRegexStr := fmt.Sprintf("^%s-.*", common.LegacyControlPlaneVMPrefix) - controlPlaneNodeRegexp, err := regexp.Compile(controlPlaneNodeRegexStr) - Expect(err).NotTo(HaveOccurred()) - for _, n := range nodes { - if n.IsLinux() { - if controlPlaneNodeRegexp.MatchString(n.Metadata.Name) { - numControlPlaneNodes++ - } else { - numAgentNodes++ - } - } - } - var largeContainerDaemonset *daemonset.Daemonset - var numLargeContainerPods int - if !cfg.KaminoVMSSPrototypeDryRun { - By("Creating a DaemonSet with a large container") - var err error - largeContainerDaemonset, err = daemonset.CreateDaemonsetDeleteIfExists(filepath.Join(WorkloadDir, "large-container-daemonset.yaml"), "large-container-daemonset", "default", "app", "large-container-daemonset", 5*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - start := time.Now() - pods, err := pod.WaitForMinRunningByLabelWithRetry(numAgentNodes, "app", "large-container-daemonset", "default", 1*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - numLargeContainerPods = len(pods) - Expect(pods).NotTo(BeEmpty()) - elapsed := time.Since(start) - log.Printf("Took %s to schedule %d Pods with large containers via DaemonSet\n", elapsed, numLargeContainerPods) - } - By("Marking all nodes as needing reboots") - for _, n := range nodes { - if n.IsLinux() && !controlPlaneNodeRegexp.MatchString(n.Metadata.Name) { - err = sshConn.ExecuteRemoteWithRetry(n.Metadata.Name, fmt.Sprintf("\"sudo touch /var/run/reboot-required\""), false, 30*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - } - } - By("Waiting for one node to be marked as SchedulingDisabled by kured") - ready := node.WaitOnReadyMax(len(nodes)-1, 5*time.Second, cfg.Timeout) - Expect(ready).To(BeTrue()) - By("Waiting for nodes to be be rebooted and annotated correctly") - _, err = node.WaitForNodesWithAnnotation(numAgentNodes, "weave.works/kured-most-recent-reboot-needed", "", 5*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - _, err = node.WaitForNodesWithAnnotation(0, "weave.works/kured-reboot-in-progress", "", 1*time.Minute, time.Duration(5*numAgentNodes)*time.Minute) - Expect(err).NotTo(HaveOccurred()) - By("Waiting for all nodes to be Ready again") - ready = node.WaitOnReady(len(nodes), 30*time.Second, cfg.Timeout) - Expect(ready).To(Equal(true)) - ctx, cancel := context.WithTimeout(context.Background(), cfg.Timeout) - defer cancel() - // Getting vmss for the vm - vmssPage, err := azureClient.ListVirtualMachineScaleSets(ctx, cfg.ResourceGroup) - Expect(err).NotTo(HaveOccurred()) - Expect(vmssPage).NotTo(BeNil()) - vmssList := vmssPage.Values() - // Name of VMSS of nodeName - var vmssName string - var vmssSku *compute.Sku - var timeToAddNewNodeBaseline, timeToLargeContainerDaemonsetRunningBaseline time.Duration - for i, vmss := range vmssList { - vmssName = *vmss.Name - vmssSku = vmss.Sku - Expect(vmssName).NotTo(BeEmpty()) - Expect(vmssSku).NotTo(BeNil()) - originalCapacity := *vmssSku.Capacity - // get a pre-kamino scaling baseline against the first VMSS in the cluster - if !cfg.KaminoVMSSPrototypeDryRun && i == 0 { - By(fmt.Sprintf("Adding one new node to VMSS %s get a baseline", vmssName)) - ctx2, cancel2 := context.WithTimeout(context.Background(), cfg.Timeout) - defer cancel2() - start := time.Now() - err = azureClient.SetVirtualMachineScaleSetCapacity( - ctx2, - cfg.ResourceGroup, - vmssName, - compute.Sku{ - Name: vmssSku.Name, - Capacity: to.Int64Ptr(originalCapacity + 1), - }, - eng.ExpandedDefinition.Location, - ) - Expect(err).NotTo(HaveOccurred()) - By("Waiting for the new node to become Ready") - ready := node.WaitOnReadyMin(numAgentNodes+1, 500*time.Millisecond, false, cfg.Timeout) - Expect(ready).To(BeTrue()) - timeToAddNewNodeBaseline = time.Since(start) - log.Printf("Took %s to add 1 node\n", timeToAddNewNodeBaseline) - By("Ensuring that we have one additional large container pod after scaling out by one") - start = time.Now() - _, err = pod.WaitForMinRunningByLabelWithRetry(numLargeContainerPods+1, "app", "large-container-daemonset", "default", 5*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - numLargeContainerPods++ - timeToLargeContainerDaemonsetRunningBaseline = time.Since(start) - log.Printf("Took %s for large-container-daemonset pod to reach Running state on new node\n", timeToLargeContainerDaemonsetRunningBaseline) - } - vmssNodes, err := node.GetByRegexWithRetry(fmt.Sprintf("^%s", vmssName), 1*time.Minute, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - Expect(len(vmssNodes)).To(BeNumerically(">", 0)) - helmName := fmt.Sprintf("vmss-prototype-%s", vmssName) - cmd := exec.Command("helm", "status", helmName) - out, err = cmd.CombinedOutput() - if err == nil { - By(fmt.Sprintf("Found pre-existing '%s' helm release, deleting it...", helmName)) - cmd := exec.Command("helm", "delete", helmName) - out, err := cmd.CombinedOutput() - log.Printf("%s\n", out) - Expect(err).NotTo(HaveOccurred()) - } - commandArgsSlice := []string{"upgrade", "--install"} - if cfg.KaminoVMSSPrototypeLocalChartPath == "" { - commandArgsSlice = append(commandArgsSlice, []string{"--repo", "https://jackfrancis.github.io/kamino/", helmName, "vmss-prototype"}...) - } else { - commandArgsSlice = append(commandArgsSlice, []string{helmName, cfg.KaminoVMSSPrototypeLocalChartPath}...) - } - newUpdatedNodes := newKaminoNodes - // account for the node we already added above to take a pre-kamino scaling baseline against the first VMSS in the cluster - if i == 0 { - newUpdatedNodes-- - } - commandArgsSlice = append(commandArgsSlice, []string{"--namespace", "default", "--set", fmt.Sprintf("kamino.name=%s", vmssName), "--set", "kamino.scheduleOnControlPlane=true", "--set", fmt.Sprintf("kamino.newUpdatedNodes=%d", newUpdatedNodes), "--set", "kamino.logLevel=DEBUG", "--set", fmt.Sprintf("kamino.targetVMSS=%s", vmssName), "--set", "kamino.auto.lastPatchAnnotation=weave.works/kured-most-recent-reboot-needed", "--set", "kamino.auto.pendingRebootAnnotation=weave.works/kured-reboot-in-progress", "--set", "kamino.auto.minimumReadyTime=1s"}...) - if cfg.KaminoVMSSPrototypeImageRegistry != "" { - commandArgsSlice = append(commandArgsSlice, []string{"--set", fmt.Sprintf("kamino.container.imageRegistry=%s", cfg.KaminoVMSSPrototypeImageRegistry)}...) - } - if cfg.KaminoVMSSPrototypeImageRepository != "" { - commandArgsSlice = append(commandArgsSlice, []string{"--set", fmt.Sprintf("kamino.container.imageRepository=%s", cfg.KaminoVMSSPrototypeImageRepository)}...) - } - if cfg.KaminoVMSSPrototypeImageTag != "" { - commandArgsSlice = append(commandArgsSlice, []string{"--set", fmt.Sprintf("kamino.container.imageTag=%s", cfg.KaminoVMSSPrototypeImageTag), "--set", "kamino.container.pullByHash=false"}...) - } - if cfg.KaminoVMSSPrototypeDryRun { - commandArgsSlice = append(commandArgsSlice, []string{"--set", "kamino.auto.dryRun=true"}...) - } - cmd = exec.Command("helm", commandArgsSlice...) - util.PrintCommand(cmd) - out, err = cmd.CombinedOutput() - log.Printf("%s\n", out) - Expect(err).NotTo(HaveOccurred()) - } - start := time.Now() - numVMSS := len(vmssList) - By("Ensuring that the kamino-vmss-prototype pods runs to completion") - succeededPods, getSucceededErr := pod.WaitForMinSucceededByLabelWithRetry(numVMSS, "app", "kamino-vmss-prototype", "default", timeToLargeContainerDaemonsetRunningBaseline, sigPublishingTimeout) - jobs, err := job.GetAllByLabelWithRetry("app", "kamino-vmss-prototype", "default", 5*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - Expect(len(jobs)).To(Equal(numVMSS)) - for _, j := range jobs { - err = j.Describe() - Expect(err).NotTo(HaveOccurred()) - } - pods, err := pod.GetAllByLabelWithRetry("app", "kamino-vmss-prototype", "default", 5*time.Second, cfg.Timeout) - Expect(err).NotTo(HaveOccurred()) - Expect(len(pods)).To(Equal(numVMSS)) - for _, p := range pods { - err = p.Describe() - Expect(err).NotTo(HaveOccurred()) - err = p.Logs() - Expect(err).NotTo(HaveOccurred()) - } - Expect(getSucceededErr).NotTo(HaveOccurred()) - Expect(len(succeededPods)).To(Equal(numVMSS)) - elapsed := time.Since(start) - log.Printf("Took %s to run kamino-vmss-prototype Jobs to completion\n", elapsed) - if !cfg.KaminoVMSSPrototypeDryRun { - newKaminoNodes *= numVMSS - numNodesExpected := numAgentNodes + newKaminoNodes + numControlPlaneNodes - numLargeContainerPodsExpected := numAgentNodes + newKaminoNodes - By(fmt.Sprintf("Waiting for the %d new nodes created from prototype(s) to become Ready; waiting for %d total nodes", newKaminoNodes, numNodesExpected)) - timeToWaitForLargeCluster := time.Duration(newKaminoNodes/1000) * time.Hour - timeToWaitForNewNodes := timeToWaitForLargeCluster - if cfg.Timeout > timeToWaitForLargeCluster { - timeToWaitForNewNodes = cfg.Timeout - } - start := time.Now() - ready := node.WaitOnReadyMin(numNodesExpected, 1*time.Minute, false, timeToWaitForNewNodes) - if !ready { - nodes, err := node.GetReadyWithRetry(1*time.Second, cfg.Timeout) - if err != nil { - log.Printf("Not enough Ready nodes! Expected %d, but only %d nodes are Ready", numNodesExpected, len(nodes)) - } - } - Expect(ready).To(BeTrue()) - elapsed = time.Since(start) - log.Printf("Took %s to add %d nodes derived from peer node prototype(s)\n", elapsed, newKaminoNodes) - By("Ensuring that we have additional large container pods after scaling out") - start = time.Now() - p, err := pod.WaitForMinRunningByLabelWithRetry(numLargeContainerPodsExpected, "app", "large-container-daemonset", "default", 5*time.Second, timeToLargeContainerDaemonsetRunningBaseline) - if err != nil { - log.Printf("%d large container pods were ready before %s", len(p), timeToLargeContainerDaemonsetRunningBaseline) - _, err = pod.WaitForMinRunningByLabelWithRetry(numLargeContainerPodsExpected, "app", "large-container-daemonset", "default", 5*time.Second, 1*time.Hour) - Expect(err).NotTo(HaveOccurred()) - elapsed = time.Since(start) - } else { - elapsed = time.Since(start) - } - log.Printf("Took %s for %d large-container-daemonset pods to reach Running state on new node built from prototype\n", elapsed, numLargeContainerPods+newKaminoNodes) - By("Deleting large container DaemonSet") - err = largeContainerDaemonset.Delete(util.DefaultDeleteRetries) - Expect(err).NotTo(HaveOccurred()) - } - } else { - Skip("no VMSS node pools") - } - } else { - Skip("InstallVMSSNodePrototype disabled") - } - }) }) }) - -func RunVMSSHealthCheck(cfg config.Config) (*exec.Cmd, error) { - outfile, err := os.Create(fmt.Sprintf("./vmss-health-check-%s.out", cfg.ResourceGroup)) - if err != nil { - return nil, err - } - defer outfile.Close() - cmd := exec.Command("scripts/vmss-health-check.sh") - cmd.Env = append(cmd.Env, fmt.Sprintf("RESOURCE_GROUP=%s", cfg.ResourceGroup)) - cmd.Env = append(cmd.Env, "LOOP_FOREVER=true") - cmd.Stdout = outfile - err = cmd.Start() - return cmd, err -} diff --git a/test/e2e/kubernetes/scripts/vmss-health-check.sh b/test/e2e/kubernetes/scripts/vmss-health-check.sh deleted file mode 100755 index 3525302ec..000000000 --- a/test/e2e/kubernetes/scripts/vmss-health-check.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash - -if [ -z "$RESOURCE_GROUP" ]; then - echo "must provide a RESOURCE_GROUP env var" - exit 1; -fi - -# TODO: track VMSS in a "Creating" state, enforce TTL, if "Creating TTL" expires: -# 1. Check if the "Creating" VMSS instance correlates with a running Kubernetes node in the cluster -# If so, (1) cordon/drain the node -# 2. Delete the instance in a stuck "Creating" state -# 3. Wait for the VMSS to achive a "Succeeded" ProvisioningState -# 4. Scale out the VMSS by 1 - -# Continually look for non-Succeeded VMSS instances -while true; do - NUM_VMSS=0 - NUM_TERMINAL_VMSS=0 - echo "$(date) Starting VMSS Health Remediation loop" - for VMSS in $(az vmss list -g $RESOURCE_GROUP | jq -r '.[] | .name'); do - ((NUM_VMSS++)) - NUM_DELETED_INSTANCES=0 - VMSS_PROVISIONING_STATE=$(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '.provisioningState') - echo "$(date) VMSS ${VMSS} has a ProvisioningState of ${VMSS_PROVISIONING_STATE}" - VMSS_CAPACITY=$(az vmss list -g $RESOURCE_GROUP | jq -r --arg VMSS "$VMSS" '.[] | select(.name == $VMSS) | .sku.capacity') - echo "$(date) VMSS ${VMSS} has a current capacity of ${VMSS_CAPACITY}" - if [ "$VMSS_PROVISIONING_STATE" == "Succeeded" ] || [ "$VMSS_PROVISIONING_STATE" == "Failed" ]; then - ((NUM_TERMINAL_VMSS++)) - HAS_FAILED_STATE_INSTANCE="false" - for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[] | select(.provisioningState == "Failed") | .name'); do - HAS_FAILED_STATE_INSTANCE="true" - echo "$(date) Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}" - if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_} --no-wait; then - sleep 30 - else - sleep 1 - ((NUM_DELETED_INSTANCES++)) - fi - done - for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.name == "vmssCSE" and .provisioningState == "Failed") | .id' | awk -F'/' '{print $9}'); do - HAS_FAILED_STATE_INSTANCE="true" - echo "$(date) Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}" - if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then - sleep 30 - else - sleep 1 - ((NUM_DELETED_INSTANCES++)) - fi - done - for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.publisher == "Microsoft.AKS" and .provisioningState != "Succeeded" and .provisioningState != "Creating" and .provisioningState != "Deleting") | .id' | awk -F'/' '{print $9}'); do - HAS_FAILED_STATE_INSTANCE="true" - echo "$(date) Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}" - if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then - sleep 30 - else - sleep 1 - ((NUM_DELETED_INSTANCES++)) - fi - done - if [ "$HAS_FAILED_STATE_INSTANCE" == "true" ]; then - echo "$(date) Waiting for ${VMSS} to reach a terminal ProvisioningState after failed instances were deleted..." - sleep 30 - until [[ $(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '. | select(.provisioningState == "Succeeded" or .provisioningState == "Failed") | .name') ]]; do - echo "$(date) Waiting for ${VMSS} to reach a terminal ProvisioningState after failed instances were deleted..." - sleep 30 - done - echo "$(date) VMSS ${VMSS} is in a terminal state after failed instances were deleted!" - fi - fi - if [ "$NUM_DELETED_INSTANCES" -gt "0" ]; then - echo "$(date) Instances were deleted from VMSS ${VMSS}, ensuring that capacity is set to ${VMSS_CAPACITY}" - az vmss scale --new-capacity $VMSS_CAPACITY -n $VMSS -g $RESOURCE_GROUP --no-wait; - fi - done - if [ "$LOOP_FOREVER" == "true" ]; then - sleep 150 - else - if [[ "${NUM_VMSS}" == "${NUM_TERMINAL_VMSS}" ]]; then - exit 0 - fi - fi -done 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 deleted file mode 100644 index 9796e9e7f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/applications.go +++ /dev/null @@ -1,1164 +0,0 @@ -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 using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index e22971a0f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/client.go +++ /dev/null @@ -1,52 +0,0 @@ -// 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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 deleted file mode 100644 index bd85fb340..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/deletedapplications.go +++ /dev/null @@ -1,363 +0,0 @@ -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 using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 924975dc3..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/domains.go +++ /dev/null @@ -1,192 +0,0 @@ -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 0daef502b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/groups.go +++ /dev/null @@ -1,1211 +0,0 @@ -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 73881629a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/models.go +++ /dev/null @@ -1,4679 +0,0 @@ -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} -} - -// GroupMembershipClaimTypes enumerates the values for group membership claim types. -type GroupMembershipClaimTypes string - -const ( - // All ... - All GroupMembershipClaimTypes = "All" - // None ... - None GroupMembershipClaimTypes = "None" - // SecurityGroup ... - SecurityGroup GroupMembershipClaimTypes = "SecurityGroup" -) - -// PossibleGroupMembershipClaimTypesValues returns an array of possible values for the GroupMembershipClaimTypes const type. -func PossibleGroupMembershipClaimTypesValues() []GroupMembershipClaimTypes { - return []GroupMembershipClaimTypes{All, None, SecurityGroup} -} - -// 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. Possible values include: 'None', 'SecurityGroup', 'All' - GroupMembershipClaims GroupMembershipClaimTypes `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 != "" { - 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 GroupMembershipClaimTypes - 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. Possible values include: 'None', 'SecurityGroup', 'All' - GroupMembershipClaims GroupMembershipClaimTypes `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. Possible values include: 'None', 'SecurityGroup', 'All' - GroupMembershipClaims GroupMembershipClaimTypes `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. Possible values include: 'None', 'SecurityGroup', 'All' - GroupMembershipClaims GroupMembershipClaimTypes `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 deleted file mode 100644 index 89dea96bb..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/oauth2permissiongrant.go +++ /dev/null @@ -1,367 +0,0 @@ -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 using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 2e5afd471..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/objects.go +++ /dev/null @@ -1,215 +0,0 @@ -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 24cd7315a..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/serviceprincipals.go +++ /dev/null @@ -1,933 +0,0 @@ -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 using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index 677692590..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/signedinuser.go +++ /dev/null @@ -1,281 +0,0 @@ -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 using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index e9325843b..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/users.go +++ /dev/null @@ -1,612 +0,0 @@ -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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. -// expand - the expand value for the operation result. -func (client UsersClient) List(ctx context.Context, filter string, expand 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, expand) - 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, expand 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) - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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, expand 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, expand) - 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// 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 deleted file mode 100644 index b0d5c79fd..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac/version.go +++ /dev/null @@ -1,30 +0,0 @@ -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() + " 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/go-autorest/autorest/azure/cli/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - 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_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go deleted file mode 100644 index 618bed392..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package cli - -// 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/azure/cli/profile.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go deleted file mode 100644 index a336b958d..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go +++ /dev/null @@ -1,79 +0,0 @@ -package cli - -// 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. - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/dimchansky/utfbom" - "github.com/mitchellh/go-homedir" -) - -// Profile represents a Profile from the Azure CLI -type Profile struct { - InstallationID string `json:"installationId"` - Subscriptions []Subscription `json:"subscriptions"` -} - -// Subscription represents a Subscription from the Azure CLI -type Subscription struct { - EnvironmentName string `json:"environmentName"` - ID string `json:"id"` - IsDefault bool `json:"isDefault"` - Name string `json:"name"` - State string `json:"state"` - TenantID string `json:"tenantId"` - User *User `json:"user"` -} - -// User represents a User from the Azure CLI -type User struct { - Name string `json:"name"` - 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) { - 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'. -func LoadProfile(path string) (result Profile, err error) { - var contents []byte - contents, err = ioutil.ReadFile(path) - if err != nil { - err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - return - } - reader := utfbom.SkipOnly(bytes.NewReader(contents)) - - dec := json.NewDecoder(reader) - if err = dec.Decode(&result); err != nil { - err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err) - return - } - - return -} 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 deleted file mode 100644 index 810075ba6..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go +++ /dev/null @@ -1,170 +0,0 @@ -package cli - -// 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. - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "os/exec" - "regexp" - "runtime" - "strconv" - "time" - - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/date" - "github.com/mitchellh/go-homedir" -) - -// Token represents an AccessToken from the Azure CLI -type Token struct { - AccessToken string `json:"accessToken"` - Authority string `json:"_authority"` - ClientID string `json:"_clientId"` - ExpiresOn string `json:"expiresOn"` - IdentityProvider string `json:"identityProvider"` - IsMRRT bool `json:"isMRRT"` - RefreshToken string `json:"refreshToken"` - Resource string `json:"resource"` - TokenType string `json:"tokenType"` - UserID string `json:"userId"` -} - -// ToADALToken converts an Azure CLI `Token`` to an `adal.Token`` -func (t Token) ToADALToken() (converted adal.Token, err error) { - tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn) - if err != nil { - err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err) - return - } - - difference := tokenExpirationDate.Sub(date.UnixEpoch()) - - converted = adal.Token{ - AccessToken: t.AccessToken, - Type: t.TokenType, - ExpiresIn: "3600", - ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))), - RefreshToken: t.RefreshToken, - Resource: t.Resource, - } - return -} - -// AccessTokensPath returns the path where access tokens are stored from the Azure CLI -// TODO(#199): add unit test. -func AccessTokensPath() (string, error) { - // Azure-CLI allows user to customize the path of access tokens thorugh environment variable. - var accessTokenPath = os.Getenv("AZURE_ACCESS_TOKEN_FILE") - var err error - - // Fallback logic to default path on non-cloud-shell environment. - // TODO(#200): remove the dependency on hard-coding path. - if accessTokenPath == "" { - accessTokenPath, err = homedir.Expand("~/.azure/accessTokens.json") - } - - return accessTokenPath, err -} - -// ParseExpirationDate parses either a Azure CLI or CloudShell date into a time object -func ParseExpirationDate(input string) (*time.Time, error) { - // CloudShell (and potentially the Azure CLI in future) - expirationDate, cloudShellErr := time.Parse(time.RFC3339, input) - if cloudShellErr != nil { - // Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone) - const cliFormat = "2006-01-02 15:04:05.999999" - expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local) - if cliErr == nil { - return &expirationDate, nil - } - - return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr) - } - - return &expirationDate, nil -} - -// LoadTokens restores a set of Token objects from a file located at 'path'. -func LoadTokens(path string) ([]Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var tokens []Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&tokens); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err) - } - - 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/dimchansky/utfbom/.gitignore b/vendor/github.com/dimchansky/utfbom/.gitignore deleted file mode 100644 index d7ec5cebb..000000000 --- a/vendor/github.com/dimchansky/utfbom/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib -*.o -*.a - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.prof - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ - -# Gogland -.idea/ \ No newline at end of file diff --git a/vendor/github.com/dimchansky/utfbom/.travis.yml b/vendor/github.com/dimchansky/utfbom/.travis.yml deleted file mode 100644 index 3512c8519..000000000 --- a/vendor/github.com/dimchansky/utfbom/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go - -go: - - '1.10' - - '1.11' - -# sudo=false makes the build run using a container -sudo: false - -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover - - go get golang.org/x/tools/cmd/goimports - - go get github.com/golang/lint/golint -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 diff --git a/vendor/github.com/dimchansky/utfbom/LICENSE b/vendor/github.com/dimchansky/utfbom/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/dimchansky/utfbom/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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 - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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/dimchansky/utfbom/README.md b/vendor/github.com/dimchansky/utfbom/README.md deleted file mode 100644 index 8ece28008..000000000 --- a/vendor/github.com/dimchansky/utfbom/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# utfbom [![Godoc](https://godoc.org/github.com/dimchansky/utfbom?status.png)](https://godoc.org/github.com/dimchansky/utfbom) [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Build Status](https://travis-ci.org/dimchansky/utfbom.svg?branch=master)](https://travis-ci.org/dimchansky/utfbom) [![Go Report Card](https://goreportcard.com/badge/github.com/dimchansky/utfbom)](https://goreportcard.com/report/github.com/dimchansky/utfbom) [![Coverage Status](https://coveralls.io/repos/github/dimchansky/utfbom/badge.svg?branch=master)](https://coveralls.io/github/dimchansky/utfbom?branch=master) - -The package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. It can also return the encoding detected by the BOM. - -## Installation - - go get -u github.com/dimchansky/utfbom - -## Example - -```go -package main - -import ( - "bytes" - "fmt" - "io/ioutil" - - "github.com/dimchansky/utfbom" -) - -func main() { - trySkip([]byte("\xEF\xBB\xBFhello")) - trySkip([]byte("hello")) -} - -func trySkip(byteData []byte) { - fmt.Println("Input:", byteData) - - // just skip BOM - output, err := ioutil.ReadAll(utfbom.SkipOnly(bytes.NewReader(byteData))) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("ReadAll with BOM skipping", output) - - // skip BOM and detect encoding - sr, enc := utfbom.Skip(bytes.NewReader(byteData)) - fmt.Printf("Detected encoding: %s\n", enc) - output, err = ioutil.ReadAll(sr) - if err != nil { - fmt.Println(err) - return - } - fmt.Println("ReadAll with BOM detection and skipping", output) - fmt.Println() -} -``` - -Output: - -``` -$ go run main.go -Input: [239 187 191 104 101 108 108 111] -ReadAll with BOM skipping [104 101 108 108 111] -Detected encoding: UTF8 -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 -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 deleted file mode 100644 index 77a303e56..000000000 --- a/vendor/github.com/dimchansky/utfbom/utfbom.go +++ /dev/null @@ -1,192 +0,0 @@ -// Package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. -// It wraps an io.Reader object, creating another object (Reader) that also implements the io.Reader -// interface but provides automatic BOM checking and removing as necessary. -package utfbom - -import ( - "errors" - "io" -) - -// Encoding is type alias for detected UTF encoding. -type Encoding int - -// Constants to identify detected UTF encodings. -const ( - // Unknown encoding, returned when no BOM was detected - Unknown Encoding = iota - - // UTF8, BOM bytes: EF BB BF - UTF8 - - // UTF-16, big-endian, BOM bytes: FE FF - UTF16BigEndian - - // UTF-16, little-endian, BOM bytes: FF FE - UTF16LittleEndian - - // UTF-32, big-endian, BOM bytes: 00 00 FE FF - UTF32BigEndian - - // UTF-32, little-endian, BOM bytes: FF FE 00 00 - 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. -// It also returns the encoding detected by the BOM. -// If the detected encoding is not needed, you can call the SkipOnly function. -func Skip(rd io.Reader) (*Reader, Encoding) { - // Is it already a Reader? - b, ok := rd.(*Reader) - if ok { - return b, Unknown - } - - enc, left, err := detectUtf(rd) - return &Reader{ - rd: rd, - buf: left, - err: err, - }, enc -} - -// SkipOnly creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -func SkipOnly(rd io.Reader) *Reader { - r, _ := Skip(rd) - return r -} - -// Reader implements automatic BOM (Unicode Byte Order Mark) checking and -// removing as necessary for an io.Reader object. -type Reader struct { - rd io.Reader // reader provided by the client - buf []byte // buffered data - err error // last error -} - -// Read is an implementation of io.Reader interface. -// The bytes are taken from the underlying Reader, but it checks for BOMs, removing them as necessary. -func (r *Reader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - - if r.buf == nil { - if r.err != nil { - return 0, r.readErr() - } - - return r.rd.Read(p) - } - - // copy as much as we can - n = copy(p, r.buf) - r.buf = nilIfEmpty(r.buf[n:]) - return n, nil -} - -func (r *Reader) readErr() error { - err := r.err - r.err = nil - return err -} - -var errNegativeRead = errors.New("utfbom: reader returned negative count from Read") - -func detectUtf(rd io.Reader) (enc Encoding, buf []byte, err error) { - buf, err = readBOM(rd) - - if len(buf) >= 4 { - if isUTF32BigEndianBOM4(buf) { - return UTF32BigEndian, nilIfEmpty(buf[4:]), err - } - if isUTF32LittleEndianBOM4(buf) { - return UTF32LittleEndian, nilIfEmpty(buf[4:]), err - } - } - - if len(buf) > 2 && isUTF8BOM3(buf) { - return UTF8, nilIfEmpty(buf[3:]), err - } - - if (err != nil && err != io.EOF) || (len(buf) < 2) { - return Unknown, nilIfEmpty(buf), err - } - - if isUTF16BigEndianBOM2(buf) { - return UTF16BigEndian, nilIfEmpty(buf[2:]), err - } - if isUTF16LittleEndianBOM2(buf) { - return UTF16LittleEndian, nilIfEmpty(buf[2:]), err - } - - return Unknown, nilIfEmpty(buf), err -} - -func readBOM(rd io.Reader) (buf []byte, err error) { - const maxBOMSize = 4 - var bom [maxBOMSize]byte // used to read BOM - - // read as many bytes as possible - for nEmpty, n := 0, 0; err == nil && len(buf) < maxBOMSize; buf = bom[:len(buf)+n] { - if n, err = rd.Read(bom[len(buf):]); n < 0 { - panic(errNegativeRead) - } - if n > 0 { - nEmpty = 0 - } else { - nEmpty++ - if nEmpty >= maxConsecutiveEmptyReads { - err = io.ErrNoProgress - } - } - } - return -} - -func isUTF32BigEndianBOM4(buf []byte) bool { - return buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0xFE && buf[3] == 0xFF -} - -func isUTF32LittleEndianBOM4(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE && buf[2] == 0x00 && buf[3] == 0x00 -} - -func isUTF8BOM3(buf []byte) bool { - return buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF -} - -func isUTF16BigEndianBOM2(buf []byte) bool { - return buf[0] == 0xFE && buf[1] == 0xFF -} - -func isUTF16LittleEndianBOM2(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE -} - -func nilIfEmpty(buf []byte) (res []byte) { - if len(buf) > 0 { - res = buf - } - return -} diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a51..000000000 --- a/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -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. diff --git a/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5b..000000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537e..000000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 3028ef3e3..6580cea36 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -8,7 +8,6 @@ github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authori github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-03-30/compute github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb -github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-10-01/network github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-08-01/network @@ -35,9 +34,6 @@ github.com/Azure/go-autorest/autorest/azure # github.com/Azure/go-autorest/autorest/adal v0.9.10 ## explicit; go 1.12 github.com/Azure/go-autorest/autorest/adal -# github.com/Azure/go-autorest/autorest/azure/cli v0.3.0 -## explicit; go 1.12 -github.com/Azure/go-autorest/autorest/azure/cli # github.com/Azure/go-autorest/autorest/date v0.3.0 ## explicit; go 1.12 github.com/Azure/go-autorest/autorest/date @@ -65,9 +61,6 @@ github.com/blang/semver # github.com/davecgh/go-spew v1.1.1 ## explicit github.com/davecgh/go-spew/spew -# github.com/dimchansky/utfbom v1.1.0 -## explicit -github.com/dimchansky/utfbom # github.com/dnaeon/go-vcr v1.0.1 ## explicit # github.com/emicklei/go-restful/v3 v3.9.0 @@ -184,9 +177,6 @@ github.com/mattn/go-isatty # github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b ## explicit github.com/mgutz/ansi -# github.com/mitchellh/go-homedir v1.1.0 -## explicit -github.com/mitchellh/go-homedir # github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd ## explicit github.com/modern-go/concurrent