diff --git a/go.mod b/go.mod index 70b16f6ba..87eb8327c 100644 --- a/go.mod +++ b/go.mod @@ -156,12 +156,14 @@ require ( k8s.io/kubelet v0.29.2 // indirect k8s.io/pod-security-admission v0.29.0 sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0 // indirect - sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.7 + sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.9 sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect ) require ( + github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets v0.12.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect github.com/distribution/reference v0.5.0 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect diff --git a/go.sum b/go.sum index bd9610621..de3a950a7 100644 --- a/go.sum +++ b/go.sum @@ -11,6 +11,10 @@ github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+ github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1/go.mod h1:h8hyGFDsU5HMivxiS2iYFZsgDbU9OnnJ163x5UGVKYo= github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 h1:LqbJ/WzJUwBf8UiaSzgX7aMclParm9/5Vgp+TY51uBQ= github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc= +github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets v0.12.0 h1:xnO4sFyG8UH2fElBkcqLTOZsAajvKfnSlgBBW8dXYjw= +github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets v0.12.0/go.mod h1:XD3DIOOVgBCO03OleB1fHjgktVRFxlT++KwKgIOewdM= +github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 h1:FbH3BbSb4bvGluTesZZ+ttN/MDsnMmQP36OSnDuSXqw= +github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1/go.mod h1:9V2j0jn9jDEkCkv8w/bKTNppX/d0FVA1ud77xCIP4KA= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.6.0 h1:ui3YNbxfW7J3tTFIZMH6LIGRjCngp+J+nIFlnizfNTE= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.6.0/go.mod h1:gZmgV+qBqygoznvqo2J9oKZAFziqhLZ2xE/WVUmzkHA= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry v1.2.0 h1:DWlwvVV5r/Wy1561nZ3wrpI1/vDIBRY/Wd1HWaRBZWA= @@ -464,8 +468,8 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0 h1:TgtAeesdhpm2S sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.28.0/go.mod h1:VHVDI/KrK4fjnV61bE2g3sA7tiETLn8sooImelsCx3Y= sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240319093822-58cad130d9dc h1:y/jDBU+4EcPiHGPMQeK6B4IKEhOp3CCts/ZaRH1sa3w= sigs.k8s.io/cloud-provider-azure v1.27.1-0.20240319093822-58cad130d9dc/go.mod h1:nS6tUQgopFVyqFQW1P/luDXNNQfsQOg3WFs9GhzNjm8= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.7 h1:2i90v/+RL6UmN9zE8bDxEy8DpEdIK9WiwmrGS6XoDgk= -sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.7/go.mod h1:4rMNajTN5xEbeVGFWfAeqorkednAmXM5/d8OK+ux+tY= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.9 h1:Dqfn77jXMi78OrCA0clZyqJtTeyxj7dBeF23lp/nT2s= +sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.9/go.mod h1:/jwCAe6Nh26G687RvUbmd0CjW4GHHXI/xOAOCSF1XqQ= sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.3 h1:4Sk81u8kxM+yTjEfC9lPP3YyLpWeDTFRquI/3a5AzRY= sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader v0.0.3/go.mod h1:FWY5fW/WLg/S1Iul/Mh5YeRyQhl8Ii1Sk+YLLOj3KDk= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/CHANGELOG.md new file mode 100644 index 000000000..8a5c4cc9f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/CHANGELOG.md @@ -0,0 +1,110 @@ +# Release History + +## 0.12.0 (2023-04-13) + +### Features Added +* upgraded to api version 7.4 + +### Breaking Changes +* This module is now DEPRECATED. The latest supported version of this module is at github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets + +## 0.11.0 (2022-11-08) + +### Breaking Changes +* `NewClient` returns an `error` + +## 0.10.1 (2022-09-20) + +### Features Added +* Added `ClientOptions.DisableChallengeResourceVerification`. + See https://aka.ms/azsdk/blog/vault-uri for more information. + +## 0.10.0 (2022-09-12) + +### Breaking Changes +* Verify the challenge resource matches the vault domain. + +## 0.9.0 (2022-08-09) + +### Breaking Changes +* Changed type of `NewClient` options parameter to `azsecrets.ClientOptions`, which embeds + the former type, `azcore.ClientOptions` + +## 0.8.0 (2022-07-07) + +### Breaking Changes +* The `Client` API now corresponds more directly to the Key Vault REST API. + Most method signatures and types have changed. See the + [module documentation](https://aka.ms/azsdk/go/keyvault-secrets/docs) + for updated code examples and more details. + +### Other Changes +* Upgrade to latest `azcore` + +## 0.7.1 (2022-05-12) + +### Other Changes +* Updated to latest `azcore` and `internal` modules. + +## 0.7.0 (2022-04-06) + +### Features Added +* Added `PossibleDeletionRecoveryLevelValues` to iterate over all valid `DeletionRecoveryLevel` values +* Implemented generic pagers from `runtime.Pager` for all List operations +* Added `Name *string` to `DeletedSecret`, `Properties`, `Secret`, `SecretItem`, and `SecretItem` +* Added `Client.VaultURL` to determine the vault URL for debugging +* Adding `ResumeToken` method to pollers for resuming polling at a later date by using the added `ResumeToken` optional parameter on client polling methods + +### Breaking Changes +* Requires a minimum version of go 1.18 +* Removed `RawResponse` from pollers +* Removed `DeletionRecoveryLevel` +* Polling operations return a Poller struct directly instead of a Response envelope +* Removed `ToPtr` methods +* `Client.UpdateSecretProperties` takes a `Secret` +* Renamed `Client.ListSecrets` to `Client.ListPropertiesOfSecrets` +* Renamed `Client.ListSecretVersions` to `Client.ListPropertiesOfSecretVersions` +* Renamed `DeletedDate` to `DeletedOn` and `Managed` to `IsManaged` +* Moved `ContentType`, `Tags`, `KeyID`, and `IsManaged` to `Properties` + +## 0.6.0 (2022-03-08) + +### Breaking Changes +* Changes `Attributes` to `Properties` +* Changes `Secret.KID` to `Secret.KeyID` +* Changes `DeletedSecretBundle` to `DeletedSecret` +* Changes `DeletedDate` to `DeletedOn`, `Created` to `CreatedOn`, and `Updated` to `UpdatedOn` +* Changes the signature of `Client.UpdateSecretProperties` to have all alterable properties in the `UpdateSecretPropertiesOptions` parameter, removing the `parameters Properties` parameter. +* Changes `Item` to `SecretItem` +* Pollers and pagers are structs instead of interfaces +* Prefixed all `DeletionRecoveryLevel` constants with "DeletionRecoveryLevel" +* Changed pager APIs for `ListSecretVersionsPager`, `ListDeletedSecretsPager`, and `ListSecretsPager` + * Use the `More()` method to determine if there are more pages to fetch + * Use the `NextPage(context.Context)` to fetch the next page of results +* Removed all `RawResponse *http.Response` fields from response structs. + +## 0.5.0 (2022-02-08) + +### Breaking Changes +* Fixes a bug where `UpdateSecretProperties` will delete properties that are not explicitly set each time. This is only a breaking change at runtime, where the request body will change. + +## 0.4.0 (2022-01-11) + +### Other Changes +* Bumps `azcore` dependency from `v0.20.0` to `v0.21.0` + +## 0.3.0 (2021-11-09) + +### Features Added +* Clients can now connect to Key Vaults in any cloud + +## 0.2.0 (2021-11-02) + +### Other Changes +* Bumps `azcore` dependency to `v0.20.0` and `azidentity` to `v0.12.0` + +## 0.1.1 (2021-10-06) +* Adds the MIT License for redistribution + +## 0.1.0 (2021-10-05) +* This is the initial release of the `azsecrets` library diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/LICENSE.txt new file mode 100644 index 000000000..d1ca00f20 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/LICENSE.txt @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/README.md new file mode 100644 index 000000000..06a23c841 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/README.md @@ -0,0 +1,144 @@ +# Azure Key Vault Secrets client module for Go +> Deprecated: use github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets instead + +Azure Key Vault helps solve the following problems: +* Secrets management (this module) - securely store and control access to tokens, passwords, certificates, API keys, and other secrets +* Cryptographic key management ([azkeys](https://azsdk/go/keyvault-keys/docs)) - create, store, and control access to the keys used to encrypt your data +* Certificate management ([azcertificates](https://aka.ms/azsdk/go/keyvault-certificates/docs)) - create, manage, and deploy public and private SSL/TLS certificates + +[Source code][module_source] | [Package (pkg.go.dev)][reference_docs] | [Product documentation][keyvault_docs] | [Samples][secrets_samples] + +## Getting started + +### Install packages + +Install `azsecrets` and `azidentity` with `go get`: +``` +go get github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets +go get github.com/Azure/azure-sdk-for-go/sdk/azidentity +``` +[azidentity][azure_identity] is used for Azure Active Directory authentication as demonstrated below. + + +### Prerequisites + +* An [Azure subscription][azure_sub] +* A supported Go version (the Azure SDK supports the two most recent Go releases) +* A key vault. If you need to create one, see the Key Vault documentation for instructions on doing so in the [Azure Portal][azure_keyvault_portal] or with the [Azure CLI][azure_keyvault_cli]. + +### Authentication + +This document demonstrates using [azidentity.NewDefaultAzureCredential][default_cred_ref] to authenticate. This credential type works in both local development and production environments. We recommend using a [managed identity][managed_identity] in production. + +[Client][client_docs] accepts any [azidentity][azure_identity] credential. See the [azidentity][azure_identity] documentation for more information about other credential types. + +#### Create a client + +Constructing the client also requires your vault's URL, which you can get from the Azure CLI or the Azure Portal. + +```golang +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets" +) + +func main() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + // TODO: handle error + } + + client := azsecrets.NewClient("https://.vault.azure.net", cred, nil) +} +``` + +## Key concepts + +### Secret + +A secret consists of a secret value and its associated metadata and management information. This library handles secret values as strings, but Azure Key Vault doesn't store them as such. For more information about secrets and how Key Vault stores and manages them, see the [Key Vault documentation](https://docs.microsoft.com/azure/key-vault/general/about-keys-secrets-certificates). + +`azseecrets.Client` can set secret values in the vault, update secret metadata, and delete secrets, as shown in the examples below. + +## Examples + +Get started with our [examples](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets#pkg-examples). + +## Troubleshooting + +### Error Handling + +All methods which send HTTP requests return `*azcore.ResponseError` when these requests fail. `ResponseError` has error details and the raw response from Key Vault. + +```go +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +resp, err := client.GetSecret(context.Background(), "secretName", nil) +if err != nil { + var httpErr *azcore.ResponseError + if errors.As(err, &httpErr) { + // TODO: investigate httpErr + } else { + // TODO: not an HTTP error + } +} +``` + +### Logging + +This module uses the logging implementation in `azcore`. To turn on logging for all Azure SDK modules, set `AZURE_SDK_GO_LOGGING` to `all`. By default the logger writes to stderr. Use the `azcore/log` package to control log output. For example, logging only HTTP request and response events, and printing them to stdout: + +```go +import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + +// Print log events to stdout +azlog.SetListener(func(cls azlog.Event, msg string) { + fmt.Println(msg) +}) + +// Includes only requests and responses in credential logs +azlog.SetEvents(azlog.EventRequest, azlog.EventResponse) +``` + +### Accessing `http.Response` + +You can access the raw `*http.Response` returned by Key Vault using the `runtime.WithCaptureResponse` method and a context passed to any client method. + +```go +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + +var response *http.Response +ctx := runtime.WithCaptureResponse(context.TODO(), &response) +_, err = client.GetSecret(ctx, "secretName", nil) +if err != nil { + // TODO: handle error +} +// TODO: do something with response +``` + +### Additional Documentation + +See the [API reference documentation][reference_docs] for complete documentation of this module. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments. + +[azure_identity]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity +[azure_keyvault_cli]: https://docs.microsoft.com/azure/key-vault/general/quick-create-cli +[azure_keyvault_portal]: https://docs.microsoft.com/azure/key-vault/general/quick-create-portal +[azure_sub]: https://azure.microsoft.com/free/ +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[default_cred_ref]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity#defaultazurecredential +[keyvault_docs]: https://docs.microsoft.com/azure/key-vault/ +[managed_identity]: https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview +[reference_docs]: https://aka.ms/azsdk/go/keyvault-secrets/docs +[client_docs]: https://aka.ms/azsdk/go/keyvault-secrets/docs#Client +[module_source]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/keyvault/azsecrets +[secrets_samples]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/keyvault/azsecrets/example_test.go + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fkeyvault%2Fazsecrets%2FREADME.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/TROUBLESHOOTING.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/TROUBLESHOOTING.md new file mode 100644 index 000000000..72269c7a0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/TROUBLESHOOTING.md @@ -0,0 +1,4 @@ +# Troubleshoot Azure Key Vault Secrets Client Module Issues + +See our [Azure Key Vault SDK Troubleshooting Guide](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/keyvault/TROUBLESHOOTING.md) +to troubleshoot issues common to Azure Key Vault client modules. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/autorest.md new file mode 100644 index 000000000..e6cfb9f8c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/autorest.md @@ -0,0 +1,96 @@ +## Go + +These settings apply only when `--go` is specified on the command line. + +```yaml +clear-output-folder: false +export-clients: true +go: true +input-file: https://github.com/Azure/azure-rest-api-specs/blob/551275acb80e1f8b39036b79dfc35a8f63b601a7/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.4/secrets.json +license-header: MICROSOFT_MIT_NO_VERSION +module: github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets +openapi-type: "data-plane" +output-folder: ../azsecrets +override-client-name: Client +security: "AADToken" +security-scopes: "https://vault.azure.net/.default" +use: "@autorest/go@4.0.0-preview.46" +version: "^3.0.0" + +directive: + # delete unused model + - remove-model: SecretProperties + + # make vault URL a parameter of the client constructor + - from: swagger-document + where: $["x-ms-parameterized-host"] + transform: $.parameters[0]["x-ms-parameter-location"] = "client" + + # rename parameter models to match their methods + - rename-model: + from: SecretRestoreParameters + to: RestoreSecretParameters + - rename-model: + from: SecretSetParameters + to: SetSecretParameters + - rename-model: + from: SecretUpdateParameters + to: UpdateSecretParameters + + # rename paged operations from Get* to List* + - rename-operation: + from: GetDeletedSecrets + to: ListDeletedSecrets + - rename-operation: + from: GetSecrets + to: ListSecrets + - rename-operation: + from: GetSecretVersions + to: ListSecretVersions + + # delete unused error models + - from: models.go + where: $ + transform: return $.replace(/(?:\/\/.*\s)+type (?:Error|KeyVaultError).+\{(?:\s.+\s)+\}\s/g, ""); + - from: models_serde.go + where: $ + transform: return $.replace(/(?:\/\/.*\s)+func \(\w \*?(?:Error|KeyVaultError)\).*\{\s(?:.+\s)+\}\s/g, ""); + + # delete the Attributes model defined in common.json (it's used only with allOf) + - from: models.go + where: $ + transform: return $.replace(/(?:\/\/.*\s)+type Attributes.+\{(?:\s.+\s)+\}\s/g, ""); + - from: models_serde.go + where: $ + transform: return $.replace(/(?:\/\/.*\s)+func \(a \*?Attributes\).*\{\s(?:.+\s)+\}\s/g, ""); + + # delete the version path param check (version == "" is legal for Key Vault but indescribable by OpenAPI) + - from: client.go + where: $ + transform: return $.replace(/\sif secretVersion == "" \{\s+.+secretVersion cannot be empty"\)\s+\}\s/g, ""); + + # delete client name prefix from method options and response types + - from: + - client.go + - models.go + - response_types.go + where: $ + transform: return $.replace(/Client(\w+)((?:Options|Response))/g, "$1$2"); + + # make secret IDs a convenience type so we can add parsing methods + - from: models.go + where: $ + transform: return $.replace(/(\sID \*)string(\s+.*)/g, "$1ID$2") + + # Maxresults -> MaxResults + - from: + - client.go + - models.go + where: $ + transform: return $.replace(/Maxresults/g, "MaxResults") + + # secretName, secretVersion -> name, version + - from: client.go + - where: $ + - transform: return $.replace(/secretName/g, "name").replace(/secretVersion/g, "version") +``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/build.go new file mode 100644 index 000000000..d6e487f2c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/build.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +//go:generate autorest ./autorest.md +//go:generate gofmt -w . + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azsecrets diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/ci.yml new file mode 100644 index 000000000..3e196e0c8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/ci.yml @@ -0,0 +1,29 @@ + +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/keyvault/azsecrets + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/keyvault/azsecrets + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'keyvault/azsecrets' + RunLiveTests: true diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/client.go new file mode 100644 index 000000000..fdfbabf96 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/client.go @@ -0,0 +1,650 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// Client contains the methods for the Client group. +// Don't use this type directly, use a constructor function instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// BackupSecret - Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will +// be downloaded. This operation requires the secrets/backup permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - options - BackupSecretOptions contains the optional parameters for the Client.BackupSecret method. +func (client *Client) BackupSecret(ctx context.Context, name string, options *BackupSecretOptions) (BackupSecretResponse, error) { + req, err := client.backupSecretCreateRequest(ctx, name, options) + if err != nil { + return BackupSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BackupSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return BackupSecretResponse{}, runtime.NewResponseError(resp) + } + return client.backupSecretHandleResponse(resp) +} + +// backupSecretCreateRequest creates the BackupSecret request. +func (client *Client) backupSecretCreateRequest(ctx context.Context, name string, options *BackupSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}/backup" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// backupSecretHandleResponse handles the BackupSecret response. +func (client *Client) backupSecretHandleResponse(resp *http.Response) (BackupSecretResponse, error) { + result := BackupSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BackupSecretResult); err != nil { + return BackupSecretResponse{}, err + } + return result, nil +} + +// DeleteSecret - The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual +// version of a secret. This operation requires the secrets/delete permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - options - DeleteSecretOptions contains the optional parameters for the Client.DeleteSecret method. +func (client *Client) DeleteSecret(ctx context.Context, name string, options *DeleteSecretOptions) (DeleteSecretResponse, error) { + req, err := client.deleteSecretCreateRequest(ctx, name, options) + if err != nil { + return DeleteSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return DeleteSecretResponse{}, runtime.NewResponseError(resp) + } + return client.deleteSecretHandleResponse(resp) +} + +// deleteSecretCreateRequest creates the DeleteSecret request. +func (client *Client) deleteSecretCreateRequest(ctx context.Context, name string, options *DeleteSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// deleteSecretHandleResponse handles the DeleteSecret response. +func (client *Client) deleteSecretHandleResponse(resp *http.Response) (DeleteSecretResponse, error) { + result := DeleteSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedSecretBundle); err != nil { + return DeleteSecretResponse{}, err + } + return result, nil +} + +// GetDeletedSecret - The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This +// operation requires the secrets/get permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - options - GetDeletedSecretOptions contains the optional parameters for the Client.GetDeletedSecret method. +func (client *Client) GetDeletedSecret(ctx context.Context, name string, options *GetDeletedSecretOptions) (GetDeletedSecretResponse, error) { + req, err := client.getDeletedSecretCreateRequest(ctx, name, options) + if err != nil { + return GetDeletedSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetDeletedSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return GetDeletedSecretResponse{}, runtime.NewResponseError(resp) + } + return client.getDeletedSecretHandleResponse(resp) +} + +// getDeletedSecretCreateRequest creates the GetDeletedSecret request. +func (client *Client) getDeletedSecretCreateRequest(ctx context.Context, name string, options *GetDeletedSecretOptions) (*policy.Request, error) { + urlPath := "/deletedsecrets/{secret-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedSecretHandleResponse handles the GetDeletedSecret response. +func (client *Client) getDeletedSecretHandleResponse(resp *http.Response) (GetDeletedSecretResponse, error) { + result := GetDeletedSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedSecretBundle); err != nil { + return GetDeletedSecretResponse{}, err + } + return result, nil +} + +// GetSecret - The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get +// permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - version - The version of the secret. This URI fragment is optional. If not specified, the latest version of the secret +// is returned. +// - options - GetSecretOptions contains the optional parameters for the Client.GetSecret method. +func (client *Client) GetSecret(ctx context.Context, name string, version string, options *GetSecretOptions) (GetSecretResponse, error) { + req, err := client.getSecretCreateRequest(ctx, name, version, options) + if err != nil { + return GetSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return GetSecretResponse{}, runtime.NewResponseError(resp) + } + return client.getSecretHandleResponse(resp) +} + +// getSecretCreateRequest creates the GetSecret request. +func (client *Client) getSecretCreateRequest(ctx context.Context, name string, version string, options *GetSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}/{secret-version}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + urlPath = strings.ReplaceAll(urlPath, "{secret-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getSecretHandleResponse handles the GetSecret response. +func (client *Client) getSecretHandleResponse(resp *http.Response) (GetSecretResponse, error) { + result := GetSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretBundle); err != nil { + return GetSecretResponse{}, err + } + return result, nil +} + +// NewListDeletedSecretsPager - The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled +// for soft-delete. This operation requires the secrets/list permission. +// +// Generated from API version 7.4 +// - options - ListDeletedSecretsOptions contains the optional parameters for the Client.NewListDeletedSecretsPager method. +func (client *Client) NewListDeletedSecretsPager(options *ListDeletedSecretsOptions) *runtime.Pager[ListDeletedSecretsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListDeletedSecretsResponse]{ + More: func(page ListDeletedSecretsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListDeletedSecretsResponse) (ListDeletedSecretsResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listDeletedSecretsCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ListDeletedSecretsResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ListDeletedSecretsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ListDeletedSecretsResponse{}, runtime.NewResponseError(resp) + } + return client.listDeletedSecretsHandleResponse(resp) + }, + }) +} + +// listDeletedSecretsCreateRequest creates the ListDeletedSecrets request. +func (client *Client) listDeletedSecretsCreateRequest(ctx context.Context, options *ListDeletedSecretsOptions) (*policy.Request, error) { + urlPath := "/deletedsecrets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listDeletedSecretsHandleResponse handles the ListDeletedSecrets response. +func (client *Client) listDeletedSecretsHandleResponse(resp *http.Response) (ListDeletedSecretsResponse, error) { + result := ListDeletedSecretsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedSecretListResult); err != nil { + return ListDeletedSecretsResponse{}, err + } + return result, nil +} + +// NewListSecretVersionsPager - The full secret identifier and attributes are provided in the response. No values are returned +// for the secrets. This operations requires the secrets/list permission. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - options - ListSecretVersionsOptions contains the optional parameters for the Client.NewListSecretVersionsPager method. +func (client *Client) NewListSecretVersionsPager(name string, options *ListSecretVersionsOptions) *runtime.Pager[ListSecretVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListSecretVersionsResponse]{ + More: func(page ListSecretVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListSecretVersionsResponse) (ListSecretVersionsResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listSecretVersionsCreateRequest(ctx, name, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ListSecretVersionsResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ListSecretVersionsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ListSecretVersionsResponse{}, runtime.NewResponseError(resp) + } + return client.listSecretVersionsHandleResponse(resp) + }, + }) +} + +// listSecretVersionsCreateRequest creates the ListSecretVersions request. +func (client *Client) listSecretVersionsCreateRequest(ctx context.Context, name string, options *ListSecretVersionsOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}/versions" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSecretVersionsHandleResponse handles the ListSecretVersions response. +func (client *Client) listSecretVersionsHandleResponse(resp *http.Response) (ListSecretVersionsResponse, error) { + result := ListSecretVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretListResult); err != nil { + return ListSecretVersionsResponse{}, err + } + return result, nil +} + +// NewListSecretsPager - The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier +// and its attributes are provided in the response. Individual secret versions are not listed in the +// response. This operation requires the secrets/list permission. +// +// Generated from API version 7.4 +// - options - ListSecretsOptions contains the optional parameters for the Client.NewListSecretsPager method. +func (client *Client) NewListSecretsPager(options *ListSecretsOptions) *runtime.Pager[ListSecretsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListSecretsResponse]{ + More: func(page ListSecretsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListSecretsResponse) (ListSecretsResponse, error) { + var req *policy.Request + var err error + if page == nil { + req, err = client.listSecretsCreateRequest(ctx, options) + } else { + req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink) + } + if err != nil { + return ListSecretsResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ListSecretsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ListSecretsResponse{}, runtime.NewResponseError(resp) + } + return client.listSecretsHandleResponse(resp) + }, + }) +} + +// listSecretsCreateRequest creates the ListSecrets request. +func (client *Client) listSecretsCreateRequest(ctx context.Context, options *ListSecretsOptions) (*policy.Request, error) { + urlPath := "/secrets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.MaxResults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.MaxResults), 10)) + } + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSecretsHandleResponse handles the ListSecrets response. +func (client *Client) listSecretsHandleResponse(resp *http.Response) (ListSecretsResponse, error) { + result := ListSecretsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretListResult); err != nil { + return ListSecretsResponse{}, err + } + return result, nil +} + +// PurgeDeletedSecret - The purge deleted secret operation removes the secret permanently, without the possibility of recovery. +// This operation can only be enabled on a soft-delete enabled vault. This operation requires the +// secrets/purge permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - options - PurgeDeletedSecretOptions contains the optional parameters for the Client.PurgeDeletedSecret method. +func (client *Client) PurgeDeletedSecret(ctx context.Context, name string, options *PurgeDeletedSecretOptions) (PurgeDeletedSecretResponse, error) { + req, err := client.purgeDeletedSecretCreateRequest(ctx, name, options) + if err != nil { + return PurgeDeletedSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PurgeDeletedSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusNoContent) { + return PurgeDeletedSecretResponse{}, runtime.NewResponseError(resp) + } + return PurgeDeletedSecretResponse{}, nil +} + +// purgeDeletedSecretCreateRequest creates the PurgeDeletedSecret request. +func (client *Client) purgeDeletedSecretCreateRequest(ctx context.Context, name string, options *PurgeDeletedSecretOptions) (*policy.Request, error) { + urlPath := "/deletedsecrets/{secret-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// RecoverDeletedSecret - Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete +// enabled vault. This operation requires the secrets/recover permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the deleted secret. +// - options - RecoverDeletedSecretOptions contains the optional parameters for the Client.RecoverDeletedSecret method. +func (client *Client) RecoverDeletedSecret(ctx context.Context, name string, options *RecoverDeletedSecretOptions) (RecoverDeletedSecretResponse, error) { + req, err := client.recoverDeletedSecretCreateRequest(ctx, name, options) + if err != nil { + return RecoverDeletedSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RecoverDeletedSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return RecoverDeletedSecretResponse{}, runtime.NewResponseError(resp) + } + return client.recoverDeletedSecretHandleResponse(resp) +} + +// recoverDeletedSecretCreateRequest creates the RecoverDeletedSecret request. +func (client *Client) recoverDeletedSecretCreateRequest(ctx context.Context, name string, options *RecoverDeletedSecretOptions) (*policy.Request, error) { + urlPath := "/deletedsecrets/{secret-name}/recover" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// recoverDeletedSecretHandleResponse handles the RecoverDeletedSecret response. +func (client *Client) recoverDeletedSecretHandleResponse(resp *http.Response) (RecoverDeletedSecretResponse, error) { + result := RecoverDeletedSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretBundle); err != nil { + return RecoverDeletedSecretResponse{}, err + } + return result, nil +} + +// RestoreSecret - Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore +// permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - parameters - The parameters to restore the secret. +// - options - RestoreSecretOptions contains the optional parameters for the Client.RestoreSecret method. +func (client *Client) RestoreSecret(ctx context.Context, parameters RestoreSecretParameters, options *RestoreSecretOptions) (RestoreSecretResponse, error) { + req, err := client.restoreSecretCreateRequest(ctx, parameters, options) + if err != nil { + return RestoreSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestoreSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return RestoreSecretResponse{}, runtime.NewResponseError(resp) + } + return client.restoreSecretHandleResponse(resp) +} + +// restoreSecretCreateRequest creates the RestoreSecret request. +func (client *Client) restoreSecretCreateRequest(ctx context.Context, parameters RestoreSecretParameters, options *RestoreSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/restore" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, runtime.MarshalAsJSON(req, parameters) +} + +// restoreSecretHandleResponse handles the RestoreSecret response. +func (client *Client) restoreSecretHandleResponse(resp *http.Response) (RestoreSecretResponse, error) { + result := RestoreSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretBundle); err != nil { + return RestoreSecretResponse{}, err + } + return result, nil +} + +// SetSecret - The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault +// creates a new version of that secret. This operation requires the secrets/set permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. The value you provide may be copied globally for the purpose of running the service. +// The value provided should not include personally identifiable or sensitive information. +// - parameters - The parameters for setting the secret. +// - options - SetSecretOptions contains the optional parameters for the Client.SetSecret method. +func (client *Client) SetSecret(ctx context.Context, name string, parameters SetSecretParameters, options *SetSecretOptions) (SetSecretResponse, error) { + req, err := client.setSecretCreateRequest(ctx, name, parameters, options) + if err != nil { + return SetSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SetSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SetSecretResponse{}, runtime.NewResponseError(resp) + } + return client.setSecretHandleResponse(resp) +} + +// setSecretCreateRequest creates the SetSecret request. +func (client *Client) setSecretCreateRequest(ctx context.Context, name string, parameters SetSecretParameters, options *SetSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, runtime.MarshalAsJSON(req, parameters) +} + +// setSecretHandleResponse handles the SetSecret response. +func (client *Client) setSecretHandleResponse(resp *http.Response) (SetSecretResponse, error) { + result := SetSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretBundle); err != nil { + return SetSecretResponse{}, err + } + return result, nil +} + +// UpdateSecret - The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not +// specified in the request are left unchanged. The value of a secret itself cannot be changed. +// This operation requires the secrets/set permission. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 7.4 +// - name - The name of the secret. +// - version - The version of the secret. +// - parameters - The parameters for update secret operation. +// - options - UpdateSecretOptions contains the optional parameters for the Client.UpdateSecret method. +func (client *Client) UpdateSecret(ctx context.Context, name string, version string, parameters UpdateSecretParameters, options *UpdateSecretOptions) (UpdateSecretResponse, error) { + req, err := client.updateSecretCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return UpdateSecretResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdateSecretResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return UpdateSecretResponse{}, runtime.NewResponseError(resp) + } + return client.updateSecretHandleResponse(resp) +} + +// updateSecretCreateRequest creates the UpdateSecret request. +func (client *Client) updateSecretCreateRequest(ctx context.Context, name string, version string, parameters UpdateSecretParameters, options *UpdateSecretOptions) (*policy.Request, error) { + urlPath := "/secrets/{secret-name}/{secret-version}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{secret-name}", url.PathEscape(name)) + urlPath = strings.ReplaceAll(urlPath, "{secret-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.4") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateSecretHandleResponse handles the UpdateSecret response. +func (client *Client) updateSecretHandleResponse(resp *http.Response) (UpdateSecretResponse, error) { + result := UpdateSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecretBundle); err != nil { + return UpdateSecretResponse{}, err + } + return result, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/constants.go new file mode 100644 index 000000000..d897d67a1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/constants.go @@ -0,0 +1,63 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +// DeletionRecoveryLevel - Reflects the deletion recovery level currently in effect for secrets in the current vault. If it +// contains 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the +// system can purge the secret, at the end of the retention interval. +type DeletionRecoveryLevel string + +const ( + // DeletionRecoveryLevelCustomizedRecoverable - Denotes a vault state in which deletion is recoverable without the possibility + // for immediate and permanent deletion (i.e. purge when 7<= SoftDeleteRetentionInDays < 90).This level guarantees the recoverability + // of the deleted entity during the retention interval and while the subscription is still available. + DeletionRecoveryLevelCustomizedRecoverable DeletionRecoveryLevel = "CustomizedRecoverable" + // DeletionRecoveryLevelCustomizedRecoverableProtectedSubscription - Denotes a vault and subscription state in which deletion + // is recoverable, immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription itself cannot + // be permanently canceled when 7<= SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the deleted + // entity during the retention interval, and also reflects the fact that the subscription itself cannot be cancelled. + DeletionRecoveryLevelCustomizedRecoverableProtectedSubscription DeletionRecoveryLevel = "CustomizedRecoverable+ProtectedSubscription" + // DeletionRecoveryLevelCustomizedRecoverablePurgeable - Denotes a vault state in which deletion is recoverable, and which + // also permits immediate and permanent deletion (i.e. purge when 7<= SoftDeleteRetentionInDays < 90). This level guarantees + // the recoverability of the deleted entity during the retention interval, unless a Purge operation is requested, or the subscription + // is cancelled. + DeletionRecoveryLevelCustomizedRecoverablePurgeable DeletionRecoveryLevel = "CustomizedRecoverable+Purgeable" + // DeletionRecoveryLevelPurgeable - Denotes a vault state in which deletion is an irreversible operation, without the possibility + // for recovery. This level corresponds to no protection being available against a Delete operation; the data is irretrievably + // lost upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.) + DeletionRecoveryLevelPurgeable DeletionRecoveryLevel = "Purgeable" + // DeletionRecoveryLevelRecoverable - Denotes a vault state in which deletion is recoverable without the possibility for immediate + // and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the retention + // interval(90 days) and while the subscription is still available. System wil permanently delete it after 90 days, if not + // recovered + DeletionRecoveryLevelRecoverable DeletionRecoveryLevel = "Recoverable" + // DeletionRecoveryLevelRecoverableProtectedSubscription - Denotes a vault and subscription state in which deletion is recoverable + // within retention interval (90 days), immediate and permanent deletion (i.e. purge) is not permitted, and in which the subscription + // itself cannot be permanently canceled. System wil permanently delete it after 90 days, if not recovered + DeletionRecoveryLevelRecoverableProtectedSubscription DeletionRecoveryLevel = "Recoverable+ProtectedSubscription" + // DeletionRecoveryLevelRecoverablePurgeable - Denotes a vault state in which deletion is recoverable, and which also permits + // immediate and permanent deletion (i.e. purge). This level guarantees the recoverability of the deleted entity during the + // retention interval (90 days), unless a Purge operation is requested, or the subscription is cancelled. System wil permanently + // delete it after 90 days, if not recovered + DeletionRecoveryLevelRecoverablePurgeable DeletionRecoveryLevel = "Recoverable+Purgeable" +) + +// PossibleDeletionRecoveryLevelValues returns the possible values for the DeletionRecoveryLevel const type. +func PossibleDeletionRecoveryLevelValues() []DeletionRecoveryLevel { + return []DeletionRecoveryLevel{ + DeletionRecoveryLevelCustomizedRecoverable, + DeletionRecoveryLevelCustomizedRecoverableProtectedSubscription, + DeletionRecoveryLevelCustomizedRecoverablePurgeable, + DeletionRecoveryLevelPurgeable, + DeletionRecoveryLevelRecoverable, + DeletionRecoveryLevelRecoverableProtectedSubscription, + DeletionRecoveryLevelRecoverablePurgeable, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/custom_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/custom_client.go new file mode 100644 index 000000000..04500bd08 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/custom_client.go @@ -0,0 +1,63 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azsecrets + +// this file contains handwritten additions to the generated code + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal" +) + +// ClientOptions contains optional settings for Client. +type ClientOptions struct { + azcore.ClientOptions + + // DisableChallengeResourceVerification controls whether the policy requires the + // authentication challenge resource to match the Key Vault or Managed HSM domain. + // See https://aka.ms/azsdk/blog/vault-uri for more information. + DisableChallengeResourceVerification bool +} + +// NewClient creates a client that accesses a Key Vault's secrets. You should validate that +// vaultURL references a valid Key Vault. See https://aka.ms/azsdk/blog/vault-uri for details. +func NewClient(vaultURL string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + authPolicy := internal.NewKeyVaultChallengePolicy( + credential, + &internal.KeyVaultChallengePolicyOptions{ + DisableChallengeResourceVerification: options.DisableChallengeResourceVerification, + }, + ) + azcoreClient, err := azcore.NewClient("azsecrets.Client", version, runtime.PipelineOptions{PerRetry: []policy.Policy{authPolicy}}, &options.ClientOptions) + if err != nil { + return nil, err + } + return &Client{endpoint: vaultURL, internal: azcoreClient}, nil +} + +// ID is a secret's unique ID, containing its name and version. +type ID string + +// Name of the secret. +func (i *ID) Name() string { + _, name, _ := internal.ParseID((*string)(i)) + return *name +} + +// Version of the secret. This returns an empty string when the ID contains no version. +func (i *ID) Version() string { + _, _, version := internal.ParseID((*string)(i)) + if version == nil { + return "" + } + return *version +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models.go new file mode 100644 index 000000000..87be9ab52 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models.go @@ -0,0 +1,268 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +import "time" + +// BackupSecretResult - The backup secret result, containing the backup blob. +type BackupSecretResult struct { + // READ-ONLY; The backup blob containing the backed up secret. + Value []byte `json:"value,omitempty" azure:"ro"` +} + +// BackupSecretOptions contains the optional parameters for the Client.BackupSecret method. +type BackupSecretOptions struct { + // placeholder for future optional parameters +} + +// DeleteSecretOptions contains the optional parameters for the Client.DeleteSecret method. +type DeleteSecretOptions struct { + // placeholder for future optional parameters +} + +// GetDeletedSecretOptions contains the optional parameters for the Client.GetDeletedSecret method. +type GetDeletedSecretOptions struct { + // placeholder for future optional parameters +} + +// GetSecretOptions contains the optional parameters for the Client.GetSecret method. +type GetSecretOptions struct { + // placeholder for future optional parameters +} + +// ListDeletedSecretsOptions contains the optional parameters for the Client.NewListDeletedSecretsPager method. +type ListDeletedSecretsOptions struct { + // Maximum number of results to return in a page. If not specified the service will return up to 25 results. + MaxResults *int32 +} + +// ListSecretVersionsOptions contains the optional parameters for the Client.NewListSecretVersionsPager method. +type ListSecretVersionsOptions struct { + // Maximum number of results to return in a page. If not specified, the service will return up to 25 results. + MaxResults *int32 +} + +// ListSecretsOptions contains the optional parameters for the Client.NewListSecretsPager method. +type ListSecretsOptions struct { + // Maximum number of results to return in a page. If not specified, the service will return up to 25 results. + MaxResults *int32 +} + +// PurgeDeletedSecretOptions contains the optional parameters for the Client.PurgeDeletedSecret method. +type PurgeDeletedSecretOptions struct { + // placeholder for future optional parameters +} + +// RecoverDeletedSecretOptions contains the optional parameters for the Client.RecoverDeletedSecret method. +type RecoverDeletedSecretOptions struct { + // placeholder for future optional parameters +} + +// RestoreSecretOptions contains the optional parameters for the Client.RestoreSecret method. +type RestoreSecretOptions struct { + // placeholder for future optional parameters +} + +// SetSecretOptions contains the optional parameters for the Client.SetSecret method. +type SetSecretOptions struct { + // placeholder for future optional parameters +} + +// UpdateSecretOptions contains the optional parameters for the Client.UpdateSecret method. +type UpdateSecretOptions struct { + // placeholder for future optional parameters +} + +// DeletedSecretBundle - A Deleted Secret consisting of its previous id, attributes and its tags, as well as information on +// when it will be purged. +type DeletedSecretBundle struct { + // The secret management attributes. + Attributes *SecretAttributes `json:"attributes,omitempty"` + + // The content type of the secret. + ContentType *string `json:"contentType,omitempty"` + + // The secret id. + ID *ID `json:"id,omitempty"` + + // The url of the recovery object, used to identify and recover the deleted secret. + RecoveryID *string `json:"recoveryId,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` + + // The secret value. + Value *string `json:"value,omitempty"` + + // READ-ONLY; The time when the secret was deleted, in UTC + DeletedDate *time.Time `json:"deletedDate,omitempty" azure:"ro"` + + // READ-ONLY; If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV + // certificate. + Kid *string `json:"kid,omitempty" azure:"ro"` + + // READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed + // will be true. + Managed *bool `json:"managed,omitempty" azure:"ro"` + + // READ-ONLY; The time when the secret is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time `json:"scheduledPurgeDate,omitempty" azure:"ro"` +} + +// DeletedSecretItem - The deleted secret item containing metadata about the deleted secret. +type DeletedSecretItem struct { + // The secret management attributes. + Attributes *SecretAttributes `json:"attributes,omitempty"` + + // Type of the secret value such as a password. + ContentType *string `json:"contentType,omitempty"` + + // Secret identifier. + ID *ID `json:"id,omitempty"` + + // The url of the recovery object, used to identify and recover the deleted secret. + RecoveryID *string `json:"recoveryId,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; The time when the secret was deleted, in UTC + DeletedDate *time.Time `json:"deletedDate,omitempty" azure:"ro"` + + // READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed + // will be true. + Managed *bool `json:"managed,omitempty" azure:"ro"` + + // READ-ONLY; The time when the secret is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time `json:"scheduledPurgeDate,omitempty" azure:"ro"` +} + +// DeletedSecretListResult - The deleted secret list result +type DeletedSecretListResult struct { + // READ-ONLY; The URL to get the next set of deleted secrets. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A response message containing a list of the deleted secrets in the vault along with a link to the next page + // of deleted secrets + Value []*DeletedSecretItem `json:"value,omitempty" azure:"ro"` +} + +// RestoreSecretParameters - The secret restore parameters. +type RestoreSecretParameters struct { + // REQUIRED; The backup blob associated with a secret bundle. + SecretBundleBackup []byte `json:"value,omitempty"` +} + +// SecretAttributes - The secret management attributes. +type SecretAttributes struct { + // Determines whether the object is enabled. + Enabled *bool `json:"enabled,omitempty"` + + // Expiry date in UTC. + Expires *time.Time `json:"exp,omitempty"` + + // Not before date in UTC. + NotBefore *time.Time `json:"nbf,omitempty"` + + // READ-ONLY; Creation time in UTC. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + RecoverableDays *int32 `json:"recoverableDays,omitempty" azure:"ro"` + + // READ-ONLY; Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains 'Purgeable', + // the secret can be permanently deleted by a privileged user; otherwise, only the + // system can purge the secret, at the end of the retention interval. + RecoveryLevel *DeletionRecoveryLevel `json:"recoveryLevel,omitempty" azure:"ro"` + + // READ-ONLY; Last updated time in UTC. + Updated *time.Time `json:"updated,omitempty" azure:"ro"` +} + +// SecretBundle - A secret consisting of a value, id and its attributes. +type SecretBundle struct { + // The secret management attributes. + Attributes *SecretAttributes `json:"attributes,omitempty"` + + // The content type of the secret. + ContentType *string `json:"contentType,omitempty"` + + // The secret id. + ID *ID `json:"id,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` + + // The secret value. + Value *string `json:"value,omitempty"` + + // READ-ONLY; If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV + // certificate. + Kid *string `json:"kid,omitempty" azure:"ro"` + + // READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed + // will be true. + Managed *bool `json:"managed,omitempty" azure:"ro"` +} + +// SecretItem - The secret item containing secret metadata. +type SecretItem struct { + // The secret management attributes. + Attributes *SecretAttributes `json:"attributes,omitempty"` + + // Type of the secret value such as a password. + ContentType *string `json:"contentType,omitempty"` + + // Secret identifier. + ID *ID `json:"id,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed + // will be true. + Managed *bool `json:"managed,omitempty" azure:"ro"` +} + +// SecretListResult - The secret list result. +type SecretListResult struct { + // READ-ONLY; The URL to get the next set of secrets. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A response message containing a list of secrets in the key vault along with a link to the next page of secrets. + Value []*SecretItem `json:"value,omitempty" azure:"ro"` +} + +// SetSecretParameters - The secret set parameters. +type SetSecretParameters struct { + // REQUIRED; The value of the secret. + Value *string `json:"value,omitempty"` + + // Type of the secret value such as a password. + ContentType *string `json:"contentType,omitempty"` + + // The secret management attributes. + SecretAttributes *SecretAttributes `json:"attributes,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` +} + +// UpdateSecretParameters - The secret update parameters. +type UpdateSecretParameters struct { + // Type of the secret value such as a password. + ContentType *string `json:"contentType,omitempty"` + + // The secret management attributes. + SecretAttributes *SecretAttributes `json:"attributes,omitempty"` + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models_serde.go new file mode 100644 index 000000000..72d554127 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/models_serde.go @@ -0,0 +1,501 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type BackupSecretResult. +func (b BackupSecretResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, runtime.Base64URLFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupSecretResult. +func (b *BackupSecretResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedSecretBundle. +func (d DeletedSecretBundle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populate(objectMap, "contentType", d.ContentType) + populateTimeUnix(objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "id", d.ID) + populate(objectMap, "kid", d.Kid) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populateTimeUnix(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedSecretBundle. +func (d *DeletedSecretBundle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &d.ContentType) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTimeUnix(val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &d.Kid) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeUnix(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedSecretItem. +func (d DeletedSecretItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populate(objectMap, "contentType", d.ContentType) + populateTimeUnix(objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "id", d.ID) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populateTimeUnix(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedSecretItem. +func (d *DeletedSecretItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &d.ContentType) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTimeUnix(val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeUnix(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedSecretListResult. +func (d DeletedSecretListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedSecretListResult. +func (d *DeletedSecretListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreSecretParameters. +func (r RestoreSecretParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", r.SecretBundleBackup, runtime.Base64URLFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreSecretParameters. +func (r *RestoreSecretParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = runtime.DecodeByteArray(string(val), &r.SecretBundleBackup, runtime.Base64URLFormat) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretAttributes. +func (s SecretAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeUnix(objectMap, "created", s.Created) + populate(objectMap, "enabled", s.Enabled) + populateTimeUnix(objectMap, "exp", s.Expires) + populateTimeUnix(objectMap, "nbf", s.NotBefore) + populate(objectMap, "recoverableDays", s.RecoverableDays) + populate(objectMap, "recoveryLevel", s.RecoveryLevel) + populateTimeUnix(objectMap, "updated", s.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretAttributes. +func (s *SecretAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulateTimeUnix(val, "Created", &s.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &s.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulateTimeUnix(val, "Expires", &s.Expires) + delete(rawMsg, key) + case "nbf": + err = unpopulateTimeUnix(val, "NotBefore", &s.NotBefore) + delete(rawMsg, key) + case "recoverableDays": + err = unpopulate(val, "RecoverableDays", &s.RecoverableDays) + delete(rawMsg, key) + case "recoveryLevel": + err = unpopulate(val, "RecoveryLevel", &s.RecoveryLevel) + delete(rawMsg, key) + case "updated": + err = unpopulateTimeUnix(val, "Updated", &s.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretBundle. +func (s SecretBundle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", s.Attributes) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "id", s.ID) + populate(objectMap, "kid", s.Kid) + populate(objectMap, "managed", s.Managed) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretBundle. +func (s *SecretBundle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &s.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &s.Kid) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &s.Managed) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretItem. +func (s SecretItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", s.Attributes) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "id", s.ID) + populate(objectMap, "managed", s.Managed) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretItem. +func (s *SecretItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &s.Attributes) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &s.Managed) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretListResult. +func (s SecretListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretListResult. +func (s *SecretListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SetSecretParameters. +func (s SetSecretParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "attributes", s.SecretAttributes) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SetSecretParameters. +func (s *SetSecretParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &s.ContentType) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "SecretAttributes", &s.SecretAttributes) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateSecretParameters. +func (u UpdateSecretParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", u.ContentType) + populate(objectMap, "attributes", u.SecretAttributes) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateSecretParameters. +func (u *UpdateSecretParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &u.ContentType) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "SecretAttributes", &u.SecretAttributes) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &u.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateByteArray(m map[string]any, k string, b []byte, f runtime.Base64Encoding) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = runtime.EncodeByteArray(b, f) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/response_types.go new file mode 100644 index 000000000..517acaabb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/response_types.go @@ -0,0 +1,70 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +// BackupSecretResponse contains the response from method Client.BackupSecret. +type BackupSecretResponse struct { + BackupSecretResult +} + +// DeleteSecretResponse contains the response from method Client.DeleteSecret. +type DeleteSecretResponse struct { + DeletedSecretBundle +} + +// GetDeletedSecretResponse contains the response from method Client.GetDeletedSecret. +type GetDeletedSecretResponse struct { + DeletedSecretBundle +} + +// GetSecretResponse contains the response from method Client.GetSecret. +type GetSecretResponse struct { + SecretBundle +} + +// ListDeletedSecretsResponse contains the response from method Client.NewListDeletedSecretsPager. +type ListDeletedSecretsResponse struct { + DeletedSecretListResult +} + +// ListSecretVersionsResponse contains the response from method Client.NewListSecretVersionsPager. +type ListSecretVersionsResponse struct { + SecretListResult +} + +// ListSecretsResponse contains the response from method Client.NewListSecretsPager. +type ListSecretsResponse struct { + SecretListResult +} + +// PurgeDeletedSecretResponse contains the response from method Client.PurgeDeletedSecret. +type PurgeDeletedSecretResponse struct { + // placeholder for future response values +} + +// RecoverDeletedSecretResponse contains the response from method Client.RecoverDeletedSecret. +type RecoverDeletedSecretResponse struct { + SecretBundle +} + +// RestoreSecretResponse contains the response from method Client.RestoreSecret. +type RestoreSecretResponse struct { + SecretBundle +} + +// SetSecretResponse contains the response from method Client.SetSecret. +type SetSecretResponse struct { + SecretBundle +} + +// UpdateSecretResponse contains the response from method Client.UpdateSecret. +type UpdateSecretResponse struct { + SecretBundle +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/test-resources.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/test-resources.json new file mode 100644 index 000000000..20f726f33 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/test-resources.json @@ -0,0 +1,331 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "baseName": { + "type": "string", + "defaultValue": "[resourceGroup().name]", + "metadata": { + "description": "The base resource name." + } + }, + "tenantId": { + "type": "string", + "defaultValue": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "metadata": { + "description": "The tenant ID to which the application and resources belong." + } + }, + "testApplicationOid": { + "type": "string", + "metadata": { + "description": "The client OID to grant access to test resources." + } + }, + "provisionerApplicationOid": { + "type": "string", + "metadata": { + "description": "The provisioner OID to grant access to test resources." + } + }, + "location": { + "type": "string", + "defaultValue": "[resourceGroup().location]", + "metadata": { + "description": "The location of the resource. By default, this is the same as the resource group." + } + }, + "hsmLocation": { + "type": "string", + "defaultValue": "southcentralus", + "allowedValues": [ + "australiacentral", + "canadacentral", + "centralus", + "eastasia", + "eastus2", + "koreacentral", + "northeurope", + "southafricanorth", + "southcentralus", + "southeastasia", + "switzerlandnorth", + "uksouth", + "westeurope", + "westus" + ], + "metadata": { + "description": "The location of the Managed HSM. By default, this is 'southcentralus'." + } + }, + "enableHsm": { + "type": "bool", + "defaultValue": false, + "metadata": { + "description": "Whether to enable deployment of Managed HSM. The default is false." + } + }, + "keyVaultSku": { + "type": "string", + "defaultValue": "premium", + "metadata": { + "description": "Key Vault SKU to deploy. The default is 'premium'" + } + }, + "attestationImage": { + "type": "string", + "defaultValue": "keyvault-mock-attestation:latest", + "metadata": { + "description": "The container image name and tag to use for the attestation mock service." + } + } + }, + "variables": { + "attestationFarm": "[concat(parameters('baseName'), 'farm')]", + "attestationSite": "[concat(parameters('baseName'), 'site')]", + "attestationUri": "[concat('DOCKER|azsdkengsys.azurecr.io/', parameters('attestationImage'))]", + "kvApiVersion": "2019-09-01", + "kvName": "[parameters('baseName')]", + "hsmApiVersion": "2021-04-01-preview", + "hsmName": "[concat(parameters('baseName'), 'hsm')]", + "mgmtApiVersion": "2019-04-01", + "blobContainerName": "backup", + "primaryAccountName": "[concat(parameters('baseName'), 'prim')]", + "encryption": { + "services": { + "blob": { + "enabled": true + } + }, + "keySource": "Microsoft.Storage" + }, + "networkAcls": { + "bypass": "AzureServices", + "virtualNetworkRules": [], + "ipRules": [], + "defaultAction": "Allow" + } + }, + "resources": [ + { + "type": "Microsoft.KeyVault/vaults", + "apiVersion": "[variables('kvApiVersion')]", + "name": "[variables('kvName')]", + "location": "[parameters('location')]", + "properties": { + "sku": { + "family": "A", + "name": "[parameters('keyVaultSku')]" + }, + "tenantId": "[parameters('tenantId')]", + "accessPolicies": [ + { + "tenantId": "[parameters('tenantId')]", + "objectId": "[parameters('testApplicationOid')]", + "permissions": { + "keys": [ + "backup", + "create", + "decrypt", + "delete", + "encrypt", + "get", + "import", + "list", + "purge", + "recover", + "release", + "restore", + "rotate", + "sign", + "unwrapKey", + "update", + "verify", + "wrapKey" + ], + "secrets": [ + "backup", + "delete", + "get", + "list", + "purge", + "recover", + "restore", + "set" + ], + "certificates": [ + "backup", + "create", + "delete", + "deleteissuers", + "get", + "getissuers", + "import", + "list", + "listissuers", + "managecontacts", + "manageissuers", + "purge", + "recover", + "restore", + "setissuers", + "update" + ] + } + } + ], + "enabledForDeployment": false, + "enabledForDiskEncryption": false, + "enabledForTemplateDeployment": false, + "enableSoftDelete": true, + "softDeleteRetentionInDays": 7 + } + }, + { + "type": "Microsoft.KeyVault/managedHSMs", + "apiVersion": "[variables('hsmApiVersion')]", + "name": "[variables('hsmName')]", + "condition": "[parameters('enableHsm')]", + "location": "[parameters('hsmLocation')]", + "sku": { + "family": "B", + "name": "Standard_B1" + }, + "properties": { + "tenantId": "[parameters('tenantId')]", + "initialAdminObjectIds": "[union(array(parameters('testApplicationOid')), array(parameters('provisionerApplicationOid')))]", + "enablePurgeProtection": false, + "enableSoftDelete": true, + "softDeleteRetentionInDays": 7, + "publicNetworkAccess": "Enabled", + "networkAcls": "[variables('networkAcls')]" + } + }, + { + "type": "Microsoft.Storage/storageAccounts", + "apiVersion": "[variables('mgmtApiVersion')]", + "name": "[variables('primaryAccountName')]", + "location": "[parameters('location')]", + "sku": { + "name": "Standard_RAGRS", + "tier": "Standard" + }, + "kind": "StorageV2", + "properties": { + "networkAcls": "[variables('networkAcls')]", + "supportsHttpsTrafficOnly": true, + "encryption": "[variables('encryption')]", + "accessTier": "Hot" + } + }, + { + "type": "Microsoft.Storage/storageAccounts/blobServices", + "apiVersion": "2019-06-01", + "name": "[concat(variables('primaryAccountName'), '/default')]", + "dependsOn": [ + "[resourceId('Microsoft.Storage/storageAccounts', variables('primaryAccountName'))]" + ], + "sku": { + "name": "Standard_RAGRS", + "tier": "Standard" + }, + "properties": { + "cors": { + "corsRules": [] + }, + "deleteRetentionPolicy": { + "enabled": false + } + } + }, + { + "type": "Microsoft.Storage/storageAccounts/blobServices/containers", + "apiVersion": "2019-06-01", + "name": "[concat(variables('primaryAccountName'), '/default/', variables('blobContainerName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Storage/storageAccounts/blobServices', variables('primaryAccountName'), 'default')]", + "[resourceId('Microsoft.Storage/storageAccounts', variables('primaryAccountName'))]" + ], + "properties": { + "publicAccess": "None" + } + }, + { + + "type": "Microsoft.Web/serverfarms", + "apiVersion": "2020-12-01", + "name": "[variables('attestationFarm')]", + "condition": "[parameters('enableHsm')]", + "location": "[parameters('location')]", + "kind": "linux", + "sku": { + "name": "B1" + }, + "properties": { + "reserved": true + } + }, + { + + "type": "Microsoft.Web/sites", + "apiVersion": "2020-12-01", + "name": "[variables('attestationSite')]", + "condition": "[parameters('enableHsm')]", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms', variables('attestationFarm'))]" + ], + "location": "[parameters('location')]", + "properties": { + "httpsOnly": true, + "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('attestationFarm'))]", + "siteConfig": { + "name": "[variables('attestationSite')]", + "alwaysOn": true, + "linuxFxVersion": "[variables('attestationUri')]", + "appSettings": [ + { + "name": "WEBSITES_ENABLE_APP_SERVICE_STORAGE", + "value": "false" + } + ] + } + } + } + ], + "outputs": { + "AZURE_KEYVAULT_URL": { + "type": "string", + "value": "[reference(variables('kvName')).vaultUri]" + }, + "AZURE_MANAGEDHSM_URL": { + "type": "string", + "condition": "[parameters('enableHsm')]", + "value": "[reference(variables('hsmName')).hsmUri]" + }, + "KEYVAULT_SKU": { + "type": "string", + "value": "[reference(parameters('baseName')).sku.name]" + }, + "CLIENT_OBJECTID": { + "type": "string", + "value": "[parameters('testApplicationOid')]" + }, + "BLOB_STORAGE_ACCOUNT_NAME": { + "type": "string", + "value": "[variables('primaryAccountName')]" + }, + "BLOB_PRIMARY_STORAGE_ACCOUNT_KEY": { + "type": "string", + "value": "[listKeys(variables('primaryAccountName'), variables('mgmtApiVersion')).keys[0].value]" + }, + "BLOB_CONTAINER_NAME" : { + "type": "string", + "value": "[variables('blobContainerName')]" + }, + "AZURE_KEYVAULT_ATTESTATION_URL": { + "type": "string", + "condition": "[parameters('enableHsm')]", + "value": "[format('https://{0}/', reference(variables('attestationSite')).defaultHostName)]" + } + } +} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/time_unix.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/time_unix.go new file mode 100644 index 000000000..ed8ce0f9d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/time_unix.go @@ -0,0 +1,62 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package azsecrets + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "strings" + "time" +) + +type timeUnix time.Time + +func (t timeUnix) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Time(t).Unix()) +} + +func (t *timeUnix) UnmarshalJSON(data []byte) error { + var seconds int64 + if err := json.Unmarshal(data, &seconds); err != nil { + return err + } + *t = timeUnix(time.Unix(seconds, 0)) + return nil +} + +func (t timeUnix) String() string { + return fmt.Sprintf("%d", time.Time(t).Unix()) +} + +func populateTimeUnix(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeUnix)(t) +} + +func unpopulateTimeUnix(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux timeUnix + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/version.go new file mode 100644 index 000000000..885158bcb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets/version.go @@ -0,0 +1,12 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azsecrets + +const ( + moduleName = "azsecrets" + version = "v0.12.0" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/CHANGELOG.md new file mode 100644 index 000000000..95d77dc95 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/CHANGELOG.md @@ -0,0 +1,54 @@ +# Release History + +## 0.7.1 (2022-11-14) + +### Bugs Fixed +* `KeyVaultChallengePolicy` uses incorrect authentication scope when challenge verification is disabled + +## 0.7.0 (2022-09-20) + +### Breaking Changes +* Added `*KeyVaultChallengePolicyOptions` parameter to `NewKeyVaultChallengePolicy` + +## 0.6.0 (2022-09-12) + +### Breaking Changes +* Verify the challenge resource matches the vault domain. See https://aka.ms/azsdk/blog/vault-uri for more information. +* `ParseID()` no longer appends a trailing slash to vault URLs + +## 0.5.0 (2022-05-12) + +### Breaking Changes +* Removed `ExpiringResource` and its dependencies in favor of shared implementation from `internal/temporal`. + +### Other Changes +* Updated to latest versions of `azcore` and `internal`. + +## 0.4.0 (2022-04-22) + +### Breaking Changes +* Updated `ExpiringResource` and its dependent types to use generics. + +### Other Changes +* Remove reference to `TokenRequestOptions.TenantID` as it's been removed and wasn't working anyways. + +## 0.3.0 (2022-04-04) + +### Features Added +* Adds the `ParseKeyvaultID` function to parse an ID into the Key Vault URL, item name, and item version + +### Breaking Changes +* Updates to azcore v0.23.0 + +## 0.2.1 (2022-01-31) + +### Bugs Fixed +* Avoid retries on terminal failures (#16932) + +## 0.2.0 (2022-01-12) + +### Bugs Fixed +* Fixes a bug with Managed HSMs that prevented correctly authorizing requests. + +## 0.1.0 (2021-11-09) +* This is the initial release of the `internal` library for KeyVault diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/LICENSE.txt new file mode 100644 index 000000000..d1ca00f20 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/LICENSE.txt @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/README.md new file mode 100644 index 000000000..bd4826705 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/README.md @@ -0,0 +1,23 @@ +# Key Vault Internal Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal) + +This module contains shared code for all the Key Vault SDKs, mainly the challenge authentication policy. + +## Contributing +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/challenge_policy.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/challenge_policy.go new file mode 100644 index 000000000..4cc1e429a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/challenge_policy.go @@ -0,0 +1,255 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package internal + +import ( + "bytes" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + "github.com/Azure/azure-sdk-for-go/sdk/internal/temporal" +) + +const ( + headerAuthorization = "Authorization" + challengeMatchError = `challenge resource "%s" doesn't match the requested domain. Set DisableChallengeResourceVerification to true in your client options to disable. See https://aka.ms/azsdk/blog/vault-uri for more information` + bearerHeader = "Bearer " +) + +type KeyVaultChallengePolicyOptions struct { + // DisableChallengeResourceVerification controls whether the policy requires the + // authentication challenge resource to match the Key Vault or Managed HSM domain + DisableChallengeResourceVerification bool +} + +type KeyVaultChallengePolicy struct { + // mainResource is the resource to be retrieved using the tenant specified in the credential + mainResource *temporal.Resource[azcore.AccessToken, acquiringResourceState] + cred azcore.TokenCredential + scope *string + tenantID *string + verifyChallengeResource bool +} + +func NewKeyVaultChallengePolicy(cred azcore.TokenCredential, opts *KeyVaultChallengePolicyOptions) *KeyVaultChallengePolicy { + if opts == nil { + opts = &KeyVaultChallengePolicyOptions{} + } + return &KeyVaultChallengePolicy{ + cred: cred, + mainResource: temporal.NewResource(acquire), + verifyChallengeResource: !opts.DisableChallengeResourceVerification, + } +} + +func (k *KeyVaultChallengePolicy) Do(req *policy.Request) (*http.Response, error) { + as := acquiringResourceState{ + p: k, + req: req, + } + + if k.scope == nil || k.tenantID == nil { + // First request, get both to get the token + challengeReq, err := k.getChallengeRequest(*req) + if err != nil { + return nil, err + } + + resp, err := challengeReq.Next() + if err != nil { + return nil, err + } + + if resp.StatusCode > 399 && resp.StatusCode != http.StatusUnauthorized { + // the request failed for some other reason, don't try any further + return resp, nil + } + err = k.findScopeAndTenant(resp, req.Raw()) + if err != nil { + return nil, err + } + } + + tk, err := k.mainResource.Get(as) + if err != nil { + return nil, err + } + + req.Raw().Header.Set( + headerAuthorization, + fmt.Sprintf("%s%s", bearerHeader, tk.Token), + ) + + // send a copy of the request + cloneReq := req.Clone(req.Raw().Context()) + resp, cloneReqErr := cloneReq.Next() + if cloneReqErr != nil { + return nil, cloneReqErr + } + + // If it fails and has a 401, try it with a new token + if resp.StatusCode == 401 { + // Force a new token + k.mainResource.Expire() + + // Find the scope and tenant again in case they have changed + err := k.findScopeAndTenant(resp, req.Raw()) + if err != nil { + // Error parsing challenge, doomed to fail. Return + return resp, cloneReqErr + } + + tk, err := k.mainResource.Get(as) + if err != nil { + return resp, err + } + + req.Raw().Header.Set( + headerAuthorization, + bearerHeader+tk.Token, + ) + + // send the original request now + return req.Next() + } + + return resp, err +} + +// parses Tenant ID from auth challenge +// https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000 +func parseTenant(url string) *string { + if url == "" { + return to.Ptr("") + } + parts := strings.Split(url, "/") + tenant := parts[3] + tenant = strings.ReplaceAll(tenant, ",", "") + return &tenant +} + +type challengePolicyError struct { + err error +} + +func (c *challengePolicyError) Error() string { + return c.err.Error() +} + +func (*challengePolicyError) NonRetriable() { + // marker method +} + +func (c *challengePolicyError) Unwrap() error { + return c.err +} + +var _ errorinfo.NonRetriable = (*challengePolicyError)(nil) + +// sets the k.scope and k.tenantID from the WWW-Authenticate header +func (k *KeyVaultChallengePolicy) findScopeAndTenant(resp *http.Response, req *http.Request) error { + authHeader := resp.Header.Get("WWW-Authenticate") + if authHeader == "" { + return &challengePolicyError{err: errors.New("response has no WWW-Authenticate header for challenge authentication")} + } + + // Strip down to auth and resource + // Format is "Bearer authorization=\"\" resource=\"\"" OR + // "Bearer authorization=\"\" scope=\"\" resource=\"\"" + authHeader = strings.ReplaceAll(authHeader, "Bearer ", "") + + parts := strings.Split(authHeader, " ") + + vals := map[string]string{} + for _, part := range parts { + subParts := strings.Split(part, "=") + if len(subParts) == 2 { + stripped := strings.ReplaceAll(subParts[1], "\"", "") + stripped = strings.TrimSuffix(stripped, ",") + vals[subParts[0]] = stripped + } + } + + k.tenantID = parseTenant(vals["authorization"]) + scope := "" + if v, ok := vals["scope"]; ok { + scope = v + } else if v, ok := vals["resource"]; ok { + scope = v + } + if scope == "" { + return &challengePolicyError{err: errors.New("could not find a valid resource in the WWW-Authenticate header")} + } + if k.verifyChallengeResource { + // the challenge resource's host must match the requested vault's host + parsed, err := url.Parse(scope) + if err != nil { + return &challengePolicyError{err: fmt.Errorf(`invalid challenge resource "%s": %v`, scope, err)} + } + if !strings.HasSuffix(req.URL.Host, "."+parsed.Host) { + return &challengePolicyError{err: fmt.Errorf(challengeMatchError, scope)} + } + } + if !strings.HasSuffix(scope, "/.default") { + scope += "/.default" + } + k.scope = &scope + return nil +} + +func (k KeyVaultChallengePolicy) getChallengeRequest(orig policy.Request) (*policy.Request, error) { + req, err := runtime.NewRequest(orig.Raw().Context(), orig.Raw().Method, orig.Raw().URL.String()) + if err != nil { + return nil, &challengePolicyError{err: err} + } + + req.Raw().Header = orig.Raw().Header + req.Raw().Header.Set("Content-Length", "0") + req.Raw().ContentLength = 0 + + copied := orig.Clone(orig.Raw().Context()) + copied.Raw().Body = req.Body() + copied.Raw().ContentLength = 0 + copied.Raw().Header.Set("Content-Length", "0") + err = copied.SetBody(streaming.NopCloser(bytes.NewReader([]byte{})), "application/json") + if err != nil { + return nil, &challengePolicyError{err: err} + } + copied.Raw().Header.Del("Content-Type") + + return copied, err +} + +type acquiringResourceState struct { + req *policy.Request + p *KeyVaultChallengePolicy +} + +// acquire acquires or updates the resource; only one +// thread/goroutine at a time ever calls this function +func acquire(state acquiringResourceState) (newResource azcore.AccessToken, newExpiration time.Time, err error) { + tk, err := state.p.cred.GetToken( + state.req.Raw().Context(), + policy.TokenRequestOptions{ + Scopes: []string{*state.p.scope}, + }, + ) + if err != nil { + return azcore.AccessToken{}, time.Time{}, err + } + return tk, tk.ExpiresOn, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/ci.keyvault.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/ci.keyvault.yml new file mode 100644 index 000000000..d72c65013 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/ci.keyvault.yml @@ -0,0 +1,28 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/keyvault/internal + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/keyvault/internal + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'keyvault/internal' + RunLiveTests: false diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/constants.go new file mode 100644 index 000000000..cd94eb0d8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/constants.go @@ -0,0 +1,11 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package internal + +const ( + version = "v0.7.1" //nolint +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/doc.go new file mode 100644 index 000000000..d8f93492f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package internal diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/parse.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/parse.go new file mode 100644 index 000000000..8511832d2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal/parse.go @@ -0,0 +1,37 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +package internal + +import ( + "fmt" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" +) + +// ParseID parses "https://myvaultname.vault.azure.net/keys/key1053998307/b86c2e6ad9054f4abf69cc185b99aa60" +// into "https://myvaultname.managedhsm.azure.net/", "key1053998307", and "b86c2e6ad9054f4abf69cc185b99aa60" +func ParseID(id *string) (*string, *string, *string) { + if id == nil { + return nil, nil, nil + } + parsed, err := url.Parse(*id) + if err != nil { + return nil, nil, nil + } + + url := fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host) + split := strings.Split(strings.TrimPrefix(parsed.Path, "/"), "/") + if len(split) < 3 { + if len(split) == 2 { + return &url, to.Ptr(split[1]), nil + } + return &url, nil, nil + } + + return &url, to.Ptr(split[1]), to.Ptr(split[2]) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 546d46cf5..c7feb66b7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -47,6 +47,12 @@ github.com/Azure/azure-sdk-for-go/sdk/internal/log github.com/Azure/azure-sdk-for-go/sdk/internal/poller github.com/Azure/azure-sdk-for-go/sdk/internal/temporal github.com/Azure/azure-sdk-for-go/sdk/internal/uuid +# github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets v0.12.0 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets +# github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal # github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 v5.6.0 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5 @@ -1613,11 +1619,12 @@ sigs.k8s.io/cloud-provider-azure/pkg/util/string sigs.k8s.io/cloud-provider-azure/pkg/util/taints sigs.k8s.io/cloud-provider-azure/pkg/util/vm sigs.k8s.io/cloud-provider-azure/pkg/version -# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.7 +# sigs.k8s.io/cloud-provider-azure/pkg/azclient v0.0.9 ## explicit; go 1.20 sigs.k8s.io/cloud-provider-azure/pkg/azclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient/mock_accountclient +sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient sigs.k8s.io/cloud-provider-azure/pkg/azclient/blobcontainerclient/mock_blobcontainerclient diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/arm_conf.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/arm_conf.go index e533cf669..d2e654c85 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/arm_conf.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/arm_conf.go @@ -62,3 +62,7 @@ func GetAzCoreClientOption(armConfig *ARMClientConfig) (*policy.ClientOptions, e } return &azCoreClientConfig, nil } + +func IsMultiTenant(armConfig *ARMClientConfig) bool { + return armConfig != nil && armConfig.NetworkResourceTenantID != "" && !strings.EqualFold(armConfig.NetworkResourceTenantID, armConfig.GetTenantID()) +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/auxiliary_auth_policy.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/auxiliary_auth_policy.go new file mode 100644 index 000000000..0af24a8bf --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/auxiliary_auth_policy.go @@ -0,0 +1,59 @@ +/* +Copyright 2024 The Kubernetes Authors. + +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. +*/ + +package armauth + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +const ( + HeaderAuthorizationAuxiliary = "x-ms-authorization-auxiliary" +) + +type AuxiliaryAuthPolicy struct { + credentials []azcore.TokenCredential + scope string +} + +func NewAuxiliaryAuthPolicy(credentials []azcore.TokenCredential, scope string) *AuxiliaryAuthPolicy { + return &AuxiliaryAuthPolicy{ + credentials: credentials, + scope: scope, + } +} + +func (p *AuxiliaryAuthPolicy) Do(req *policy.Request) (*http.Response, error) { + tokens := make([]string, 0, len(p.credentials)) + + for _, cred := range p.credentials { + token, err := cred.GetToken(context.TODO(), policy.TokenRequestOptions{ + Scopes: []string{p.scope}, + }) + if err != nil { + return nil, err + } + tokens = append(tokens, fmt.Sprintf("Bearer %s", token.Token)) + } + req.Raw().Header.Set(HeaderAuthorizationAuxiliary, strings.Join(tokens, ", ")) + return req.Next() +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/keyvault_credential.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/keyvault_credential.go new file mode 100644 index 000000000..13352d729 --- /dev/null +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth/keyvault_credential.go @@ -0,0 +1,102 @@ +/* +Copyright 2024 The Kubernetes Authors. + +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. +*/ + +package armauth + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets" +) + +type KeyVaultCredential struct { + secretClient *azsecrets.Client + secretPath string + + token *azcore.AccessToken +} + +type KeyVaultCredentialSecret struct { + AccessToken string `json:"access_token"` + ExpiresOn time.Time `json:"expires_on"` +} + +func NewKeyVaultCredential( + msiCredential azcore.TokenCredential, + keyVaultURL string, + secretName string, +) (*KeyVaultCredential, error) { + cli, err := azsecrets.NewClient(keyVaultURL, msiCredential, nil) + if err != nil { + return nil, fmt.Errorf("create KeyVault client: %w", err) + } + + rv := &KeyVaultCredential{ + secretClient: cli, + secretPath: secretName, + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := rv.refreshToken(ctx); err != nil { + return nil, fmt.Errorf("refresh token: %w", err) + } + + return rv, nil +} + +func (c *KeyVaultCredential) refreshToken(ctx context.Context) error { + const LatestVersion = "" + + resp, err := c.secretClient.GetSecret(ctx, c.secretPath, LatestVersion, nil) + if err != nil { + return err + } + if resp.Value == nil { + return fmt.Errorf("secret value is nil") + } + + var secret KeyVaultCredentialSecret + if err := json.Unmarshal([]byte(*resp.Value), &secret); err != nil { + return fmt.Errorf("unmarshal secret value `%s`: %w", *resp.Value, err) + } + + c.token = &azcore.AccessToken{ + Token: secret.AccessToken, + ExpiresOn: secret.ExpiresOn, + } + + return nil +} + +func (c *KeyVaultCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + const RefreshTokenOffset = 5 * time.Minute + + if c.token != nil && c.token.ExpiresOn.Add(RefreshTokenOffset).Before(time.Now()) { + return *c.token, nil + } + + if err := c.refreshToken(ctx); err != nil { + return azcore.AccessToken{}, fmt.Errorf("refresh token: %w", err) + } + + return *c.token, nil +} diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth.go index 503efd3db..df6316a16 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth.go @@ -24,15 +24,21 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/armauth" ) type AuthProvider struct { - FederatedIdentityCredential azcore.TokenCredential - ManagedIdentityCredential azcore.TokenCredential - ClientSecretCredential azcore.TokenCredential + FederatedIdentityCredential azcore.TokenCredential + + ManagedIdentityCredential azcore.TokenCredential + ClientSecretCredential azcore.TokenCredential + ClientCertificateCredential azcore.TokenCredential + + NetworkTokenCredential azcore.TokenCredential NetworkClientSecretCredential azcore.TokenCredential - MultiTenantCredential azcore.TokenCredential - ClientCertificateCredential azcore.TokenCredential + + MultiTenantCredential azcore.TokenCredential } func NewAuthProvider(armConfig *ARMClientConfig, config *AzureAuthConfig, clientOptionsMutFn ...func(option *policy.ClientOptions)) (*AuthProvider, error) { @@ -76,6 +82,20 @@ func NewAuthProvider(armConfig *ARMClientConfig, config *AzureAuthConfig, client } } + var ( + networkTokenCredential azcore.TokenCredential + ) + if config.UseManagedIdentityExtension && config.AuxiliaryTokenProvider != nil && IsMultiTenant(armConfig) { + networkTokenCredential, err = armauth.NewKeyVaultCredential( + managedIdentityCredential, + config.AuxiliaryTokenProvider.KeyVaultURL, + config.AuxiliaryTokenProvider.SecretName, + ) + if err != nil { + return nil, fmt.Errorf("create KeyVaultCredential for auxiliary token provider: %w", err) + } + } + // ClientSecretCredential is used for client secret var clientSecretCredential azcore.TokenCredential var networkClientSecretCredential azcore.TokenCredential @@ -88,7 +108,7 @@ func NewAuthProvider(armConfig *ARMClientConfig, config *AzureAuthConfig, client if err != nil { return nil, err } - if len(armConfig.NetworkResourceTenantID) > 0 && !strings.EqualFold(armConfig.NetworkResourceTenantID, armConfig.GetTenantID()) { + if IsMultiTenant(armConfig) { credOptions := &azidentity.ClientSecretCredentialOptions{ ClientOptions: *clientOption, } @@ -128,7 +148,7 @@ func NewAuthProvider(armConfig *ARMClientConfig, config *AzureAuthConfig, client if err != nil { return nil, err } - if len(armConfig.NetworkResourceTenantID) > 0 && !strings.EqualFold(armConfig.NetworkResourceTenantID, armConfig.GetTenantID()) { + if IsMultiTenant(armConfig) { networkClientSecretCredential, err = azidentity.NewClientCertificateCredential(armConfig.NetworkResourceTenantID, config.GetAADClientID(), certificate, privateKey, credOptions) if err != nil { return nil, err @@ -150,6 +170,7 @@ func NewAuthProvider(armConfig *ARMClientConfig, config *AzureAuthConfig, client ClientSecretCredential: clientSecretCredential, ClientCertificateCredential: clientCertificateCredential, NetworkClientSecretCredential: networkClientSecretCredential, + NetworkTokenCredential: networkTokenCredential, MultiTenantCredential: multiTenantCredential, }, nil } @@ -173,6 +194,9 @@ func (factory *AuthProvider) GetNetworkAzIdentity() azcore.TokenCredential { if factory.NetworkClientSecretCredential != nil { return factory.NetworkClientSecretCredential } + if factory.NetworkTokenCredential != nil { + return factory.NetworkTokenCredential + } return nil } diff --git a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go index 46a66e94f..aa7e464f2 100644 --- a/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go +++ b/vendor/sigs.k8s.io/cloud-provider-azure/pkg/azclient/auth_conf.go @@ -42,6 +42,14 @@ type AzureAuthConfig struct { AADFederatedTokenFile string `json:"aadFederatedTokenFile,omitempty" yaml:"aadFederatedTokenFile,omitempty"` // Use workload identity federation for the virtual machine to access Azure ARM APIs UseFederatedWorkloadIdentityExtension bool `json:"useFederatedWorkloadIdentityExtension,omitempty" yaml:"useFederatedWorkloadIdentityExtension,omitempty"` + // Auxiliary token provider for accessing resources from network tenant + // Require MSI to be enabled and have permission to access the KeyVault + AuxiliaryTokenProvider *AzureAuthAuxiliaryTokenProvider `json:"auxiliaryTokenProvider,omitempty" yaml:"auxiliaryTokenProvider,omitempty"` +} + +type AzureAuthAuxiliaryTokenProvider struct { + KeyVaultURL string `json:"keyVaultURL,omitempty" yaml:"keyVaultURL,omitempty"` + SecretName string `json:"secretName" yaml:"secretName"` } func (config *AzureAuthConfig) GetAADClientID() string {