From 79337dde464aaf0cc2d2178260c7c27b728f2bb1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Apr 2025 16:42:32 +0000 Subject: [PATCH] build(deps): bump github.com/sigstore/sigstore/pkg/signature/kms/azure Bumps [github.com/sigstore/sigstore/pkg/signature/kms/azure](https://github.com/sigstore/sigstore) from 1.8.15 to 1.9.4. - [Release notes](https://github.com/sigstore/sigstore/releases) - [Commits](https://github.com/sigstore/sigstore/compare/v1.8.15...v1.9.4) --- updated-dependencies: - dependency-name: github.com/sigstore/sigstore/pkg/signature/kms/azure dependency-version: 1.9.4 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 30 +- go.sum | 75 +- .../azure-sdk-for-go/sdk/azcore/CHANGELOG.md | 14 + .../sdk/azcore/internal/exported/exported.go | 7 +- .../sdk/azcore/internal/shared/constants.go | 2 +- .../sdk/azcore/runtime/policy_bearer_token.go | 14 +- .../sdk/azidentity/BREAKING_CHANGES.md | 10 + .../sdk/azidentity/CHANGELOG.md | 31 + .../sdk/azidentity/MIGRATION.md | 2 +- .../azure-sdk-for-go/sdk/azidentity/README.md | 44 +- .../sdk/azidentity/TOKEN_CACHING.MD | 15 +- .../sdk/azidentity/TROUBLESHOOTING.md | 24 + .../sdk/azidentity/assets.json | 2 +- .../sdk/azidentity/azidentity.go | 29 +- .../sdk/azidentity/azure_cli_credential.go | 12 +- .../azure_developer_cli_credential.go | 6 +- .../azidentity/chained_token_credential.go | 8 +- .../azure-sdk-for-go/sdk/azidentity/ci.yml | 15 +- .../sdk/azidentity/confidential_client.go | 4 +- .../azidentity/default_azure_credential.go | 14 +- .../sdk/azidentity/device_code_credential.go | 5 +- .../sdk/azidentity/environment_credential.go | 7 +- .../azure-sdk-for-go/sdk/azidentity/go.work | 2 +- .../interactive_browser_credential.go | 5 +- .../azidentity/managed-identity-matrix.json | 2 +- .../sdk/azidentity/managed_identity_client.go | 438 ++--------- .../azidentity/managed_identity_credential.go | 28 +- .../sdk/azidentity/public_client.go | 11 +- .../sdk/azidentity/test-resources-post.ps1 | 20 +- .../username_password_credential.go | 12 +- .../sdk/azidentity/version.go | 2 +- .../azure-sdk-for-go/sdk/internal/log/log.go | 2 +- .../sdk/internal/temporal/resource.go | 51 +- .../sdk/security/keyvault/azkeys/CHANGELOG.md | 5 + .../sdk/security/keyvault/azkeys/README.md | 12 +- .../sdk/security/keyvault/azkeys/autorest.md | 252 ------ .../sdk/security/keyvault/azkeys/build.go | 8 +- .../sdk/security/keyvault/azkeys/ci.yml | 9 - .../sdk/security/keyvault/azkeys/client.go | 398 ++++++---- .../sdk/security/keyvault/azkeys/constants.go | 196 ++--- .../security/keyvault/azkeys/custom_client.go | 5 +- .../sdk/security/keyvault/azkeys/models.go | 38 +- .../security/keyvault/azkeys/models_serde.go | 235 ++++-- .../sdk/security/keyvault/azkeys/options.go | 12 +- .../{response_types.go => responses.go} | 6 +- .../sdk/security/keyvault/azkeys/time_unix.go | 12 +- .../keyvault/azkeys/tsp-location.yaml | 6 + .../sdk/security/keyvault/azkeys/version.go | 5 +- .../security/keyvault/internal/CHANGELOG.md | 5 + .../keyvault/internal/challenge_policy.go | 37 +- .../keyvault/internal/ci.keyvault.yml | 1 + .../security/keyvault/internal/constants.go | 2 +- .../apps/confidential/confidential.go | 61 +- .../apps/errors/errors.go | 9 + .../apps/internal/base/base.go | 61 +- .../base/{internal => }/storage/items.go | 7 +- .../storage/partitioned_storage.go | 3 +- .../base/{internal => }/storage/storage.go | 8 +- .../apps/internal/exported/exported.go | 2 + .../apps/internal/local/server.go | 3 +- .../apps/internal/oauth/oauth.go | 20 +- .../oauth/ops/accesstokens/accesstokens.go | 55 +- .../internal/oauth/ops/accesstokens/tokens.go | 66 +- .../internal/oauth/ops/authority/authority.go | 8 +- .../internal/oauth/ops/internal/comm/comm.go | 4 +- .../apps/internal/version/version.go | 2 +- .../apps/managedidentity/azure_ml.go | 28 + .../apps/managedidentity/cloud_shell.go | 37 + .../apps/managedidentity/managedidentity.go | 717 ++++++++++++++++++ .../apps/managedidentity/servicefabric.go | 25 + .../apps/public/public.go | 13 +- .../stargz-snapshotter/estargz/build.go | 3 +- .../stargz-snapshotter/estargz/testutil.go | 15 +- .../cli/cli/config/credentials/file_store.go | 14 +- .../client/client.go | 25 +- .../client/command.go | 13 +- .../credentials/credentials.go | 69 +- .../credentials/error.go | 40 +- .../internal/redact/redact.go | 6 +- .../pkg/authn/keychain.go | 4 +- .../go-containerregistry/pkg/name/ref.go | 2 +- .../pkg/v1/mutate/mutate.go | 7 +- .../pkg/v1/remote/referrers.go | 2 +- .../pkg/v1/remote/transport/bearer.go | 20 +- .../gen/pb-go/common/v1/sigstore_common.pb.go | 71 +- .../pkg/signature/kms/azure/client.go | 2 +- .../vbatts/tar-split/archive/tar/reader.go | 12 +- .../net/http/otelhttp/client.go | 6 +- .../net/http/otelhttp/common.go | 7 - .../net/http/otelhttp/handler.go | 31 +- .../internal/request/resp_writer_wrapper.go | 11 +- .../net/http/otelhttp/internal/semconv/env.go | 120 ++- .../otelhttp/internal/semconv/httpconv.go | 34 +- .../http/otelhttp/internal/semconv/util.go | 4 +- .../http/otelhttp/internal/semconv/v1.20.0.go | 130 +++- .../net/http/otelhttp/start_time_context.go | 29 + .../net/http/otelhttp/transport.go | 58 +- .../net/http/otelhttp/version.go | 2 +- vendor/golang.org/x/sys/execabs/execabs.go | 102 --- .../golang.org/x/sys/execabs/execabs_go118.go | 17 - .../golang.org/x/sys/execabs/execabs_go119.go | 20 - vendor/modules.txt | 52 +- 102 files changed, 2594 insertions(+), 1650 deletions(-) delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/autorest.md rename vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/{response_types.go => responses.go} (95%) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/tsp-location.yaml rename vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/{internal => }/storage/items.go (95%) rename vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/{internal => }/storage/partitioned_storage.go (99%) rename vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/{internal => }/storage/storage.go (98%) create mode 100644 vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/azure_ml.go create mode 100644 vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/cloud_shell.go create mode 100644 vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/managedidentity.go create mode 100644 vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/servicefabric.go create mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go118.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go119.go diff --git a/go.mod b/go.mod index 5eb0abad830..b6922c88d84 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/ahmetb/gen-crd-api-reference-docs v0.3.1-0.20220720053627-e327d0730470 // Waiting for https://github.com/ahmetb/gen-crd-api-reference-docs/pull/43/files to merge github.com/cloudevents/sdk-go/v2 v2.15.2 github.com/google/go-cmp v0.7.0 - github.com/google/go-containerregistry v0.20.2 + github.com/google/go-containerregistry v0.20.3 github.com/google/uuid v1.6.0 github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 @@ -43,7 +43,7 @@ require ( github.com/google/cel-go v0.24.1 github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20240108195214-a0658aa1d0cc github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15 - github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15 + github.com/sigstore/sigstore/pkg/signature/kms/azure v1.9.4 github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15 github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.15 go.opentelemetry.io/otel v1.35.0 @@ -64,12 +64,12 @@ require ( cloud.google.com/go/longrunning v0.6.2 // indirect fortio.org/safecast v1.0.0 // indirect github.com/42wim/httpsig v1.2.1 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 // indirect - github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.9.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 // indirect github.com/antlr4-go/antlr/v4 v4.13.0 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.1 // indirect github.com/aws/aws-sdk-go-v2/service/kms v1.37.13 // indirect @@ -107,14 +107,14 @@ require ( github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/ryanuber/go-glob v1.0.0 // indirect github.com/secure-systems-lab/go-securesystemslib v0.9.0 // indirect - github.com/sigstore/protobuf-specs v0.4.0 // indirect + github.com/sigstore/protobuf-specs v0.4.1 // indirect github.com/stoewer/go-strcase v1.3.0 // indirect github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/zeebo/errs v1.4.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 // indirect go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/proto/otlp v1.5.0 // indirect @@ -163,12 +163,12 @@ require ( github.com/census-instrumentation/opencensus-proto v0.4.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589 // indirect - github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect + github.com/containerd/stargz-snapshotter/estargz v0.16.3 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dimchansky/utfbom v1.1.1 // indirect - github.com/docker/cli v27.1.1+incompatible // indirect - github.com/docker/distribution v2.8.2+incompatible // indirect - github.com/docker/docker-credential-helpers v0.7.0 // indirect + github.com/docker/cli v27.5.0+incompatible // indirect + github.com/docker/distribution v2.8.3+incompatible // indirect + github.com/docker/docker-credential-helpers v0.8.2 // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect @@ -208,7 +208,7 @@ require ( github.com/sirupsen/logrus v1.9.3 // indirect github.com/spf13/pflag v1.0.6 // indirect github.com/stretchr/testify v1.10.0 - github.com/vbatts/tar-split v0.11.3 // indirect + github.com/vbatts/tar-split v0.11.6 // indirect go.uber.org/automaxprocs v1.6.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/crypto v0.37.0 // indirect diff --git a/go.sum b/go.sum index 9b8687f26b3..ba543e5fe7a 100644 --- a/go.sum +++ b/go.sum @@ -68,18 +68,18 @@ github.com/42wim/httpsig v1.2.1/go.mod h1:P/UYo7ytNBFwc+dg35IubuAUIs8zj5zzFIgUCE github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 h1:g0EZJwz7xkXQiZAI5xi9f3WWFYBlX1CPTrR+NDToRkQ= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0/go.mod h1:XCW7KnZet0Opnr7HccfUw1PLc4CjHqpcaxW8DHklNkQ= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0/go.mod h1:fiPSssYvltE08HJchL04dOy+RD4hgrjph0cwGGMntdI= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0 h1:+m0M/LFxN43KvULkDNfdXOgrjtg6UYJPFBJyuEcRCAw= -github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0/go.mod h1:PwOyop78lveYMRs6oCxjiVyBdyCgIYH6XHIVZO9/SFQ= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.0 h1:7rKG7UmnrxX4N53TFhkYqjc+kVUZuw0fL8I3Fh+Ld9E= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.0/go.mod h1:Wjo+24QJVhhl/L7jy6w9yzFF2yDOf3cKECAa8ecf9vE= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 h1:eXnN9kaS8TiDwXjoie3hMRLuwdUBUMW9KRgOqB3mCaw= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0/go.mod h1:XIpam8wumeZ5rVMuhdDQLMfIPDf1WO3IzrCRO3e3e3o= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0 h1:Gt0j3wceWMwPmiazCa8MzMA0MfhmPIz0Qp0FJ6qcM0U= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0/go.mod h1:Ot/6aikWnKWi4l9QB7qVSwa8iMphQNqkWALMoNT3rzM= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.9.0 h1:OVoM452qUFBrX+URdH3VpR299ma4kfom0yB0URYky9g= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.9.0/go.mod h1:kUjrAo8bgEwLeZ/CmHqNl3Z/kPm7y6FKfxxK0izYUg4= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 h1:FPKJS1T+clwv+OLGt13a8UjqeRuh0O4SJ3lUriThc+4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1/go.mod h1:j2chePtV91HrC22tGoRX3sGY42uF13WzmmV80/OdVAA= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1 h1:Wgf5rZba3YZqeTNJPtvqZoBu1sBN/L4sry+u2U3Y75w= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1/go.mod h1:xxCBG/f/4Vbmh2XQJBsOmNdxWUY5j/s27jujKPbQf14= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1 h1:bFWuoEKg+gImo7pvkiQEFAc8ocibADgXeiLAxWhWmkI= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1/go.mod h1:Vih/3yc6yac2JzU4hzpaDupBJP0Flaia9rXXrU8xyww= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-autorest v10.8.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= @@ -112,10 +112,9 @@ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUM github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= -github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 h1:gUDtaZk8heteyfdmv+pcfHvhR9llnh7c7GMwZ8RVG04= -github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 h1:oygO0locgZJe7PpYPXT5A29ZkwJaPqcva7BVeemZOZs= +github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= @@ -327,8 +326,8 @@ github.com/containerd/nri v0.0.0-20201007170849-eb1350a75164/go.mod h1:+2wGSDGFY github.com/containerd/nri v0.0.0-20210316161719-dbaa18c31c14/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= github.com/containerd/nri v0.1.0/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= github.com/containerd/stargz-snapshotter/estargz v0.7.0/go.mod h1:83VWDqHnurTKliEB0YvWMiCfLDwv4Cjj1X9Vk98GJZw= -github.com/containerd/stargz-snapshotter/estargz v0.14.3 h1:OqlDCK3ZVUO6C3B/5FSkDwbkEETK84kQgEeFwDC+62k= -github.com/containerd/stargz-snapshotter/estargz v0.14.3/go.mod h1:KY//uOCIkSuNAHhJogcZtrNHdKrA99/FCCRjE3HD36o= +github.com/containerd/stargz-snapshotter/estargz v0.16.3 h1:7evrXtoh1mSbGj/pfRccTampEyKpjpOnS3CyiV1Ebr8= +github.com/containerd/stargz-snapshotter/estargz v0.16.3/go.mod h1:uyr4BfYfOj3G9WBVE8cOlQmXAbPN9VEQpBBeJIuOipU= github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= github.com/containerd/ttrpc v0.0.0-20190828172938-92c8520ef9f8/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= github.com/containerd/ttrpc v0.0.0-20191028202541-4f1b8fe65a5c/go.mod h1:LPm1u0xBw8r8NOKoOdNMeVHSawSsltak+Ihv+etqsE8= @@ -370,7 +369,6 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= @@ -395,17 +393,18 @@ github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= github.com/docker/cli v20.10.7+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/cli v27.1.1+incompatible h1:goaZxOqs4QKxznZjjBWKONQci/MywhtRv2oNn0GkeZE= -github.com/docker/cli v27.1.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v27.5.0+incompatible h1:aMphQkcGtpHixwwhAXJT1rrK/detk2JIvDaFkLctbGM= +github.com/docker/cli v27.5.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= -github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= +github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/docker v20.10.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.6.3/go.mod h1:WRaJzqw3CTB9bk10avuGsjVBZsD05qeibJ1/TYlvc0Y= -github.com/docker/docker-credential-helpers v0.7.0 h1:xtCHsjxogADNZcdv1pKUHXryefjlVRqWqIhk/uXJp0A= github.com/docker/docker-credential-helpers v0.7.0/go.mod h1:rETQfLdHNT3foU5kuNkFR1R1V12OJRRO5lzt2D1b5X0= +github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo= +github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= @@ -584,8 +583,8 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-containerregistry v0.6.0/go.mod h1:euCCtNbZ6tKqi1E72vwDj2xZcN5ttKpZLfa/wSo5iLw= -github.com/google/go-containerregistry v0.20.2 h1:B1wPJ1SN/S7pB+ZAimcciVD+r+yV/l/DSArMxlbwseo= -github.com/google/go-containerregistry v0.20.2/go.mod h1:z38EKdKh4h7IP2gSfUUqEvalZBqs6AoLeWfUy34nQC8= +github.com/google/go-containerregistry v0.20.3 h1:oNx7IdTI936V8CQRveCjaxOiegWwvM7kqkbXTpyiovI= +github.com/google/go-containerregistry v0.20.3/go.mod h1:w00pIgBRDVUDFM6bq+Qx8lwNWK+cxgCuX1vd3PIBDNI= github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20240108195214-a0658aa1d0cc h1:eJ9J17+23quNw5z6O9AdTH+irI7JI+6eQX9TswViyvk= github.com/google/go-containerregistry/pkg/authn/k8schain v0.0.0-20240108195214-a0658aa1d0cc/go.mod h1:Ek+8PQrShkA7aHEj3/zSW33wU0V/Bx3zW/gFh7l21xY= github.com/google/go-containerregistry/pkg/authn/kubernetes v0.0.0-20240108195214-a0658aa1d0cc h1:fHDosK/RhxYQpWBRo+bbawVuR402odSaNToA0Pp+ojw= @@ -740,8 +739,8 @@ github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8 github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8= github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= -github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6 h1:IsMZxCuZqKuao2vNdfD82fjjgPLfyHLpR41Z88viRWs= -github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6/go.mod h1:3VeWNIJaW+O5xpRQbPp0Ybqu1vJd/pm7s2F473HRrkw= +github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU= +github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -957,8 +956,8 @@ github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoG github.com/prometheus/statsd_exporter v0.22.7 h1:7Pji/i2GuhK6Lu7DHrtTkFmNBCudCPT1pX2CziuyQR0= github.com/prometheus/statsd_exporter v0.22.7/go.mod h1:N/TevpjkIh9ccs6nuzY3jQn9dFqnUakOjnEuMPJJJnI= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4= -github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= @@ -984,14 +983,14 @@ github.com/shurcooL/githubv4 v0.0.0-20190718010115-4ba037080260/go.mod h1:hAF0iL github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f h1:tygelZueB1EtXkPI6mQ4o9DQ0+FKW41hTbunoXZCTqk= github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f/go.mod h1:AuYgA5Kyo4c7HfUmvRGs/6rGlMMV/6B1bVnB9JxJEEg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sigstore/protobuf-specs v0.4.0 h1:yoZbdh0kZYKOSiVbYyA8J3f2wLh5aUk2SQB7LgAfIdU= -github.com/sigstore/protobuf-specs v0.4.0/go.mod h1:FKW5NYhnnFQ/Vb9RKtQk91iYd0MKJ9AxyqInEwU6+OI= +github.com/sigstore/protobuf-specs v0.4.1 h1:5SsMqZbdkcO/DNHudaxuCUEjj6x29tS2Xby1BxGU7Zc= +github.com/sigstore/protobuf-specs v0.4.1/go.mod h1:+gXR+38nIa2oEupqDdzg4qSBT0Os+sP7oYv6alWewWc= github.com/sigstore/sigstore v1.8.15 h1:9HHnZmxjPQSTPXTCZc25HDxxSTWwsGMh/ZhWZZ39maU= github.com/sigstore/sigstore v1.8.15/go.mod h1:+Wa5mrG6A+Gss516YC9owy10q3IazqIRe0y1EoQRHHM= github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15 h1:g/hPoaemFv/6ZJIRyb5I1lA4qU9PZwCTu/GkvFV5jEw= github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15/go.mod h1:n2yKi/b29+JB54PyONruHvvha4zugC7jzr+A16cNLvw= -github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15 h1:K2GstKWXftcpmg/wHfcJFYKWuj+YRSoTgwxm3ox2FjE= -github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15/go.mod h1:tOSdKYXCkplk54FSR/58UYQm1S/GlQK4Y1GgMhiq40U= +github.com/sigstore/sigstore/pkg/signature/kms/azure v1.9.4 h1:MHRm7YQuF4zFyoXRLgUdLaNxqVO6JlLGnkDUI9fm9ow= +github.com/sigstore/sigstore/pkg/signature/kms/azure v1.9.4/go.mod h1:899VNYSSnQ0QtcuhkW0gznzxn0cqhowTL3nzc/xnym8= github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15 h1:ThpZMfR2TecI6Ji7s/nFlcCIkwXYhZUYziJdZs3pOaw= github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15/go.mod h1:x+4wvq6tzIQRZaSdMS6/VT9nuCoepypozfzP4Tqwnqw= github.com/sigstore/sigstore/pkg/signature/kms/hashivault v1.8.15 h1:mR+VaOSx2sUpaE8lXarinHcT8UXi+fKE4ESNBzDRAtQ= @@ -1081,11 +1080,10 @@ github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli v1.22.12/go.mod h1:sSBEIC79qR6OvcmsD4U3KABeOTxDqQtdDnaFuUN30b8= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/vbatts/tar-split v0.11.3 h1:hLFqsOLQ1SsppQNTMpkpPXClLDfC2A3Zgy9OUU+RVck= -github.com/vbatts/tar-split v0.11.3/go.mod h1:9QlHN18E+fEH7RdG+QAJJcuya3rqT7eXSTY7wGrAokY= +github.com/vbatts/tar-split v0.11.6 h1:4SjTW5+PU11n6fZenf2IPoV8/tz3AaYHMWjf23envGs= +github.com/vbatts/tar-split v0.11.6/go.mod h1:dqKNtesIOr2j2Qv3W/cHjnvk9I8+G7oAkFDFN6TCBEI= github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= @@ -1134,8 +1132,8 @@ go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJyS go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 h1:r6I7RJCN86bpD/FQwedZ0vSixDpwuWREjW9oRMsmqDc= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0/go.mod h1:B9yO6b04uB80CzjedvewuqDhxJxi11s7/GtiGa8bAjI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 h1:OeNbIYk/2C15ckl7glBlOBp5+WlYsOElzTNmiPW/x60= @@ -1421,7 +1419,6 @@ golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220906165534-d0df966e6959/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md index cf422304e7b..926ed3882cd 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md @@ -1,5 +1,19 @@ # Release History +## 1.18.0 (2025-04-03) + +### Features Added + +* Added `AccessToken.RefreshOn` and updated `BearerTokenPolicy` to consider nonzero values of it when deciding whether to request a new token + + +## 1.17.1 (2025-03-20) + +### Other Changes + +* Upgraded to Go 1.23 +* Upgraded dependencies + ## 1.17.0 (2025-01-07) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go index f2b296b6dc7..460170034aa 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go @@ -47,8 +47,13 @@ func HasStatusCode(resp *http.Response, statusCodes ...int) bool { // AccessToken represents an Azure service bearer access token with expiry information. // Exported as azcore.AccessToken. type AccessToken struct { - Token string + // Token is the access token + Token string + // ExpiresOn indicates when the token expires ExpiresOn time.Time + // RefreshOn is a suggested time to refresh the token. + // Clients should ignore this value when it's zero. + RefreshOn time.Time } // TokenRequestOptions contain specific parameter that may be used by credentials types when attempting to get a token. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go index 44ab00d4008..85514db3b84 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go @@ -40,5 +40,5 @@ const ( Module = "azcore" // Version is the semantic version (see http://semver.org) of this module. - Version = "v1.17.0" + Version = "v1.18.0" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go index b26db920b09..1950a2e5b3f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go @@ -51,6 +51,15 @@ func acquire(state acquiringResourceState) (newResource exported.AccessToken, ne return tk, tk.ExpiresOn, nil } +// shouldRefresh determines whether the token should be refreshed. It's a variable so tests can replace it. +var shouldRefresh = func(tk exported.AccessToken, _ acquiringResourceState) bool { + if tk.RefreshOn.IsZero() { + return tk.ExpiresOn.Add(-5 * time.Minute).Before(time.Now()) + } + // no offset in this case because the authority suggested a refresh window--between RefreshOn and ExpiresOn + return tk.RefreshOn.Before(time.Now()) +} + // NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens. // cred: an azcore.TokenCredential implementation such as a credential object from azidentity // scopes: the list of permission scopes required for the token. @@ -69,11 +78,14 @@ func NewBearerTokenPolicy(cred exported.TokenCredential, scopes []string, opts * return authNZ(policy.TokenRequestOptions{Scopes: scopes}) } } + mr := temporal.NewResourceWithOptions(acquire, temporal.ResourceOptions[exported.AccessToken, acquiringResourceState]{ + ShouldRefresh: shouldRefresh, + }) return &BearerTokenPolicy{ authzHandler: ah, cred: cred, scopes: scopes, - mainResource: temporal.NewResource(acquire), + mainResource: mr, allowHTTP: opts.InsecureAllowCredentialWithHTTP, } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/BREAKING_CHANGES.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/BREAKING_CHANGES.md index ea267e4f411..567e6975b18 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/BREAKING_CHANGES.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/BREAKING_CHANGES.md @@ -1,5 +1,15 @@ # Breaking Changes +## v1.8.0 + +### New errors from `NewManagedIdentityCredential` in some environments + +`NewManagedIdentityCredential` now returns an error when `ManagedIdentityCredentialOptions.ID` is set in a hosting environment whose managed identity API doesn't support user-assigned identities. `ManagedIdentityCredential.GetToken()` formerly logged a warning in these cases. Returning an error instead prevents the credential authenticating an unexpected identity. The affected hosting environments are: + * Azure Arc + * Azure ML (when a resource or object ID is specified; client IDs are supported) + * Cloud Shell + * Service Fabric + ## v1.6.0 ### Behavioral change to `DefaultAzureCredential` in IMDS managed identity scenarios diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md index e35f5ad935b..485224197e8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md @@ -1,5 +1,36 @@ # Release History +## 1.9.0 (2025-04-08) + +### Features Added +* `GetToken()` sets `AccessToken.RefreshOn` when the token provider specifies a value + +### Other Changes +* `NewManagedIdentityCredential` logs the configured user-assigned identity, if any +* Deprecated `UsernamePasswordCredential` because it can't support multifactor + authentication (MFA), which Microsoft Entra ID requires for most tenants. See + https://aka.ms/azsdk/identity/mfa for migration guidance. +* Updated dependencies + +## 1.8.2 (2025-02-12) + +### Other Changes +* Upgraded dependencies + +## 1.8.1 (2025-01-15) + +### Bugs Fixed +* User credential types inconsistently log access token scopes +* `DefaultAzureCredential` skips managed identity in Azure Container Instances +* Credentials having optional tenant IDs such as `AzureCLICredential` and + `InteractiveBrowserCredential` require setting `AdditionallyAllowedTenants` + when used with some clients + +### Other Changes +* `ChainedTokenCredential` and `DefaultAzureCredential` continue to their next + credential after `ManagedIdentityCredential` receives an unexpected response + from IMDS, indicating the response is from something else such as a proxy + ## 1.8.0 (2024-10-08) ### Other Changes diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md index 4404be82449..29b60baec8a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md @@ -304,4 +304,4 @@ client := subscriptions.NewClient() client.Authorizer = azidext.NewTokenCredentialAdapter(cred, []string{"https://management.azure.com//.default"}) ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FMIGRATION.png) + diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md index 96f30b25cc3..069bc688d52 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md @@ -21,7 +21,7 @@ go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity ## Prerequisites - an [Azure subscription](https://azure.microsoft.com/free/) -- Go 1.18 +- [Supported](https://aka.ms/azsdk/go/supported-versions) version of Go ### Authenticating during local development @@ -54,17 +54,7 @@ The `azidentity` module focuses on OAuth authentication with Microsoft Entra ID. ### DefaultAzureCredential -`DefaultAzureCredential` simplifies authentication while developing applications that deploy to Azure by combining credentials used in Azure hosting environments and credentials used in local development. In production, it's better to use a specific credential type so authentication is more predictable and easier to debug. `DefaultAzureCredential` attempts to authenticate via the following mechanisms in this order, stopping when one succeeds: - -![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg) - -1. **Environment** - `DefaultAzureCredential` will read account information specified via [environment variables](#environment-variables) and use it to authenticate. -1. **Workload Identity** - If the app is deployed on Kubernetes with environment variables set by the workload identity webhook, `DefaultAzureCredential` will authenticate the configured identity. -1. **Managed Identity** - If the app is deployed to an Azure host with managed identity enabled, `DefaultAzureCredential` will authenticate with it. -1. **Azure CLI** - If a user or service principal has authenticated via the Azure CLI `az login` command, `DefaultAzureCredential` will authenticate that identity. -1. **Azure Developer CLI** - If the developer has authenticated via the Azure Developer CLI `azd auth login` command, the `DefaultAzureCredential` will authenticate with that account. - -> Note: `DefaultAzureCredential` is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types. +`DefaultAzureCredential` simplifies authentication while developing apps that deploy to Azure by combining credentials used in Azure hosting environments with credentials used in local development. For more information, see [DefaultAzureCredential overview][dac_overview]. ## Managed Identity @@ -128,10 +118,10 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) ### Credential chains -|Credential|Usage -|-|- -|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps -|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials +|Credential|Usage|Reference +|-|-|- +|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps|[DefaultAzureCredential overview][dac_overview]| +|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials|[ChainedTokenCredential overview][ctc_overview]| ### Authenticating Azure-Hosted Applications @@ -156,7 +146,6 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |-|- |[InteractiveBrowserCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#InteractiveBrowserCredential)|Interactively authenticate a user with the default web browser |[DeviceCodeCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential)|Interactively authenticate a user on a device with limited UI -|[UsernamePasswordCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#UsernamePasswordCredential)|Authenticate a user with a username and password ### Authenticating via Development Tools @@ -169,7 +158,7 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) `DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables: -#### Service principal with secret +### Service principal with secret |variable name|value |-|- @@ -177,7 +166,7 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |`AZURE_TENANT_ID`|ID of the application's Microsoft Entra tenant |`AZURE_CLIENT_SECRET`|one of the application's client secrets -#### Service principal with certificate +### Service principal with certificate |variable name|value |-|- @@ -186,16 +175,7 @@ client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) |`AZURE_CLIENT_CERTIFICATE_PATH`|path to a certificate file including private key |`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any -#### Username and password - -|variable name|value -|-|- -|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application -|`AZURE_USERNAME`|a username (usually an email address) -|`AZURE_PASSWORD`|that user's password - -Configuration is attempted in the above order. For example, if values for a -client secret and certificate are both present, the client secret will be used. +Configuration is attempted in the above order. For example, if values for a client secret and certificate are both present, the client secret will be used. ## Token caching @@ -260,4 +240,8 @@ For more information, see the or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FREADME.png) + +[ctc_overview]: https://aka.ms/azsdk/go/identity/credential-chains#chainedtokencredential-overview +[dac_overview]: https://aka.ms/azsdk/go/identity/credential-chains#defaultazurecredential-overview + + diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD index e0bd09c636e..dd3f8e5b217 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TOKEN_CACHING.MD @@ -22,13 +22,12 @@ Some credential types support opt-in persistent token caching (see [the below ta Persistent caches are encrypted at rest using a mechanism that depends on the operating system: -| Operating system | Encryption facility | -|------------------|---------------------------------------| -| Linux | kernel key retention service (keyctl) | -| macOS | Keychain | -| Windows | Data Protection API (DPAPI) | - -Persistent caching requires encryption. When the required encryption facility is unuseable, or the application is running on an unsupported OS, the persistent cache constructor returns an error. This doesn't mean that authentication is impossible, only that credentials can't persist authentication data and the application will need to reauthenticate the next time it runs. See the [package documentation][example] for example code showing how to configure persistent caching and access cached data. +| Operating system | Encryption facility | Limitations | +| ---------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Linux | kernel key retention service (keyctl) | Cache data is lost on system shutdown because kernel keys are stored in memory. Depending on kernel compile options, data may also be lost on logout, or storage may be impossible because the key retention service isn't available. | +| macOS | Keychain | Building requires cgo and native build tools. Keychain access requires a graphical session, so persistent caching isn't possible in a headless environment such as an SSH session (macOS as host). | +| Windows | Data Protection API (DPAPI) | No specific limitations. | +Persistent caching requires encryption. When the required encryption facility is unuseable, or the application is running on an unsupported OS, the persistent cache constructor returns an error. This doesn't mean that authentication is impossible, only that credentials can't persist authentication data and the application will need to reauthenticate the next time it runs. See the package documentation for examples showing how to configure persistent caching and access cached data for [users][user_example] and [service principals][sp_example]. ### Credentials supporting token caching @@ -37,7 +36,7 @@ The following table indicates the state of in-memory and persistent caching in e **Note:** in-memory caching is enabled by default for every type supporting it. Persistent token caching must be enabled explicitly. See the [package documentation][user_example] for an example showing how to do this for credential types authenticating users. For types that authenticate service principals, set the `Cache` field on the constructor's options as shown in [this example][sp_example]. | Credential | In-memory token caching | Persistent token caching | -|--------------------------------|---------------------------------------------------------------------|--------------------------| +| ------------------------------ | ------------------------------------------------------------------- | ------------------------ | | `AzureCLICredential` | Not Supported | Not Supported | | `AzureDeveloperCLICredential` | Not Supported | Not Supported | | `AzurePipelinesCredential` | Supported | Supported | diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md index c24f67e84a7..9c4b1cd71c8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md @@ -8,6 +8,7 @@ This troubleshooting guide covers failure investigation techniques, common error - [Permission issues](#permission-issues) - [Find relevant information in errors](#find-relevant-information-in-errors) - [Enable and configure logging](#enable-and-configure-logging) +- [Troubleshoot persistent token caching issues](#troubleshoot-persistent-token-caching-issues) - [Troubleshoot AzureCLICredential authentication issues](#troubleshoot-azureclicredential-authentication-issues) - [Troubleshoot AzureDeveloperCLICredential authentication issues](#troubleshoot-azuredeveloperclicredential-authentication-issues) - [Troubleshoot AzurePipelinesCredential authentication issues](#troubleshoot-azurepipelinescredential-authentication-issues) @@ -236,6 +237,29 @@ azd auth token --output json --scope https://management.core.windows.net/.defaul | No service connection found with identifier |The `serviceConnectionID` argument to `NewAzurePipelinesCredential` is incorrect| Verify the service connection ID. This parameter refers to the `resourceId` of the Azure Service Connection. It can also be found in the query string of the service connection's configuration in Azure DevOps. [Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml) has more information about service connections.| |401 (Unauthorized) response from OIDC endpoint|The `systemAccessToken` argument to `NewAzurePipelinesCredential` is incorrect|Check pipeline configuration. This value comes from the predefined variable `System.AccessToken` [as described in Azure Pipelines documentation](https://learn.microsoft.com/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#systemaccesstoken).| +## Troubleshoot persistent token caching issues + +### macOS + +[azidentity/cache](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache) encrypts persistent caches with the system Keychain on macOS. You may see build and runtime errors there because calling the Keychain API requires cgo and macOS prohibits Keychain access in some scenarios. + +#### Build errors + +Build errors about undefined `accessor` symbols indicate that cgo wasn't enabled. For example: +``` +$ GOOS=darwin go build +# github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache +../../go/pkg/mod/github.com/!azure/azure-sdk-for-go/sdk/azidentity/cache@v0.3.0/darwin.go:18:19: undefined: accessor.New +../../go/pkg/mod/github.com/!azure/azure-sdk-for-go/sdk/azidentity/cache@v0.3.0/darwin.go:18:38: undefined: accessor.WithAccount +``` + +Try `go build` again with `CGO_ENABLED=1`. You may need to install native build tools. + +#### Runtime errors + +macOS prohibits Keychain access from environments without a GUI such as SSH sessions. If your application calls the persistent cache constructor ([cache.New](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache#New)) from an SSH session on a macOS host, you'll see an error like +`persistent storage isn't available due to error "User interaction is not allowed. (-25308)"`. This doesn't mean authentication is impossible, only that credentials can't persist data and the application must reauthenticate the next time it runs. + ## Get additional help Additional information on ways to reach out for support can be found in [SUPPORT.md](https://github.com/Azure/azure-sdk-for-go/blob/main/SUPPORT.md). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json index 045f87acd58..4118f99ef2c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "go", "TagPrefix": "go/azidentity", - "Tag": "go/azidentity_c55452bbf6" + "Tag": "go/azidentity_191110b0dd" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go index ce55dc658e3..bd196ddd32e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go @@ -22,6 +22,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" "github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" ) @@ -42,6 +43,8 @@ const ( developerSignOnClientID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" defaultSuffix = "/.default" + scopeLogFmt = "%s.GetToken() acquired a token for scope %q" + traceNamespace = "Microsoft.Entra" traceOpGetToken = "GetToken" traceOpAuthenticate = "Authenticate" @@ -103,7 +106,16 @@ func resolveAdditionalTenants(tenants []string) []string { return cp } -// resolveTenant returns the correct tenant for a token request +// resolveTenant returns the correct tenant for a token request, or "" when the calling credential doesn't +// have an explicitly configured tenant and the caller didn't specify a tenant for the token request. +// +// - defaultTenant: tenant set when constructing the credential, if any. "" is valid for credentials +// having an optional or implicit tenant such as dev tool and interactive user credentials. Those +// default to the tool's configured tenant or the user's home tenant, respectively. +// - specified: tenant specified for this token request i.e., TokenRequestOptions.TenantID. May be "". +// - credName: name of the calling credential type; for error messages +// - additionalTenants: optional allow list of tenants the credential may acquire tokens from in +// addition to defaultTenant i.e., the credential's AdditionallyAllowedTenants option func resolveTenant(defaultTenant, specified, credName string, additionalTenants []string) (string, error) { if specified == "" || specified == defaultTenant { return defaultTenant, nil @@ -119,6 +131,17 @@ func resolveTenant(defaultTenant, specified, credName string, additionalTenants return specified, nil } } + if len(additionalTenants) == 0 { + switch defaultTenant { + case "", organizationsTenantID: + // The application didn't specify a tenant or allow list when constructing the credential. Allow the + // tenant specified for this token request because we have nothing to compare it to (i.e., it vacuously + // satisfies the credential's configuration); don't know whether the application is multitenant; and + // don't want to return an error in the common case that the specified tenant matches the credential's + // default tenant determined elsewhere e.g., in some dev tool's configuration. + return specified, nil + } + } return "", fmt.Errorf(`%s isn't configured to acquire tokens for tenant %q. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to allow acquiring tokens for any tenant`, credName, specified) } @@ -186,6 +209,10 @@ type msalConfidentialClient interface { AcquireTokenOnBehalfOf(ctx context.Context, userAssertion string, scopes []string, options ...confidential.AcquireOnBehalfOfOption) (confidential.AuthResult, error) } +type msalManagedIdentityClient interface { + AcquireToken(context.Context, string, ...managedidentity.AcquireTokenOption) (managedidentity.AuthResult, error) +} + // enables fakes for test scenarios type msalPublicClient interface { AcquireTokenSilent(ctx context.Context, scopes []string, options ...public.AcquireSilentOption) (public.AuthResult, error) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go index b9976f5fede..36e359a099e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go @@ -30,9 +30,9 @@ type azTokenProvider func(ctx context.Context, scopes []string, tenant, subscrip // AzureCLICredentialOptions contains optional parameters for AzureCLICredential. type AzureCLICredentialOptions struct { - // AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition - // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the - // logged in account can access. + // AdditionallyAllowedTenants specifies tenants to which the credential may authenticate, in addition to + // TenantID. When TenantID is empty, this option has no effect and the credential will authenticate to + // any requested tenant. Add the wildcard value "*" to allow the credential to authenticate to any tenant. AdditionallyAllowedTenants []string // Subscription is the name or ID of a subscription. Set this to acquire tokens for an account other @@ -70,7 +70,11 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent } for _, r := range cp.Subscription { if !(alphanumeric(r) || r == '-' || r == '_' || r == ' ' || r == '.') { - return nil, fmt.Errorf("%s: invalid Subscription %q", credNameAzureCLI, cp.Subscription) + return nil, fmt.Errorf( + "%s: Subscription %q contains invalid characters. If this is the name of a subscription, use its ID instead", + credNameAzureCLI, + cp.Subscription, + ) } } if cp.TenantID != "" && !validTenantID(cp.TenantID) { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go index cbe7c4c2db1..46d0b551922 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_developer_cli_credential.go @@ -30,9 +30,9 @@ type azdTokenProvider func(ctx context.Context, scopes []string, tenant string) // AzureDeveloperCLICredentialOptions contains optional parameters for AzureDeveloperCLICredential. type AzureDeveloperCLICredentialOptions struct { - // AdditionallyAllowedTenants specifies tenants for which the credential may acquire tokens, in addition - // to TenantID. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the - // logged in account can access. + // AdditionallyAllowedTenants specifies tenants to which the credential may authenticate, in addition to + // TenantID. When TenantID is empty, this option has no effect and the credential will authenticate to + // any requested tenant. Add the wildcard value "*" to allow the credential to authenticate to any tenant. AdditionallyAllowedTenants []string // TenantID identifies the tenant the credential should authenticate in. Defaults to the azd environment, diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go index 2460f66ec1e..82342a02545 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go @@ -27,7 +27,10 @@ type ChainedTokenCredentialOptions struct { } // ChainedTokenCredential links together multiple credentials and tries them sequentially when authenticating. By default, -// it tries all the credentials until one authenticates, after which it always uses that credential. +// it tries all the credentials until one authenticates, after which it always uses that credential. For more information, +// see [ChainedTokenCredential overview]. +// +// [ChainedTokenCredential overview]: https://aka.ms/azsdk/go/identity/credential-chains#chainedtokencredential-overview type ChainedTokenCredential struct { cond *sync.Cond iterating bool @@ -46,6 +49,9 @@ func NewChainedTokenCredential(sources []azcore.TokenCredential, options *Chaine if source == nil { // cannot have a nil credential in the chain or else the application will panic when GetToken() is called on nil return nil, errors.New("sources cannot contain nil") } + if mc, ok := source.(*ManagedIdentityCredential); ok { + mc.mic.chained = true + } } cp := make([]azcore.TokenCredential, len(sources)) copy(cp, sources) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml index 62c12b5465f..c3af0cdc2d6 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml @@ -26,27 +26,16 @@ extends: parameters: CloudConfig: Public: - ServiceConnection: azure-sdk-tests - SubscriptionConfigurationFilePaths: - - eng/common/TestResources/sub-config/AzurePublicMsft.json SubscriptionConfigurations: - - $(sub-config-azure-cloud-test-resources) - $(sub-config-identity-test-resources) EnableRaceDetector: true + Location: westus2 RunLiveTests: true ServiceDirectory: azidentity UsePipelineProxy: false ${{ if endsWith(variables['Build.DefinitionName'], 'weekly') }}: - PreSteps: - - task: AzureCLI@2 - displayName: Set OIDC token - inputs: - addSpnToEnvironment: true - azureSubscription: azure-sdk-tests - inlineScript: Write-Host "##vso[task.setvariable variable=OIDC_TOKEN;]$($env:idToken)" - scriptLocation: inlineScript - scriptType: pscore + PersistOidcToken: true MatrixConfigs: - Name: managed_identity_matrix GenerateVMJobs: true diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go index 7059a510c22..58c4b585c15 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/confidential_client.go @@ -115,10 +115,10 @@ func (c *confidentialClient) GetToken(ctx context.Context, tro policy.TokenReque err = newAuthenticationFailedErrorFromMSAL(c.name, err) } } else { - msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", c.name, strings.Join(ar.GrantedScopes, ", ")) + msg := fmt.Sprintf(scopeLogFmt, c.name, strings.Join(ar.GrantedScopes, ", ")) log.Write(EventAuthentication, msg) } - return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC(), RefreshOn: ar.Metadata.RefreshOn.UTC()}, err } func (c *confidentialClient) client(tro policy.TokenRequestOptions) (msalConfidentialClient, *sync.Mutex, error) { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go index 3cfc0f7bf1d..14af271f6a1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go @@ -23,15 +23,19 @@ type DefaultAzureCredentialOptions struct { // to credential types that authenticate via external tools such as the Azure CLI. azcore.ClientOptions - // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire tokens. Add - // the wildcard value "*" to allow the credential to acquire tokens for any tenant. This value can also be - // set as a semicolon delimited list of tenants in the environment variable AZURE_ADDITIONALLY_ALLOWED_TENANTS. + // AdditionallyAllowedTenants specifies tenants to which the credential may authenticate, in addition to + // TenantID. When TenantID is empty, this option has no effect and the credential will authenticate to + // any requested tenant. Add the wildcard value "*" to allow the credential to authenticate to any tenant. + // This value can also be set as a semicolon delimited list of tenants in the environment variable + // AZURE_ADDITIONALLY_ALLOWED_TENANTS. AdditionallyAllowedTenants []string + // DisableInstanceDiscovery should be set true only by applications authenticating in disconnected clouds, or // private clouds such as Azure Stack. It determines whether the credential requests Microsoft Entra instance metadata // from https://login.microsoft.com before authenticating. Setting this to true will skip this request, making // the application responsible for ensuring the configured authority is valid and trustworthy. DisableInstanceDiscovery bool + // TenantID sets the default tenant for authentication via the Azure CLI and workload identity. TenantID string } @@ -39,7 +43,7 @@ type DefaultAzureCredentialOptions struct { // DefaultAzureCredential simplifies authentication while developing applications that deploy to Azure by // combining credentials used in Azure hosting environments and credentials used in local development. In // production, it's better to use a specific credential type so authentication is more predictable and easier -// to debug. +// to debug. For more information, see [DefaultAzureCredential overview]. // // DefaultAzureCredential attempts to authenticate with each of these credential types, in the following order, // stopping when one provides a token: @@ -55,6 +59,8 @@ type DefaultAzureCredentialOptions struct { // Consult the documentation for these credential types for more information on how they authenticate. // Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for // every subsequent authentication. +// +// [DefaultAzureCredential overview]: https://aka.ms/azsdk/go/identity/credential-chains#defaultazurecredential-overview type DefaultAzureCredential struct { chain *ChainedTokenCredential } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go index 53c4c728735..53ae9767f42 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go @@ -21,8 +21,9 @@ const credNameDeviceCode = "DeviceCodeCredential" type DeviceCodeCredentialOptions struct { azcore.ClientOptions - // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire - // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. + // AdditionallyAllowedTenants specifies tenants to which the credential may authenticate, in addition to + // TenantID. When TenantID is empty, this option has no effect and the credential will authenticate to + // any requested tenant. Add the wildcard value "*" to allow the credential to authenticate to any tenant. AdditionallyAllowedTenants []string // AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go index b30f5474f55..ec1eab05c55 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go @@ -60,7 +60,10 @@ type EnvironmentCredentialOptions struct { // Note that this credential uses [ParseCertificates] to load the certificate and key from the file. If this // function isn't able to parse your certificate, use [ClientCertificateCredential] instead. // -// # User with username and password +// # Deprecated: User with username and password +// +// User password authentication is deprecated because it can't support multifactor authentication. See +// [Entra ID documentation] for migration guidance. // // AZURE_TENANT_ID: (optional) tenant to authenticate in. Defaults to "organizations". // @@ -75,6 +78,8 @@ type EnvironmentCredentialOptions struct { // To enable multitenant authentication, set AZURE_ADDITIONALLY_ALLOWED_TENANTS with a semicolon delimited list of tenants // the credential may request tokens from in addition to the tenant specified by AZURE_TENANT_ID. Set // AZURE_ADDITIONALLY_ALLOWED_TENANTS to "*" to enable the credential to request a token from any tenant. +// +// [Entra ID documentation]: https://aka.ms/azsdk/identity/mfa type EnvironmentCredential struct { cred azcore.TokenCredential } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work index 04ea962b422..6dd5b3d64da 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/go.work @@ -1,4 +1,4 @@ -go 1.18 +go 1.23.0 use ( . diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go index 848db16e435..ec89de9b5b2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go @@ -20,8 +20,9 @@ const credNameBrowser = "InteractiveBrowserCredential" type InteractiveBrowserCredentialOptions struct { azcore.ClientOptions - // AdditionallyAllowedTenants specifies additional tenants for which the credential may acquire - // tokens. Add the wildcard value "*" to allow the credential to acquire tokens for any tenant. + // AdditionallyAllowedTenants specifies tenants to which the credential may authenticate, in addition to + // TenantID. When TenantID is empty, this option has no effect and the credential will authenticate to + // any requested tenant. Add the wildcard value "*" to allow the credential to authenticate to any tenant. AdditionallyAllowedTenants []string // AuthenticationRecord returned by a call to a credential's Authenticate method. Set this option diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed-identity-matrix.json b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed-identity-matrix.json index 1c3791777a1..edd56f9d571 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed-identity-matrix.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed-identity-matrix.json @@ -9,7 +9,7 @@ } }, "GoVersion": [ - "1.22.1" + "env:GO_VERSION_PREVIOUS" ], "IDENTITY_IMDS_AVAILABLE": "1" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go index 4c657a92ec5..b3a0f85883f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go @@ -8,24 +8,18 @@ package azidentity import ( "context" - "encoding/json" "errors" "fmt" "net/http" - "net/url" - "os" - "path/filepath" - "runtime" - "strconv" "strings" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "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/internal/log" - "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + msalerrors "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity" ) const ( @@ -41,56 +35,20 @@ const ( msiResID = "msi_res_id" msiSecret = "MSI_SECRET" imdsAPIVersion = "2018-02-01" - azureArcAPIVersion = "2019-08-15" + azureArcAPIVersion = "2020-06-01" qpClientID = "client_id" serviceFabricAPIVersion = "2019-07-01-preview" ) var imdsProbeTimeout = time.Second -type msiType int - -const ( - msiTypeAppService msiType = iota - msiTypeAzureArc - msiTypeAzureML - msiTypeCloudShell - msiTypeIMDS - msiTypeServiceFabric -) - type managedIdentityClient struct { - azClient *azcore.Client - endpoint string - id ManagedIDKind - msiType msiType - probeIMDS bool -} - -// arcKeyDirectory returns the directory expected to contain Azure Arc keys -var arcKeyDirectory = func() (string, error) { - switch runtime.GOOS { - case "linux": - return "/var/opt/azcmagent/tokens", nil - case "windows": - pd := os.Getenv("ProgramData") - if pd == "" { - return "", errors.New("environment variable ProgramData has no value") - } - return filepath.Join(pd, "AzureConnectedMachineAgent", "Tokens"), nil - default: - return "", fmt.Errorf("unsupported OS %q", runtime.GOOS) - } -} - -type wrappedNumber json.Number - -func (n *wrappedNumber) UnmarshalJSON(b []byte) error { - c := string(b) - if c == "\"\"" { - return nil - } - return json.Unmarshal(b, (*json.Number)(n)) + azClient *azcore.Client + imds, probeIMDS, userAssigned bool + // chained indicates whether the client is part of a credential chain. If true, the client will return + // a credentialUnavailableError instead of an AuthenticationFailedError for an unexpected IMDS response. + chained bool + msalClient msalManagedIdentityClient } // setIMDSRetryOptionDefaults sets zero-valued fields to default values appropriate for IMDS @@ -138,51 +96,20 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag options = &ManagedIdentityCredentialOptions{} } cp := options.ClientOptions - c := managedIdentityClient{id: options.ID, endpoint: imdsEndpoint, msiType: msiTypeIMDS} - env := "IMDS" - if endpoint, ok := os.LookupEnv(identityEndpoint); ok { - if _, ok := os.LookupEnv(identityHeader); ok { - if _, ok := os.LookupEnv(identityServerThumbprint); ok { - if options.ID != nil { - return nil, errors.New("the Service Fabric API doesn't support specifying a user-assigned managed identity at runtime") - } - env = "Service Fabric" - c.endpoint = endpoint - c.msiType = msiTypeServiceFabric - } else { - env = "App Service" - c.endpoint = endpoint - c.msiType = msiTypeAppService - } - } else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok { - if options.ID != nil { - return nil, errors.New("the Azure Arc API doesn't support specifying a user-assigned managed identity at runtime") - } - env = "Azure Arc" - c.endpoint = endpoint - c.msiType = msiTypeAzureArc - } - } else if endpoint, ok := os.LookupEnv(msiEndpoint); ok { - c.endpoint = endpoint - if _, ok := os.LookupEnv(msiSecret); ok { - if options.ID != nil && options.ID.idKind() != miClientID { - return nil, errors.New("the Azure ML API supports specifying a user-assigned managed identity by client ID only") - } - env = "Azure ML" - c.msiType = msiTypeAzureML - } else { - if options.ID != nil { - return nil, errors.New("the Cloud Shell API doesn't support user-assigned managed identities") - } - env = "Cloud Shell" - c.msiType = msiTypeCloudShell - } - } else { + c := managedIdentityClient{} + source, err := managedidentity.GetSource() + if err != nil { + return nil, err + } + env := string(source) + if source == managedidentity.DefaultToIMDS { + env = "IMDS" + c.imds = true c.probeIMDS = options.dac setIMDSRetryOptionDefaults(&cp.Retry) } - client, err := azcore.NewClient(module, version, azruntime.PipelineOptions{ + c.azClient, err = azcore.NewClient(module, version, azruntime.PipelineOptions{ Tracing: azruntime.TracingOptions{ Namespace: traceNamespace, }, @@ -190,77 +117,95 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag if err != nil { return nil, err } - c.azClient = client + + id := managedidentity.SystemAssigned() + if options.ID != nil { + c.userAssigned = true + switch s := options.ID.String(); options.ID.idKind() { + case miClientID: + id = managedidentity.UserAssignedClientID(s) + case miObjectID: + id = managedidentity.UserAssignedObjectID(s) + case miResourceID: + id = managedidentity.UserAssignedResourceID(s) + } + } + msalClient, err := managedidentity.New(id, managedidentity.WithHTTPClient(&c), managedidentity.WithRetryPolicyDisabled()) + if err != nil { + return nil, err + } + c.msalClient = &msalClient if log.Should(EventAuthentication) { - log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env) + msg := fmt.Sprintf("%s will use %s managed identity", credNameManagedIdentity, env) + if options.ID != nil { + kind := "client" + switch options.ID.(type) { + case ObjectID: + kind = "object" + case ResourceID: + kind = "resource" + } + msg += fmt.Sprintf(" with %s ID %q", kind, options.ID.String()) + } + log.Write(EventAuthentication, msg) } return &c, nil } -// provideToken acquires a token for MSAL's confidential.Client, which caches the token -func (c *managedIdentityClient) provideToken(ctx context.Context, params confidential.TokenProviderParameters) (confidential.TokenProviderResult, error) { - result := confidential.TokenProviderResult{} - tk, err := c.authenticate(ctx, c.id, params.Scopes) - if err == nil { - result.AccessToken = tk.Token - result.ExpiresInSeconds = int(time.Until(tk.ExpiresOn).Seconds()) - } - return result, err +func (*managedIdentityClient) CloseIdleConnections() { + // do nothing +} + +func (c *managedIdentityClient) Do(r *http.Request) (*http.Response, error) { + return doForClient(c.azClient, r) } // authenticate acquires an access token -func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKind, scopes []string) (azcore.AccessToken, error) { +func (c *managedIdentityClient) GetToken(ctx context.Context, tro policy.TokenRequestOptions) (azcore.AccessToken, error) { // no need to synchronize around this value because it's true only when DefaultAzureCredential constructed the client, // and in that case ChainedTokenCredential.GetToken synchronizes goroutines that would execute this block if c.probeIMDS { + // send a malformed request (no Metadata header) to IMDS to determine whether the endpoint is available cx, cancel := context.WithTimeout(ctx, imdsProbeTimeout) defer cancel() cx = policy.WithRetryOptions(cx, policy.RetryOptions{MaxRetries: -1}) - req, err := azruntime.NewRequest(cx, http.MethodGet, c.endpoint) + req, err := azruntime.NewRequest(cx, http.MethodGet, imdsEndpoint) if err != nil { return azcore.AccessToken{}, fmt.Errorf("failed to create IMDS probe request: %s", err) } - res, err := c.azClient.Pipeline().Do(req) - if err != nil { + if _, err = c.azClient.Pipeline().Do(req); err != nil { msg := err.Error() if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { msg = "managed identity timed out. See https://aka.ms/azsdk/go/identity/troubleshoot#dac for more information" } return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg) } - // because IMDS always responds with JSON, assume a non-JSON response is from something else, such - // as a proxy, and return credentialUnavailableError so DefaultAzureCredential continues iterating - b, err := azruntime.Payload(res) - if err != nil { - return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, fmt.Sprintf("failed to read IMDS probe response: %s", err)) - } - if !json.Valid(b) { - return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, "unexpected response to IMDS probe") - } - // send normal token requests from now on because IMDS responded + // send normal token requests from now on because something responded c.probeIMDS = false } - msg, err := c.createAuthRequest(ctx, id, scopes) - if err != nil { - return azcore.AccessToken{}, err - } - - resp, err := c.azClient.Pipeline().Do(msg) - if err != nil { - return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil) - } - - if azruntime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { - return c.createAccessToken(resp) - } - - if c.msiType == msiTypeIMDS { + ar, err := c.msalClient.AcquireToken(ctx, tro.Scopes[0], managedidentity.WithClaims(tro.Claims)) + if err == nil { + msg := fmt.Sprintf(scopeLogFmt, credNameManagedIdentity, strings.Join(ar.GrantedScopes, ", ")) + log.Write(EventAuthentication, msg) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC(), RefreshOn: ar.Metadata.RefreshOn.UTC()}, err + } + if c.imds { + var ije msalerrors.InvalidJsonErr + if c.chained && errors.As(err, &ije) { + // an unmarshaling error implies the response is from something other than IMDS such as a proxy listening at + // the same address. Return a credentialUnavailableError so credential chains continue to their next credential + return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, err.Error()) + } + resp := getResponseFromError(err) + if resp == nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSAL(credNameManagedIdentity, err) + } switch resp.StatusCode { case http.StatusBadRequest: - if id != nil { + if c.userAssigned { return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp) } msg := "failed to authenticate a system assigned identity" @@ -277,229 +222,6 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi } } } - - return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "", resp) -} - -func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) { - value := struct { - // these are the only fields that we use - Token string `json:"access_token,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` - ExpiresIn wrappedNumber `json:"expires_in,omitempty"` // this field should always return the number of seconds for which a token is valid - ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string - }{} - if err := azruntime.UnmarshalAsJSON(res, &value); err != nil { - return azcore.AccessToken{}, fmt.Errorf("internal AccessToken: %v", err) - } - if value.ExpiresIn != "" { - expiresIn, err := json.Number(value.ExpiresIn).Int64() - if err != nil { - return azcore.AccessToken{}, err - } - return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Now().Add(time.Second * time.Duration(expiresIn)).UTC()}, nil - } - switch v := value.ExpiresOn.(type) { - case float64: - return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(v), 0).UTC()}, nil - case string: - if expiresOn, err := strconv.Atoi(v); err == nil { - return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil - } - return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res) - default: - msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v) - return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res) - } -} - -func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { - switch c.msiType { - case msiTypeIMDS: - return c.createIMDSAuthRequest(ctx, id, scopes) - case msiTypeAppService: - return c.createAppServiceAuthRequest(ctx, id, scopes) - case msiTypeAzureArc: - // need to perform preliminary request to retreive the secret key challenge provided by the HIMDS service - key, err := c.getAzureArcSecretKey(ctx, scopes) - if err != nil { - msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err) - return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil) - } - return c.createAzureArcAuthRequest(ctx, scopes, key) - case msiTypeAzureML: - return c.createAzureMLAuthRequest(ctx, id, scopes) - case msiTypeServiceFabric: - return c.createServiceFabricAuthRequest(ctx, scopes) - case msiTypeCloudShell: - return c.createCloudShellAuthRequest(ctx, scopes) - default: - return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment") - } -} - -func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return nil, err - } - request.Raw().Header.Set(headerMetadata, "true") - q := request.Raw().URL.Query() - q.Set("api-version", imdsAPIVersion) - q.Set("resource", strings.Join(scopes, " ")) - if id != nil { - switch id.idKind() { - case miClientID: - q.Set(qpClientID, id.String()) - case miObjectID: - q.Set("object_id", id.String()) - case miResourceID: - q.Set(msiResID, id.String()) - } - } - request.Raw().URL.RawQuery = q.Encode() - return request, nil -} - -func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return nil, err - } - request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader)) - q := request.Raw().URL.Query() - q.Set("api-version", "2019-08-01") - q.Set("resource", scopes[0]) - if id != nil { - switch id.idKind() { - case miClientID: - q.Set(qpClientID, id.String()) - case miObjectID: - q.Set("principal_id", id.String()) - case miResourceID: - q.Set(miResID, id.String()) - } - } - request.Raw().URL.RawQuery = q.Encode() - return request, nil -} - -func (c *managedIdentityClient) createAzureMLAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return nil, err - } - request.Raw().Header.Set("secret", os.Getenv(msiSecret)) - q := request.Raw().URL.Query() - q.Set("api-version", "2017-09-01") - q.Set("resource", strings.Join(scopes, " ")) - q.Set("clientid", os.Getenv(defaultIdentityClientID)) - if id != nil { - switch id.idKind() { - case miClientID: - q.Set("clientid", id.String()) - case miObjectID: - return nil, newAuthenticationFailedError(credNameManagedIdentity, "Azure ML doesn't support specifying a managed identity by object ID", nil) - case miResourceID: - return nil, newAuthenticationFailedError(credNameManagedIdentity, "Azure ML doesn't support specifying a managed identity by resource ID", nil) - } - } - request.Raw().URL.RawQuery = q.Encode() - return request, nil -} - -func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, scopes []string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return nil, err - } - q := request.Raw().URL.Query() - request.Raw().Header.Set("Accept", "application/json") - request.Raw().Header.Set("Secret", os.Getenv(identityHeader)) - q.Set("api-version", serviceFabricAPIVersion) - q.Set("resource", strings.Join(scopes, " ")) - request.Raw().URL.RawQuery = q.Encode() - return request, nil -} - -func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resources []string) (string, error) { - // create the request to retreive the secret key challenge provided by the HIMDS service - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return "", err - } - request.Raw().Header.Set(headerMetadata, "true") - q := request.Raw().URL.Query() - q.Set("api-version", azureArcAPIVersion) - q.Set("resource", strings.Join(resources, " ")) - request.Raw().URL.RawQuery = q.Encode() - // send the initial request to get the short-lived secret key - response, err := c.azClient.Pipeline().Do(request) - if err != nil { - return "", err - } - // the endpoint is expected to return a 401 with the WWW-Authenticate header set to the location - // of the secret key file. Any other status code indicates an error in the request. - if response.StatusCode != 401 { - msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode) - return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response) - } - header := response.Header.Get("WWW-Authenticate") - if len(header) == 0 { - return "", newAuthenticationFailedError(credNameManagedIdentity, "HIMDS response has no WWW-Authenticate header", nil) - } - // the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key - _, p, found := strings.Cut(header, "=") - if !found { - return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected WWW-Authenticate header from HIMDS: "+header, nil) - } - expected, err := arcKeyDirectory() - if err != nil { - return "", err - } - if filepath.Dir(p) != expected || !strings.HasSuffix(p, ".key") { - return "", newAuthenticationFailedError(credNameManagedIdentity, "unexpected file path from HIMDS service: "+p, nil) - } - f, err := os.Stat(p) - if err != nil { - return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not stat %q: %v", p, err), nil) - } - if s := f.Size(); s > 4096 { - return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("key is too large (%d bytes)", s), nil) - } - key, err := os.ReadFile(p) - if err != nil { - return "", newAuthenticationFailedError(credNameManagedIdentity, fmt.Sprintf("could not read %q: %v", p, err), nil) - } - return string(key), nil -} - -func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, resources []string, key string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodGet, c.endpoint) - if err != nil { - return nil, err - } - request.Raw().Header.Set(headerMetadata, "true") - request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key)) - q := request.Raw().URL.Query() - q.Set("api-version", azureArcAPIVersion) - q.Set("resource", strings.Join(resources, " ")) - request.Raw().URL.RawQuery = q.Encode() - return request, nil -} - -func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, scopes []string) (*policy.Request, error) { - request, err := azruntime.NewRequest(ctx, http.MethodPost, c.endpoint) - if err != nil { - return nil, err - } - request.Raw().Header.Set(headerMetadata, "true") - data := url.Values{} - data.Set("resource", strings.Join(scopes, " ")) - dataEncoded := data.Encode() - body := streaming.NopCloser(strings.NewReader(dataEncoded)) - if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil { - return nil, err - } - return request, nil + err = newAuthenticationFailedErrorFromMSAL(credNameManagedIdentity, err) + return azcore.AccessToken{}, err } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go index 1d53579cf3e..11b686ccdac 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go @@ -14,7 +14,6 @@ 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/AzureAD/microsoft-authentication-library-for-go/apps/confidential" ) const credNameManagedIdentity = "ManagedIdentityCredential" @@ -110,8 +109,7 @@ type ManagedIdentityCredentialOptions struct { // // [Azure managed identity]: https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview type ManagedIdentityCredential struct { - client *confidentialClient - mic *managedIdentityClient + mic *managedIdentityClient } // NewManagedIdentityCredential creates a ManagedIdentityCredential. Pass nil to accept default options. @@ -123,38 +121,22 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M if err != nil { return nil, err } - cred := confidential.NewCredFromTokenProvider(mic.provideToken) - - // It's okay to give MSAL an invalid client ID because MSAL will use it only as part of a cache key. - // ManagedIdentityClient handles all the details of authentication and won't receive this value from MSAL. - clientID := "SYSTEM-ASSIGNED-MANAGED-IDENTITY" - if options.ID != nil { - clientID = options.ID.String() - } - // similarly, it's okay to give MSAL an incorrect tenant because MSAL won't use the value - c, err := newConfidentialClient("common", clientID, credNameManagedIdentity, cred, confidentialClientOptions{ - ClientOptions: options.ClientOptions, - }) - if err != nil { - return nil, err - } - return &ManagedIdentityCredential{client: c, mic: mic}, nil + return &ManagedIdentityCredential{mic: mic}, nil } // GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients. func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { var err error - ctx, endSpan := runtime.StartSpan(ctx, credNameManagedIdentity+"."+traceOpGetToken, c.client.azClient.Tracer(), nil) + ctx, endSpan := runtime.StartSpan(ctx, credNameManagedIdentity+"."+traceOpGetToken, c.mic.azClient.Tracer(), nil) defer func() { endSpan(err) }() if len(opts.Scopes) != 1 { err = fmt.Errorf("%s.GetToken() requires exactly one scope", credNameManagedIdentity) return azcore.AccessToken{}, err } - // managed identity endpoints require a Microsoft Entra ID v1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here + // managed identity endpoints require a v1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here opts.Scopes = []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)} - tk, err := c.client.GetToken(ctx, opts) - return tk, err + return c.mic.GetToken(ctx, opts) } var _ azcore.TokenCredential = (*ManagedIdentityCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go index 73363e1c9e7..053d1785f81 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/public_client.go @@ -154,12 +154,7 @@ func (p *publicClient) GetToken(ctx context.Context, tro policy.TokenRequestOpti if p.opts.DisableAutomaticAuthentication { return azcore.AccessToken{}, newAuthenticationRequiredError(p.name, tro) } - at, err := p.reqToken(ctx, client, tro) - if err == nil { - msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %q", p.name, strings.Join(ar.GrantedScopes, ", ")) - log.Write(EventAuthentication, msg) - } - return at, err + return p.reqToken(ctx, client, tro) } // reqToken requests a token from the MSAL public client. It's separate from GetToken() to enable Authenticate() to bypass the cache. @@ -242,11 +237,13 @@ func (p *publicClient) newMSALClient(enableCAE bool) (msalPublicClient, error) { func (p *publicClient) token(ar public.AuthResult, err error) (azcore.AccessToken, error) { if err == nil { + msg := fmt.Sprintf(scopeLogFmt, p.name, strings.Join(ar.GrantedScopes, ", ")) + log.Write(EventAuthentication, msg) p.record, err = newAuthenticationRecord(ar) } else { err = newAuthenticationFailedErrorFromMSAL(p.name, err) } - return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC(), RefreshOn: ar.Metadata.RefreshOn.UTC()}, err } // resolveTenant returns the correct WithTenantID() argument for a token request given the client's diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-post.ps1 b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-post.ps1 index 1a07fede637..67f97fbb2b0 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-post.ps1 +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/test-resources-post.ps1 @@ -7,6 +7,10 @@ param ( [hashtable] $AdditionalParameters = @{}, [hashtable] $DeploymentOutputs, + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string] $SubscriptionId, + [Parameter(ParameterSetName = 'Provisioner', Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $TenantId, @@ -15,6 +19,10 @@ param ( [ValidatePattern('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')] [string] $TestApplicationId, + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string] $Environment, + # Captures any arguments from eng/New-TestResources.ps1 not declared here (no parameter errors). [Parameter(ValueFromRemainingArguments = $true)] $RemainingArguments @@ -28,8 +36,9 @@ if ($CI) { Write-Host "Skipping post-provisioning script because resources weren't deployed" return } - az login --federated-token $env:OIDC_TOKEN --service-principal -t $TenantId -u $TestApplicationId - az account set --subscription $DeploymentOutputs['AZIDENTITY_SUBSCRIPTION_ID'] + az cloud set -n $Environment + az login --federated-token $env:ARM_OIDC_TOKEN --service-principal -t $TenantId -u $TestApplicationId + az account set --subscription $SubscriptionId } Write-Host "Building container" @@ -62,6 +71,10 @@ $aciName = "azidentity-test" az container create -g $rg -n $aciName --image $image ` --acr-identity $($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY']) ` --assign-identity [system] $($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY']) ` + --cpu 1 ` + --ip-address Public ` + --memory 1.0 ` + --os-type Linux ` --role "Storage Blob Data Reader" ` --scope $($DeploymentOutputs['AZIDENTITY_STORAGE_ID']) ` -e AZIDENTITY_STORAGE_NAME=$($DeploymentOutputs['AZIDENTITY_STORAGE_NAME']) ` @@ -70,7 +83,8 @@ az container create -g $rg -n $aciName --image $image ` AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY_CLIENT_ID']) ` AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID=$($DeploymentOutputs['AZIDENTITY_USER_ASSIGNED_IDENTITY_OBJECT_ID']) ` FUNCTIONS_CUSTOMHANDLER_PORT=80 -Write-Host "##vso[task.setvariable variable=AZIDENTITY_ACI_NAME;]$aciName" +$aciIP = az container show -g $rg -n $aciName --query ipAddress.ip --output tsv +Write-Host "##vso[task.setvariable variable=AZIDENTITY_ACI_IP;]$aciIP" # Azure Functions deployment: copy the Windows binary from the Docker image, deploy it in a zip Write-Host "Deploying to Azure Functions" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go index 740abd47094..5791e7d2240 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go @@ -17,6 +17,11 @@ import ( const credNameUserPassword = "UsernamePasswordCredential" // UsernamePasswordCredentialOptions contains optional parameters for UsernamePasswordCredential. +// +// Deprecated: UsernamePasswordCredential is deprecated because it can't support multifactor +// authentication. See [Entra ID documentation] for migration guidance. +// +// [Entra ID documentation]: https://aka.ms/azsdk/identity/mfa type UsernamePasswordCredentialOptions struct { azcore.ClientOptions @@ -43,8 +48,13 @@ type UsernamePasswordCredentialOptions struct { // UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, // because it's less secure than other authentication flows. This credential is not interactive, so it isn't compatible -// with any form of multi-factor authentication, and the application must already have user or admin consent. +// with any form of multifactor authentication, and the application must already have user or admin consent. // This credential can only authenticate work and school accounts; it can't authenticate Microsoft accounts. +// +// Deprecated: this credential is deprecated because it can't support multifactor authentication. See [Entra ID documentation] +// for migration guidance. +// +// [Entra ID documentation]: https://aka.ms/azsdk/identity/mfa type UsernamePasswordCredential struct { client *publicClient } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go index 4fa22dcc121..584aabe1cbd 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go @@ -14,5 +14,5 @@ const ( module = "github.com/Azure/azure-sdk-for-go/sdk/" + component // Version is the semantic version (see http://semver.org) of this module. - version = "v1.8.0" + version = "v1.9.0" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go index 4f1dcf1b78a..76dadf7d351 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go @@ -44,7 +44,7 @@ func Should(cls Event) bool { if log.lst == nil { return false } - if log.cls == nil || len(log.cls) == 0 { + if len(log.cls) == 0 { return true } for _, c := range log.cls { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go index 238ef42ed03..02aa1fb3bc8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go @@ -11,9 +11,17 @@ import ( "time" ) +// backoff sets a minimum wait time between eager update attempts. It's a variable so tests can manipulate it. +var backoff = func(now, lastAttempt time.Time) bool { + return lastAttempt.Add(30 * time.Second).After(now) +} + // AcquireResource abstracts a method for refreshing a temporal resource. type AcquireResource[TResource, TState any] func(state TState) (newResource TResource, newExpiration time.Time, err error) +// ShouldRefresh abstracts a method for indicating whether a resource should be refreshed before expiration. +type ShouldRefresh[TResource, TState any] func(TResource, TState) bool + // Resource is a temporal resource (usually a credential) that requires periodic refreshing. type Resource[TResource, TState any] struct { // cond is used to synchronize access to the shared resource embodied by the remaining fields @@ -31,24 +39,43 @@ type Resource[TResource, TState any] struct { // lastAttempt indicates when a thread/goroutine last attempted to acquire/update the resource lastAttempt time.Time + // shouldRefresh indicates whether the resource should be refreshed before expiration + shouldRefresh ShouldRefresh[TResource, TState] + // acquireResource is the callback function that actually acquires the resource acquireResource AcquireResource[TResource, TState] } // NewResource creates a new Resource that uses the specified AcquireResource for refreshing. func NewResource[TResource, TState any](ar AcquireResource[TResource, TState]) *Resource[TResource, TState] { - return &Resource[TResource, TState]{cond: sync.NewCond(&sync.Mutex{}), acquireResource: ar} + r := &Resource[TResource, TState]{acquireResource: ar, cond: sync.NewCond(&sync.Mutex{})} + r.shouldRefresh = r.expiringSoon + return r +} + +// ResourceOptions contains optional configuration for Resource +type ResourceOptions[TResource, TState any] struct { + // ShouldRefresh indicates whether [Resource.Get] should acquire an updated resource despite + // the currently held resource not having expired. [Resource.Get] ignores all errors from + // refresh attempts triggered by ShouldRefresh returning true, and doesn't call ShouldRefresh + // when the resource has expired (it unconditionally updates expired resources). When + // ShouldRefresh is nil, [Resource.Get] refreshes the resource if it will expire within 5 + // minutes. + ShouldRefresh ShouldRefresh[TResource, TState] +} + +// NewResourceWithOptions creates a new Resource that uses the specified AcquireResource for refreshing. +func NewResourceWithOptions[TResource, TState any](ar AcquireResource[TResource, TState], opts ResourceOptions[TResource, TState]) *Resource[TResource, TState] { + r := NewResource(ar) + if opts.ShouldRefresh != nil { + r.shouldRefresh = opts.ShouldRefresh + } + return r } // Get returns the underlying resource. // If the resource is fresh, no refresh is performed. func (er *Resource[TResource, TState]) Get(state TState) (TResource, error) { - // If the resource is expiring within this time window, update it eagerly. - // This allows other threads/goroutines to keep running by using the not-yet-expired - // resource value while one thread/goroutine updates the resource. - const window = 5 * time.Minute // This example updates the resource 5 minutes prior to expiration - const backoff = 30 * time.Second // Minimum wait time between eager update attempts - now, acquire, expired := time.Now(), false, false // acquire exclusive lock @@ -65,9 +92,8 @@ func (er *Resource[TResource, TState]) Get(state TState) (TResource, error) { break } // Getting here means that this thread/goroutine will wait for the updated resource - } else if er.expiration.Add(-window).Before(now) { - // The resource is valid but is expiring within the time window - if !er.acquiring && er.lastAttempt.Add(backoff).Before(now) { + } else if er.shouldRefresh(resource, state) { + if !(er.acquiring || backoff(now, er.lastAttempt)) { // If another thread/goroutine is not acquiring/renewing the resource, and none has attempted // to do so within the last 30 seconds, this thread/goroutine will do it er.acquiring, acquire = true, true @@ -121,3 +147,8 @@ func (er *Resource[TResource, TState]) Expire() { // Reset the expiration as if we never got this resource to begin with er.expiration = time.Time{} } + +func (er *Resource[TResource, TState]) expiringSoon(TResource, TState) bool { + // call time.Now() instead of using Get's value so ShouldRefresh doesn't need a time.Time parameter + return er.expiration.Add(-5 * time.Minute).Before(time.Now()) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/CHANGELOG.md index d99490438cb..8b0a775a34b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/CHANGELOG.md @@ -1,5 +1,10 @@ # Release History +## 1.3.1 (2025-02-13) + +### Other Changes +* Upgraded dependencies + ## 1.3.0 (2024-11-06) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/README.md index 709fe30050f..fdaa5a8e723 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/README.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/README.md @@ -57,7 +57,7 @@ func main() { ### Keys -Azure Key Vault can create and store RSA and elliptic curve keys. Both can optionally be protected by hardware security modules (HSMs). Azure Key Vault can also perform cryptographic operations with them. For more information about keys and supported operations and algorithms, see the [Key Vault documentation](https://docs.microsoft.com/azure/key-vault/keys/about-keys). +Azure Key Vault can create and store RSA and elliptic curve keys. Both can optionally be protected by hardware security modules (HSMs). Azure Key Vault can also perform cryptographic operations with them. For more information about keys and supported operations and algorithms, see the [Key Vault documentation](https://learn.microsoft.com/azure/key-vault/keys/about-keys). [Client][client_docs] can create keys in the vault, get existing keys from the vault, update key metadata, and delete keys, as shown in the examples below. @@ -131,17 +131,17 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [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_keyvault_cli]: https://learn.microsoft.com/azure/key-vault/general/quick-create-cli +[azure_keyvault_portal]: https://learn.microsoft.com/azure/key-vault/general/quick-create-portal [azure_sub]: https://azure.microsoft.com/free/ [default_cred_ref]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#NewDefaultAzureCredential [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -[keyvault_docs]: https://docs.microsoft.com/azure/key-vault/ +[keyvault_docs]: https://learn.microsoft.com/azure/key-vault/ [goget_azkeys]: https://aka.ms/azsdk/go/keyvault-keys/docs [reference_docs]: https://aka.ms/azsdk/go/keyvault-keys/docs [client_docs]: https://aka.ms/azsdk/go/keyvault-keys/docs#Client [key_client_src]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/security/keyvault/azkeys/client.go [keys_samples]: https://aka.ms/azsdk/go/keyvault-keys/docs#pkg-examples -[managed_identity]: https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview +[managed_identity]: https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview + -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fsecurity%2Fkeyvault%2Fazkeys%2FREADME.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/autorest.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/autorest.md deleted file mode 100644 index b067fd8013f..00000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/autorest.md +++ /dev/null @@ -1,252 +0,0 @@ -## Go - -```yaml -clear-output-folder: false -export-clients: true -go: true -input-file: https://github.com/Azure/azure-rest-api-specs/blob/7452e1cc7db72fbc6cd9539b390d8b8e5c2a1864/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.5/keys.json -license-header: MICROSOFT_MIT_NO_VERSION -module: github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys -openapi-type: "data-plane" -output-folder: ../azkeys -override-client-name: Client -security: "AADToken" -security-scopes: "https://vault.azure.net/.default" -use: "@autorest/go@4.0.0-preview.59" -inject-spans: true -version: "^3.0.0" - -directive: - # delete unused models - - remove-model: KeyExportParameters - - remove-model: KeyProperties - - # 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: KeyCreateParameters - to: CreateKeyParameters - - rename-model: - from: KeyExportParameters - to: ExportKeyParameters - - rename-model: - from: KeyImportParameters - to: ImportKeyParameters - - rename-model: - from: KeyReleaseParameters - to: ReleaseParameters - - rename-model: - from: KeyRestoreParameters - to: RestoreKeyParameters - - rename-model: - from: KeySignParameters - to: SignParameters - - rename-model: - from: KeyUpdateParameters - to: UpdateKeyParameters - - rename-model: - from: KeyVerifyParameters - to: VerifyParameters - - rename-model: - from: GetRandomBytesRequest - to: GetRandomBytesParameters - - # rename paged operations from Get* to List* - - rename-operation: - from: GetDeletedKeys - to: ListDeletedKeyProperties - - rename-operation: - from: GetKeys - to: ListKeyProperties - - rename-operation: - from: GetKeyVersions - to: ListKeyPropertiesVersions - - # rename KeyItem and KeyBundle - - rename-model: - from: DeletedKeyBundle - to: DeletedKey - - rename-model: - from: KeyItem - to: KeyProperties - - rename-model: - from: DeletedKeyItem - to: DeletedKeyProperties - - rename-model: - from: DeletedKeyListResult - to: DeletedKeyPropertiesListResult - - rename-model: - from: KeyListResult - to: KeyPropertiesListResult - - from: swagger-document - where: $.definitions.RestoreKeyParameters.properties.value - transform: $["x-ms-client-name"] = "KeyBackup" - - # Change LifetimeActions to LifetimeAction - - rename-model: - from: LifetimeActions - to: LifetimeAction - - rename-model: - from: LifetimeActionsType - to: LifetimeActionType - - rename-model: - from: LifetimeActionsTrigger - to: LifetimeActionTrigger - - # Rename HsmPlatform to HSMPlatform for consistency - - where-model: KeyAttributes - rename-property: - from: hsmPlatform - to: HSMPlatform - - # Remove MaxResults parameter - - where: "$.paths..*" - remove-parameter: - in: query - name: maxresults - - # KeyOps updates - - rename-model: - from: KeyOperationsParameters - to: KeyOperationParameters - - from: models.go - where: $ - transform: return $.replace(/KeyOps \[\]\*string/, "KeyOps []*KeyOperation"); - - # fix capitalization - - from: swagger-document - where: $.definitions.ImportKeyParameters.properties.Hsm - transform: $["x-ms-client-name"] = "HSM" - - from: swagger-document - where: $.definitions..properties..iv - transform: $["x-ms-client-name"] = "IV" - - from: swagger-document - where: $.definitions..properties..kid - transform: $["x-ms-client-name"] = "KID" - - # keyName, keyVersion -> name, version - - from: swagger-document - where: $.paths..parameters..[?(@.name=='key-name')] - transform: $["x-ms-client-name"] = "name" - - from: swagger-document - where: $.paths..parameters..[?(@.name=='key-version')] - transform: $["x-ms-client-name"] = "version" - - # KeyEncryptionAlgorithm renames - - from: swagger-document - where: $.definitions.ReleaseParameters.properties.enc - transform: $["x-ms-client-name"] = "algorithm" - - # rename KeyOperationsParameters fields - - from: swagger-document - where: $.definitions.KeyOperationParameters.properties.aad - transform: $["x-ms-client-name"] = "AdditionalAuthenticatedData" - - from: swagger-document - where: $.definitions.KeyOperationParameters.properties.tag - transform: $["x-ms-client-name"] = "AuthenticationTag" - - # remove JSONWeb Prefix - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/JSONWebKeyOperation/g, "KeyOperation"); - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/JSONWebKeyCurveName/g, "CurveName"); - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/JSONWebKeyEncryptionAlgorithm/g, "EncryptionAlgorithm"); - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/JSONWebKeySignatureAlgorithm/g, "SignatureAlgorithm"); - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/JSONWebKeyType/g, "KeyType"); - - # remove DeletionRecoveryLevel type - - from: models.go - where: $ - transform: return $.replace(/RecoveryLevel \*DeletionRecoveryLevel/g, "RecoveryLevel *string"); - - from: constants.go - where: $ - transform: return $.replace(/(?:\/\/.*\s)+type DeletionRecoveryLevel string/, ""); - - from: constants.go - where: $ - transform: return $.replace(/(?:\/\/.*\s)+func PossibleDeletionRecovery(?:.+\s)+\}/, ""); - - from: constants.go - where: $ - transform: return $.replace(/const \(\n\s\/\/ DeletionRecoveryLevel(?:.+\s)+\)/, ""); - - # delete SignatureAlgorithmRSNULL - - from: constants.go - where: $ - transform: return $.replace(/.*(\bSignatureAlgorithmRSNULL\b).*/g, ""); - - # delete KeyOperationExport - - from: constants.go - where: $ - transform: return $.replace(/.*(\bKeyOperationExport\b).*/g, ""); - - # 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/, ""); - - 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 version == "" \{\s+.+version cannot be empty"\)\s+\}\s/g, ""); - - # delete client name prefix from method options and response types - - from: - - client.go - - models.go - - options.go - - response_types.go - - options.go - where: $ - transform: return $.replace(/Client(\w+)((?:Options|Response))/g, "$1$2"); - - # insert a handwritten type for "KID" fields so we can add parsing methods - - from: models.go - where: $ - transform: return $.replace(/(KID \*)string(\s+.*)/g, "$1ID$2") - - # edit doc comments to not contain DeletedKeyBundle - - from: - - models.go - - response_types.go - where: $ - transform: return $.replace(/DeletedKeyBundle/g, "DeletedKey") - - # remove redundant section of doc comment - - from: - - models.go - - constants.go - where: $ - transform: return $.replace(/(For valid values, (.*)\.)|(For more information .*\.)|(For more information on possible algorithm\n\/\/ types, see JsonWebKeySignatureAlgorithm.)/g, ""); -``` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/build.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/build.go index da8103e45c2..16ea90bf888 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/build.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/build.go @@ -1,8 +1,6 @@ -//go:build go1.18 -// +build go1.18 - -//go:generate autorest ./autorest.md -//go:generate gofmt -w . +//go:generate tsp-client update +//go:generate go run ./internal/transforms.go +//go:generate goimports -w . // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/ci.yml index 75586518a61..9b3a65805c6 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/ci.yml +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/ci.yml @@ -28,15 +28,6 @@ extends: ServiceDirectory: 'security/keyvault/azkeys' RunLiveTests: true UsePipelineProxy: false - SupportedClouds: 'Public,UsGov,China' - CloudConfig: - Public: - UsGov: - MatrixFilters: - - ArmTemplateParameters=^(?!.*enableHsm.*true) - China: - MatrixFilters: - - ArmTemplateParameters=^(?!.*enableHsm.*true) # Due to the high cost of Managed HSMs, we only want to test using them weekly. ${{ if contains(variables['Build.DefinitionName'], 'weekly') }}: diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/client.go index bb4afa61a2b..0120d4206e2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/client.go @@ -1,41 +1,38 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys 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" "strings" + + "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" ) -// Client contains the methods for the Client group. +// Client - The key vault client performs cryptographic key operations and vault operations against the Key Vault service. // Don't use this type directly, use a constructor function instead. type Client struct { - internal *azcore.Client - endpoint string -} - -// BackupKey - The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does -// NOT return key material in a form that can be used outside the Azure Key Vault system, -// the returned key material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this -// operation is to allow a client to GENERATE a key in one Azure Key Vault -// instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP operation may be used to -// export, in protected form, any key type from Azure Key Vault. Individual -// versions of a key cannot be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that -// a BACKUP from one geographical area cannot be restored to another -// geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This -// operation requires the key/backup permission. + internal *azcore.Client + vaultBaseUrl string +} + +// BackupKey - Requests that a backup of the specified key be downloaded to the client. +// +// The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does NOT return +// key material in a form that can be used outside the Azure Key Vault system, the returned key material is either protected +// to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to allow a client to GENERATE a +// key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP +// operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a key cannot +// be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that a BACKUP from one geographical +// area cannot be restored to another geographical area. For example, a backup from the US geographical area cannot be restored +// in an EU geographical area. This operation requires the key/backup permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -62,13 +59,15 @@ func (client *Client) BackupKey(ctx context.Context, name string, options *Backu } // backupKeyCreateRequest creates the BackupKey request. -func (client *Client) backupKeyCreateRequest(ctx context.Context, name string, options *BackupKeyOptions) (*policy.Request, error) { +func (client *Client) backupKeyCreateRequest(ctx context.Context, name string, _ *BackupKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/backup" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -88,15 +87,16 @@ func (client *Client) backupKeyHandleResponse(resp *http.Response) (BackupKeyRes return result, nil } -// CreateKey - The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, -// Azure Key Vault creates a new version of the key. It requires the keys/create -// permission. +// CreateKey - Creates a new key, stores it, then returns key parameters and attributes to the client. +// +// The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure +// Key Vault creates a new version of the key. It requires the keys/create permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 // - name - The name for the new key. The system will generate the version name for the new key. 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. +// copied globally for the purpose of running the service. The value provided should not include personally identifiable or +// sensitive information. // - parameters - The parameters to create a key. // - options - CreateKeyOptions contains the optional parameters for the Client.CreateKey method. func (client *Client) CreateKey(ctx context.Context, name string, parameters CreateKeyParameters, options *CreateKeyOptions) (CreateKeyResponse, error) { @@ -120,13 +120,15 @@ func (client *Client) CreateKey(ctx context.Context, name string, parameters Cre } // createKeyCreateRequest creates the CreateKey request. -func (client *Client) createKeyCreateRequest(ctx context.Context, name string, parameters CreateKeyParameters, options *CreateKeyOptions) (*policy.Request, error) { +func (client *Client) createKeyCreateRequest(ctx context.Context, name string, parameters CreateKeyParameters, _ *CreateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/create" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -134,6 +136,7 @@ func (client *Client) createKeyCreateRequest(ctx context.Context, name string, p reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -149,14 +152,14 @@ func (client *Client) createKeyHandleResponse(resp *http.Response) (CreateKeyRes return result, nil } -// Decrypt - The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified -// algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of -// data may be decrypted, the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT -// operation applies to asymmetric and symmetric keys stored in Azure Key Vault -// since it uses the private portion of the key. This operation requires the keys/decrypt permission. Microsoft recommends -// not to use CBC algorithms for decryption without first ensuring the integrity of -// the ciphertext using an HMAC, for example. See https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode -// for more information. +// Decrypt - Decrypts a single block of encrypted data. +// +// The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified algorithm. +// This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, the size of this +// block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies to asymmetric and symmetric +// keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/decrypt permission. +// Microsoft recommends not to use CBC algorithms for decryption without first ensuring the integrity of the ciphertext using +// an HMAC, for example. See https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -185,14 +188,16 @@ func (client *Client) Decrypt(ctx context.Context, name string, version string, } // decryptCreateRequest creates the Decrypt request. -func (client *Client) decryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *DecryptOptions) (*policy.Request, error) { +func (client *Client) decryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *DecryptOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/decrypt" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -200,6 +205,7 @@ func (client *Client) decryptCreateRequest(ctx context.Context, name string, ver reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -215,9 +221,11 @@ func (client *Client) decryptHandleResponse(resp *http.Response) (DecryptRespons return result, nil } -// DeleteKey - The delete key operation cannot be used to remove individual versions of a key. This operation removes the -// cryptographic material associated with the key, which means the key is not usable for -// Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. This operation requires the keys/delete permission. +// DeleteKey - Deletes a key of any type from storage in Azure Key Vault. +// +// The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic +// material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. +// This operation requires the keys/delete permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -244,13 +252,15 @@ func (client *Client) DeleteKey(ctx context.Context, name string, options *Delet } // deleteKeyCreateRequest creates the DeleteKey request. -func (client *Client) deleteKeyCreateRequest(ctx context.Context, name string, options *DeleteKeyOptions) (*policy.Request, error) { +func (client *Client) deleteKeyCreateRequest(ctx context.Context, name string, _ *DeleteKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -270,13 +280,14 @@ func (client *Client) deleteKeyHandleResponse(resp *http.Response) (DeleteKeyRes return result, nil } -// Encrypt - The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure -// Key Vault. Note that the ENCRYPT operation only supports a single block of data, the size -// of which is dependent on the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly -// necessary for symmetric keys stored in Azure Key Vault since protection with an -// asymmetric key can be performed using public portion of the key. This operation is supported for asymmetric keys as a convenience -// for callers that have a key-reference but do not have access to the -// public key material. This operation requires the keys/encrypt permission. +// Encrypt - Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. +// +// The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. +// Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on the target key +// and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for symmetric keys stored in +// Azure Key Vault since protection with an asymmetric key can be performed using public portion of the key. This operation +// is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public +// key material. This operation requires the keys/encrypt permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -305,14 +316,16 @@ func (client *Client) Encrypt(ctx context.Context, name string, version string, } // encryptCreateRequest creates the Encrypt request. -func (client *Client) encryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *EncryptOptions) (*policy.Request, error) { +func (client *Client) encryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *EncryptOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/encrypt" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -320,6 +333,7 @@ func (client *Client) encryptCreateRequest(ctx context.Context, name string, ver reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -335,9 +349,10 @@ func (client *Client) encryptHandleResponse(resp *http.Response) (EncryptRespons return result, nil } -// GetDeletedKey - The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be -// invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This -// operation requires the keys/get permission. +// GetDeletedKey - Gets the public part of a deleted key. +// +// The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, +// it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/get permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -364,13 +379,15 @@ func (client *Client) GetDeletedKey(ctx context.Context, name string, options *G } // getDeletedKeyCreateRequest creates the GetDeletedKey request. -func (client *Client) getDeletedKeyCreateRequest(ctx context.Context, name string, options *GetDeletedKeyOptions) (*policy.Request, error) { +func (client *Client) getDeletedKeyCreateRequest(ctx context.Context, name string, _ *GetDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/deletedkeys/{key-name}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -390,8 +407,10 @@ func (client *Client) getDeletedKeyHandleResponse(resp *http.Response) (GetDelet return result, nil } -// GetKey - The get key operation is applicable to all key types. If the requested key is symmetric, then no key material -// is released in the response. This operation requires the keys/get permission. +// GetKey - Gets the public part of a stored key. +// +// The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released +// in the response. This operation requires the keys/get permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -420,14 +439,16 @@ func (client *Client) GetKey(ctx context.Context, name string, version string, o } // getKeyCreateRequest creates the GetKey request. -func (client *Client) getKeyCreateRequest(ctx context.Context, name string, version string, options *GetKeyOptions) (*policy.Request, error) { +func (client *Client) getKeyCreateRequest(ctx context.Context, name string, version string, _ *GetKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -447,8 +468,10 @@ func (client *Client) getKeyHandleResponse(resp *http.Response) (GetKeyResponse, return result, nil } -// GetKeyRotationPolicy - The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key -// vault. This operation requires the keys/get permission. +// GetKeyRotationPolicy - Lists the policy for a key. +// +// The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This operation +// requires the keys/get permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -475,13 +498,15 @@ func (client *Client) GetKeyRotationPolicy(ctx context.Context, name string, opt } // getKeyRotationPolicyCreateRequest creates the GetKeyRotationPolicy request. -func (client *Client) getKeyRotationPolicyCreateRequest(ctx context.Context, name string, options *GetKeyRotationPolicyOptions) (*policy.Request, error) { +func (client *Client) getKeyRotationPolicyCreateRequest(ctx context.Context, name string, _ *GetKeyRotationPolicyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/rotationpolicy" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -501,7 +526,9 @@ func (client *Client) getKeyRotationPolicyHandleResponse(resp *http.Response) (G return result, nil } -// GetRandomBytes - Get the requested number of bytes containing random values from a managed HSM. +// GetRandomBytes - Get the requested number of bytes containing random values. +// +// Get the requested number of bytes containing random values from a managed HSM. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -528,9 +555,11 @@ func (client *Client) GetRandomBytes(ctx context.Context, parameters GetRandomBy } // getRandomBytesCreateRequest creates the GetRandomBytes request. -func (client *Client) getRandomBytesCreateRequest(ctx context.Context, parameters GetRandomBytesParameters, options *GetRandomBytesOptions) (*policy.Request, error) { +func (client *Client) getRandomBytesCreateRequest(ctx context.Context, parameters GetRandomBytesParameters, _ *GetRandomBytesOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/rng" - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -538,6 +567,7 @@ func (client *Client) getRandomBytesCreateRequest(ctx context.Context, parameter reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -553,9 +583,10 @@ func (client *Client) getRandomBytesHandleResponse(resp *http.Response) (GetRand return result, nil } -// ImportKey - The import key operation may be used to import any key type into an Azure Key Vault. If the named key already -// exists, Azure Key Vault creates a new version of the key. This operation requires the -// keys/import permission. +// ImportKey - Imports an externally created key, stores it, and returns key parameters and attributes to the client. +// +// The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure +// Key Vault creates a new version of the key. This operation requires the keys/import permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -584,13 +615,15 @@ func (client *Client) ImportKey(ctx context.Context, name string, parameters Imp } // importKeyCreateRequest creates the ImportKey request. -func (client *Client) importKeyCreateRequest(ctx context.Context, name string, parameters ImportKeyParameters, options *ImportKeyOptions) (*policy.Request, error) { +func (client *Client) importKeyCreateRequest(ctx context.Context, name string, parameters ImportKeyParameters, _ *ImportKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -598,6 +631,7 @@ func (client *Client) importKeyCreateRequest(ctx context.Context, name string, p reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -613,11 +647,12 @@ func (client *Client) importKeyHandleResponse(resp *http.Response) (ImportKeyRes return result, nil } -// NewListDeletedKeyPropertiesPager - Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain -// the public part of a deleted key. This operation includes deletion-specific information. The Get Deleted Keys -// operation is applicable for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return -// an error if invoked on a non soft-delete enabled vault. This operation -// requires the keys/list permission. +// NewListDeletedKeyPropertiesPager - Lists the deleted keys in the specified vault. +// +// Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a deleted key. +// This operation includes deletion-specific information. The Get Deleted Keys operation is applicable for vaults enabled +// for soft-delete. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete +// enabled vault. This operation requires the keys/list permission. // // Generated from API version 7.5 // - options - ListDeletedKeyPropertiesOptions contains the optional parameters for the Client.NewListDeletedKeyPropertiesPager @@ -646,8 +681,10 @@ func (client *Client) NewListDeletedKeyPropertiesPager(options *ListDeletedKeyPr // listDeletedKeyPropertiesCreateRequest creates the ListDeletedKeyProperties request. func (client *Client) listDeletedKeyPropertiesCreateRequest(ctx context.Context, options *ListDeletedKeyPropertiesOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/deletedkeys" - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -667,10 +704,11 @@ func (client *Client) listDeletedKeyPropertiesHandleResponse(resp *http.Response return result, nil } -// NewListKeyPropertiesPager - Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public -// part of a stored key. The LIST operation is applicable to all key types, however only the base key -// identifier, attributes, and tags are provided in the response. Individual versions of a key are not listed in the response. -// This operation requires the keys/list permission. +// NewListKeyPropertiesPager - List keys in the specified vault. +// +// Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored key. +// The LIST operation is applicable to all key types, however only the base key identifier, attributes, and tags are provided +// in the response. Individual versions of a key are not listed in the response. This operation requires the keys/list permission. // // Generated from API version 7.5 // - options - ListKeyPropertiesOptions contains the optional parameters for the Client.NewListKeyPropertiesPager method. @@ -698,8 +736,10 @@ func (client *Client) NewListKeyPropertiesPager(options *ListKeyPropertiesOption // listKeyPropertiesCreateRequest creates the ListKeyProperties request. func (client *Client) listKeyPropertiesCreateRequest(ctx context.Context, options *ListKeyPropertiesOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys" - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -719,8 +759,9 @@ func (client *Client) listKeyPropertiesHandleResponse(resp *http.Response) (List return result, nil } -// NewListKeyPropertiesVersionsPager - The full key identifier, attributes, and tags are provided in the response. This operation -// requires the keys/list permission. +// NewListKeyPropertiesVersionsPager - Retrieves a list of individual key versions with the same key name. +// +// The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. // // Generated from API version 7.5 // - name - The name of the key. @@ -750,12 +791,14 @@ func (client *Client) NewListKeyPropertiesVersionsPager(name string, options *Li // listKeyPropertiesVersionsCreateRequest creates the ListKeyPropertiesVersions request. func (client *Client) listKeyPropertiesVersionsCreateRequest(ctx context.Context, name string, options *ListKeyPropertiesVersionsOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/versions" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -775,9 +818,10 @@ func (client *Client) listKeyPropertiesVersionsHandleResponse(resp *http.Respons return result, nil } -// PurgeDeletedKey - The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can -// be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. -// This operation requires the keys/purge permission. +// PurgeDeletedKey - Permanently deletes the specified key. +// +// The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any +// vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/purge permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -803,13 +847,15 @@ func (client *Client) PurgeDeletedKey(ctx context.Context, name string, options } // purgeDeletedKeyCreateRequest creates the PurgeDeletedKey request. -func (client *Client) purgeDeletedKeyCreateRequest(ctx context.Context, name string, options *PurgeDeletedKeyOptions) (*policy.Request, error) { +func (client *Client) purgeDeletedKeyCreateRequest(ctx context.Context, name string, _ *PurgeDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/deletedkeys/{key-name}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -820,10 +866,11 @@ func (client *Client) purgeDeletedKeyCreateRequest(ctx context.Context, name str return req, nil } -// RecoverDeletedKey - The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It -// recovers the deleted key back to its latest version under /keys. An attempt to recover an non-deleted -// key will return an error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation -// requires the keys/recover permission. +// RecoverDeletedKey - Recovers the deleted key to its latest version. +// +// The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the deleted +// key back to its latest version under /keys. An attempt to recover an non-deleted key will return an error. Consider this +// the inverse of the delete operation on soft-delete enabled vaults. This operation requires the keys/recover permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -850,13 +897,15 @@ func (client *Client) RecoverDeletedKey(ctx context.Context, name string, option } // recoverDeletedKeyCreateRequest creates the RecoverDeletedKey request. -func (client *Client) recoverDeletedKeyCreateRequest(ctx context.Context, name string, options *RecoverDeletedKeyOptions) (*policy.Request, error) { +func (client *Client) recoverDeletedKeyCreateRequest(ctx context.Context, name string, _ *RecoverDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/deletedkeys/{key-name}/recover" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -876,8 +925,10 @@ func (client *Client) recoverDeletedKeyHandleResponse(resp *http.Response) (Reco return result, nil } -// Release - The release key operation is applicable to all key types. The target key must be marked exportable. This operation -// requires the keys/release permission. +// Release - Releases a key. +// +// The release key operation is applicable to all key types. The target key must be marked exportable. This operation requires +// the keys/release permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -906,14 +957,16 @@ func (client *Client) Release(ctx context.Context, name string, version string, } // releaseCreateRequest creates the Release request. -func (client *Client) releaseCreateRequest(ctx context.Context, name string, version string, parameters ReleaseParameters, options *ReleaseOptions) (*policy.Request, error) { +func (client *Client) releaseCreateRequest(ctx context.Context, name string, version string, parameters ReleaseParameters, _ *ReleaseOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/release" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -921,6 +974,7 @@ func (client *Client) releaseCreateRequest(ctx context.Context, name string, ver reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -936,15 +990,16 @@ func (client *Client) releaseHandleResponse(resp *http.Response) (ReleaseRespons return result, nil } -// RestoreKey - Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes -// and access control policies. The RESTORE operation may be used to import a previously backed -// up key. Individual versions of a key cannot be restored. The key is restored in its entirety with the same key name as -// it had when it was backed up. If the key name is not available in the target Key -// Vault, the RESTORE operation will be rejected. While the key name is retained during restore, the final key identifier -// will change if the key is restored to a different vault. Restore will restore all -// versions and preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault -// must be owned by the same Microsoft Azure Subscription as the source Key Vault -// The user must have RESTORE permission in the target Key Vault. This operation requires the keys/restore permission. +// RestoreKey - Restores a backed up key to a vault. +// +// Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and access control +// policies. The RESTORE operation may be used to import a previously backed up key. Individual versions of a key cannot be +// restored. The key is restored in its entirety with the same key name as it had when it was backed up. If the key name is +// not available in the target Key Vault, the RESTORE operation will be rejected. While the key name is retained during restore, +// the final key identifier will change if the key is restored to a different vault. Restore will restore all versions and +// preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault must be owned +// by the same Microsoft Azure Subscription as the source Key Vault The user must have RESTORE permission in the target Key +// Vault. This operation requires the keys/restore permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -971,9 +1026,11 @@ func (client *Client) RestoreKey(ctx context.Context, parameters RestoreKeyParam } // restoreKeyCreateRequest creates the RestoreKey request. -func (client *Client) restoreKeyCreateRequest(ctx context.Context, parameters RestoreKeyParameters, options *RestoreKeyOptions) (*policy.Request, error) { +func (client *Client) restoreKeyCreateRequest(ctx context.Context, parameters RestoreKeyParameters, _ *RestoreKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/restore" - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -981,6 +1038,7 @@ func (client *Client) restoreKeyCreateRequest(ctx context.Context, parameters Re reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -996,7 +1054,9 @@ func (client *Client) restoreKeyHandleResponse(resp *http.Response) (RestoreKeyR return result, nil } -// RotateKey - The operation will rotate the key based on the key policy. It requires the keys/rotate permission. +// RotateKey - Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. +// +// The operation will rotate the key based on the key policy. It requires the keys/rotate permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1023,13 +1083,15 @@ func (client *Client) RotateKey(ctx context.Context, name string, options *Rotat } // rotateKeyCreateRequest creates the RotateKey request. -func (client *Client) rotateKeyCreateRequest(ctx context.Context, name string, options *RotateKeyOptions) (*policy.Request, error) { +func (client *Client) rotateKeyCreateRequest(ctx context.Context, name string, _ *RotateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/rotate" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1049,8 +1111,10 @@ func (client *Client) rotateKeyHandleResponse(resp *http.Response) (RotateKeyRes return result, nil } -// Sign - The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation -// uses the private portion of the key. This operation requires the keys/sign permission. +// Sign - Creates a signature from a digest using the specified key. +// +// The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation uses the +// private portion of the key. This operation requires the keys/sign permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1079,14 +1143,16 @@ func (client *Client) Sign(ctx context.Context, name string, version string, par } // signCreateRequest creates the Sign request. -func (client *Client) signCreateRequest(ctx context.Context, name string, version string, parameters SignParameters, options *SignOptions) (*policy.Request, error) { +func (client *Client) signCreateRequest(ctx context.Context, name string, version string, parameters SignParameters, _ *SignOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/sign" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1094,6 +1160,7 @@ func (client *Client) signCreateRequest(ctx context.Context, name string, versio reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -1109,10 +1176,11 @@ func (client *Client) signHandleResponse(resp *http.Response) (SignResponse, err return result, nil } -// UnwrapKey - The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation -// is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and -// symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey -// permission. +// UnwrapKey - Unwraps a symmetric key using the specified key that was initially used for wrapping that key. +// +// The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the +// reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault +// since it uses the private portion of the key. This operation requires the keys/unwrapKey permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1141,14 +1209,16 @@ func (client *Client) UnwrapKey(ctx context.Context, name string, version string } // unwrapKeyCreateRequest creates the UnwrapKey request. -func (client *Client) unwrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *UnwrapKeyOptions) (*policy.Request, error) { +func (client *Client) unwrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *UnwrapKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/unwrapkey" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1156,6 +1226,7 @@ func (client *Client) unwrapKeyCreateRequest(ctx context.Context, name string, v reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -1171,8 +1242,11 @@ func (client *Client) unwrapKeyHandleResponse(resp *http.Response) (UnwrapKeyRes return result, nil } -// UpdateKey - In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material -// of a key itself cannot be changed. This operation requires the keys/update permission. +// UpdateKey - The update key operation changes specified attributes of a stored key and can be applied to any key type and +// key version stored in Azure Key Vault. +// +// In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material of a +// key itself cannot be changed. This operation requires the keys/update permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1201,14 +1275,16 @@ func (client *Client) UpdateKey(ctx context.Context, name string, version string } // updateKeyCreateRequest creates the UpdateKey request. -func (client *Client) updateKeyCreateRequest(ctx context.Context, name string, version string, parameters UpdateKeyParameters, options *UpdateKeyOptions) (*policy.Request, error) { +func (client *Client) updateKeyCreateRequest(ctx context.Context, name string, version string, parameters UpdateKeyParameters, _ *UpdateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1216,6 +1292,7 @@ func (client *Client) updateKeyCreateRequest(ctx context.Context, name string, v reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -1231,15 +1308,15 @@ func (client *Client) updateKeyHandleResponse(resp *http.Response) (UpdateKeyRes return result, nil } -// UpdateKeyRotationPolicy - Set specified members in the key policy. Leave others as undefined. This operation requires the -// keys/update permission. +// UpdateKeyRotationPolicy - Updates the rotation policy for a key. +// +// Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 // - name - The name of the key in the given vault. // - keyRotationPolicy - The policy for the key. -// - options - UpdateKeyRotationPolicyOptions contains the optional parameters for the Client.UpdateKeyRotationPolicy -// method. +// - options - UpdateKeyRotationPolicyOptions contains the optional parameters for the Client.UpdateKeyRotationPolicy method. func (client *Client) UpdateKeyRotationPolicy(ctx context.Context, name string, keyRotationPolicy KeyRotationPolicy, options *UpdateKeyRotationPolicyOptions) (UpdateKeyRotationPolicyResponse, error) { var err error ctx, endSpan := runtime.StartSpan(ctx, "Client.UpdateKeyRotationPolicy", client.internal.Tracer(), nil) @@ -1261,13 +1338,15 @@ func (client *Client) UpdateKeyRotationPolicy(ctx context.Context, name string, } // updateKeyRotationPolicyCreateRequest creates the UpdateKeyRotationPolicy request. -func (client *Client) updateKeyRotationPolicyCreateRequest(ctx context.Context, name string, keyRotationPolicy KeyRotationPolicy, options *UpdateKeyRotationPolicyOptions) (*policy.Request, error) { +func (client *Client) updateKeyRotationPolicyCreateRequest(ctx context.Context, name string, keyRotationPolicy KeyRotationPolicy, _ *UpdateKeyRotationPolicyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/rotationpolicy" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) - req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1275,6 +1354,7 @@ func (client *Client) updateKeyRotationPolicyCreateRequest(ctx context.Context, reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, keyRotationPolicy); err != nil { return nil, err } @@ -1290,11 +1370,12 @@ func (client *Client) updateKeyRotationPolicyHandleResponse(resp *http.Response) return result, nil } -// Verify - The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary -// for asymmetric keys stored in Azure Key Vault since signature verification can be -// performed using the public portion of the key but this operation is supported as a convenience for callers that only have -// a key-reference and not the public portion of the key. This operation requires -// the keys/verify permission. +// Verify - Verifies a signature using a specified key. +// +// The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric +// keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this +// operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. +// This operation requires the keys/verify permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1323,14 +1404,16 @@ func (client *Client) Verify(ctx context.Context, name string, version string, p } // verifyCreateRequest creates the Verify request. -func (client *Client) verifyCreateRequest(ctx context.Context, name string, version string, parameters VerifyParameters, options *VerifyOptions) (*policy.Request, error) { +func (client *Client) verifyCreateRequest(ctx context.Context, name string, version string, parameters VerifyParameters, _ *VerifyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/verify" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1338,6 +1421,7 @@ func (client *Client) verifyCreateRequest(ctx context.Context, name string, vers reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } @@ -1353,12 +1437,13 @@ func (client *Client) verifyHandleResponse(resp *http.Response) (VerifyResponse, return result, nil } -// WrapKey - The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been -// stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric -// keys stored in Azure Key Vault since protection with an asymmetric key can be performed using the public portion of the -// key. This operation is supported for asymmetric keys as a convenience for -// callers that have a key-reference but do not have access to the public key material. This operation requires the keys/wrapKey -// permission. +// WrapKey - Wraps a symmetric key using a specified key. +// +// The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been stored in +// an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection +// with an asymmetric key can be performed using the public portion of the key. This operation is supported for asymmetric +// keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation +// requires the keys/wrapKey permission. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 7.5 @@ -1387,14 +1472,16 @@ func (client *Client) WrapKey(ctx context.Context, name string, version string, } // wrapKeyCreateRequest creates the WrapKey request. -func (client *Client) wrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *WrapKeyOptions) (*policy.Request, error) { +func (client *Client) wrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *WrapKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) urlPath := "/keys/{key-name}/{key-version}/wrapkey" if name == "" { return nil, errors.New("parameter name cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) - req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) if err != nil { return nil, err } @@ -1402,6 +1489,7 @@ func (client *Client) wrapKeyCreateRequest(ctx context.Context, name string, ver reqQP.Set("api-version", "7.5") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, parameters); err != nil { return nil, err } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/constants.go index 8f5c30c9f1c..de3f3a8133a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/constants.go @@ -1,10 +1,6 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys @@ -32,24 +28,42 @@ func PossibleCurveNameValues() []CurveName { } } -// EncryptionAlgorithm - algorithm identifier +// EncryptionAlgorithm - An algorithm used for encryption and decryption. type EncryptionAlgorithm string const ( - EncryptionAlgorithmA128CBC EncryptionAlgorithm = "A128CBC" + // EncryptionAlgorithmA128CBC - 128-bit AES-CBC. + EncryptionAlgorithmA128CBC EncryptionAlgorithm = "A128CBC" + // EncryptionAlgorithmA128CBCPAD - 128-bit AES-CBC with PKCS padding. EncryptionAlgorithmA128CBCPAD EncryptionAlgorithm = "A128CBCPAD" - EncryptionAlgorithmA128GCM EncryptionAlgorithm = "A128GCM" - EncryptionAlgorithmA128KW EncryptionAlgorithm = "A128KW" - EncryptionAlgorithmA192CBC EncryptionAlgorithm = "A192CBC" + // EncryptionAlgorithmA128GCM - 128-bit AES-GCM. + EncryptionAlgorithmA128GCM EncryptionAlgorithm = "A128GCM" + // EncryptionAlgorithmA128KW - 128-bit AES key wrap. + EncryptionAlgorithmA128KW EncryptionAlgorithm = "A128KW" + // EncryptionAlgorithmA192CBC - 192-bit AES-CBC. + EncryptionAlgorithmA192CBC EncryptionAlgorithm = "A192CBC" + // EncryptionAlgorithmA192CBCPAD - 192-bit AES-CBC with PKCS padding. EncryptionAlgorithmA192CBCPAD EncryptionAlgorithm = "A192CBCPAD" - EncryptionAlgorithmA192GCM EncryptionAlgorithm = "A192GCM" - EncryptionAlgorithmA192KW EncryptionAlgorithm = "A192KW" - EncryptionAlgorithmA256CBC EncryptionAlgorithm = "A256CBC" + // EncryptionAlgorithmA192GCM - 192-bit AES-GCM. + EncryptionAlgorithmA192GCM EncryptionAlgorithm = "A192GCM" + // EncryptionAlgorithmA192KW - 192-bit AES key wrap. + EncryptionAlgorithmA192KW EncryptionAlgorithm = "A192KW" + // EncryptionAlgorithmA256CBC - 256-bit AES-CBC. + EncryptionAlgorithmA256CBC EncryptionAlgorithm = "A256CBC" + // EncryptionAlgorithmA256CBCPAD - 256-bit AES-CBC with PKCS padding. EncryptionAlgorithmA256CBCPAD EncryptionAlgorithm = "A256CBCPAD" - EncryptionAlgorithmA256GCM EncryptionAlgorithm = "A256GCM" - EncryptionAlgorithmA256KW EncryptionAlgorithm = "A256KW" - EncryptionAlgorithmRSA15 EncryptionAlgorithm = "RSA1_5" - EncryptionAlgorithmRSAOAEP EncryptionAlgorithm = "RSA-OAEP" + // EncryptionAlgorithmA256GCM - 256-bit AES-GCM. + EncryptionAlgorithmA256GCM EncryptionAlgorithm = "A256GCM" + // EncryptionAlgorithmA256KW - 256-bit AES key wrap. + EncryptionAlgorithmA256KW EncryptionAlgorithm = "A256KW" + // EncryptionAlgorithmRSA15 - RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. + EncryptionAlgorithmRSA15 EncryptionAlgorithm = "RSA1_5" + // EncryptionAlgorithmRSAOAEP - RSAES using Optimal Asymmetric Encryption Padding (OAEP), as described in https://tools.ietf.org/html/rfc3447, + // with the default parameters specified by RFC 3447 in Section A.2.1. Those default parameters are using a hash function + // of SHA-1 and a mask generation function of MGF1 with SHA-1. + EncryptionAlgorithmRSAOAEP EncryptionAlgorithm = "RSA-OAEP" + // EncryptionAlgorithmRSAOAEP256 - RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and a + // mask generation function of MGF1 with SHA-256. EncryptionAlgorithmRSAOAEP256 EncryptionAlgorithm = "RSA-OAEP-256" ) @@ -74,18 +88,46 @@ func PossibleEncryptionAlgorithmValues() []EncryptionAlgorithm { } } -// KeyOperation - JSON web key operations. For more information, see JsonWebKeyOperation. +// KeyEncryptionAlgorithm - The encryption algorithm to use to protected the exported key material +type KeyEncryptionAlgorithm string + +const ( + // KeyEncryptionAlgorithmCKMRSAAESKEYWRAP - The CKM_RSA_AES_KEY_WRAP key wrap mechanism. + KeyEncryptionAlgorithmCKMRSAAESKEYWRAP KeyEncryptionAlgorithm = "CKM_RSA_AES_KEY_WRAP" + // KeyEncryptionAlgorithmRSAAESKEYWRAP256 - The RSA_AES_KEY_WRAP_256 key wrap mechanism. + KeyEncryptionAlgorithmRSAAESKEYWRAP256 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_256" + // KeyEncryptionAlgorithmRSAAESKEYWRAP384 - The RSA_AES_KEY_WRAP_384 key wrap mechanism. + KeyEncryptionAlgorithmRSAAESKEYWRAP384 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_384" +) + +// PossibleKeyEncryptionAlgorithmValues returns the possible values for the KeyEncryptionAlgorithm const type. +func PossibleKeyEncryptionAlgorithmValues() []KeyEncryptionAlgorithm { + return []KeyEncryptionAlgorithm{ + KeyEncryptionAlgorithmCKMRSAAESKEYWRAP, + KeyEncryptionAlgorithmRSAAESKEYWRAP256, + KeyEncryptionAlgorithmRSAAESKEYWRAP384, + } +} + +// KeyOperation - JSON web key operations. type KeyOperation string const ( + // KeyOperationDecrypt - Indicates that the key can be used to decrypt. KeyOperationDecrypt KeyOperation = "decrypt" + // KeyOperationEncrypt - Indicates that the key can be used to encrypt. KeyOperationEncrypt KeyOperation = "encrypt" - KeyOperationImport KeyOperation = "import" - KeyOperationSign KeyOperation = "sign" + // KeyOperationImport - Indicates that the key can be imported during creation. + KeyOperationImport KeyOperation = "import" + // KeyOperationSign - Indicates that the key can be used to sign. + KeyOperationSign KeyOperation = "sign" + // KeyOperationUnwrapKey - Indicates that the key can be used to unwrap another key. KeyOperationUnwrapKey KeyOperation = "unwrapKey" - KeyOperationVerify KeyOperation = "verify" - KeyOperationWrapKey KeyOperation = "wrapKey" + // KeyOperationVerify - Indicates that the key can be used to verify. + KeyOperationVerify KeyOperation = "verify" + // KeyOperationWrapKey - Indicates that the key can be used to wrap another key. + KeyOperationWrapKey KeyOperation = "wrapKey" ) // PossibleKeyOperationValues returns the possible values for the KeyOperation const type. @@ -102,45 +144,21 @@ func PossibleKeyOperationValues() []KeyOperation { } } -// SignatureAlgorithm - The signing/verification algorithm identifier. -type SignatureAlgorithm string +// KeyRotationPolicyAction - The type of the action. The value should be compared case-insensitively. +type KeyRotationPolicyAction string const ( - // SignatureAlgorithmES256 - ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. - SignatureAlgorithmES256 SignatureAlgorithm = "ES256" - // SignatureAlgorithmES256K - ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmES256K SignatureAlgorithm = "ES256K" - // SignatureAlgorithmES384 - ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmES384 SignatureAlgorithm = "ES384" - // SignatureAlgorithmES512 - ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmES512 SignatureAlgorithm = "ES512" - // SignatureAlgorithmPS256 - RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmPS256 SignatureAlgorithm = "PS256" - // SignatureAlgorithmPS384 - RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmPS384 SignatureAlgorithm = "PS384" - // SignatureAlgorithmPS512 - RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmPS512 SignatureAlgorithm = "PS512" - // SignatureAlgorithmRS256 - RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmRS256 SignatureAlgorithm = "RS256" - // SignatureAlgorithmRS384 - RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmRS384 SignatureAlgorithm = "RS384" - // SignatureAlgorithmRS512 - RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518 - SignatureAlgorithmRS512 SignatureAlgorithm = "RS512" + // KeyRotationPolicyActionNotify - Trigger Event Grid events. Defaults to 30 days before expiry. Key Vault only. + KeyRotationPolicyActionNotify KeyRotationPolicyAction = "Notify" + // KeyRotationPolicyActionRotate - Rotate the key based on the key policy. + KeyRotationPolicyActionRotate KeyRotationPolicyAction = "Rotate" ) -// PossibleSignatureAlgorithmValues returns the possible values for the SignatureAlgorithm const type. -func PossibleSignatureAlgorithmValues() []SignatureAlgorithm { - return []SignatureAlgorithm{ - SignatureAlgorithmES256, - SignatureAlgorithmES256K, - SignatureAlgorithmES384, - SignatureAlgorithmES512, - SignatureAlgorithmPS256, - SignatureAlgorithmPS384, - SignatureAlgorithmPS512, - SignatureAlgorithmRS256, - SignatureAlgorithmRS384, - SignatureAlgorithmRS512, +// PossibleKeyRotationPolicyActionValues returns the possible values for the KeyRotationPolicyAction const type. +func PossibleKeyRotationPolicyActionValues() []KeyRotationPolicyAction { + return []KeyRotationPolicyAction{ + KeyRotationPolicyActionNotify, + KeyRotationPolicyActionRotate, } } @@ -174,38 +192,44 @@ func PossibleKeyTypeValues() []KeyType { } } -// KeyEncryptionAlgorithm - The encryption algorithm to use to protected the exported key material -type KeyEncryptionAlgorithm string - -const ( - KeyEncryptionAlgorithmCKMRSAAESKEYWRAP KeyEncryptionAlgorithm = "CKM_RSA_AES_KEY_WRAP" - KeyEncryptionAlgorithmRSAAESKEYWRAP256 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_256" - KeyEncryptionAlgorithmRSAAESKEYWRAP384 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_384" -) - -// PossibleKeyEncryptionAlgorithmValues returns the possible values for the KeyEncryptionAlgorithm const type. -func PossibleKeyEncryptionAlgorithmValues() []KeyEncryptionAlgorithm { - return []KeyEncryptionAlgorithm{ - KeyEncryptionAlgorithmCKMRSAAESKEYWRAP, - KeyEncryptionAlgorithmRSAAESKEYWRAP256, - KeyEncryptionAlgorithmRSAAESKEYWRAP384, - } -} - -// KeyRotationPolicyAction - The type of the action. The value should be compared case-insensitively. -type KeyRotationPolicyAction string +// SignatureAlgorithm - The signing/verification algorithm identifier. +type SignatureAlgorithm string const ( - // KeyRotationPolicyActionNotify - Trigger Event Grid events. Defaults to 30 days before expiry. Key Vault only. - KeyRotationPolicyActionNotify KeyRotationPolicyAction = "Notify" - // KeyRotationPolicyActionRotate - Rotate the key based on the key policy. - KeyRotationPolicyActionRotate KeyRotationPolicyAction = "Rotate" + // SignatureAlgorithmES256 - ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. + SignatureAlgorithmES256 SignatureAlgorithm = "ES256" + // SignatureAlgorithmES256K - ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES256K SignatureAlgorithm = "ES256K" + // SignatureAlgorithmES384 - ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES384 SignatureAlgorithm = "ES384" + // SignatureAlgorithmES512 - ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES512 SignatureAlgorithm = "ES512" + // SignatureAlgorithmPS256 - RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS256 SignatureAlgorithm = "PS256" + // SignatureAlgorithmPS384 - RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS384 SignatureAlgorithm = "PS384" + // SignatureAlgorithmPS512 - RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS512 SignatureAlgorithm = "PS512" + // SignatureAlgorithmRS256 - RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS256 SignatureAlgorithm = "RS256" + // SignatureAlgorithmRS384 - RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS384 SignatureAlgorithm = "RS384" + // SignatureAlgorithmRS512 - RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS512 SignatureAlgorithm = "RS512" ) -// PossibleKeyRotationPolicyActionValues returns the possible values for the KeyRotationPolicyAction const type. -func PossibleKeyRotationPolicyActionValues() []KeyRotationPolicyAction { - return []KeyRotationPolicyAction{ - KeyRotationPolicyActionNotify, - KeyRotationPolicyActionRotate, +// PossibleSignatureAlgorithmValues returns the possible values for the SignatureAlgorithm const type. +func PossibleSignatureAlgorithmValues() []SignatureAlgorithm { + return []SignatureAlgorithm{ + SignatureAlgorithmES256, + SignatureAlgorithmES256K, + SignatureAlgorithmES384, + SignatureAlgorithmES512, + SignatureAlgorithmPS256, + SignatureAlgorithmPS384, + SignatureAlgorithmPS512, + SignatureAlgorithmRS256, + SignatureAlgorithmRS384, + SignatureAlgorithmRS512, } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/custom_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/custom_client.go index 350ef41c42b..3b486ace289 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/custom_client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/custom_client.go @@ -1,6 +1,3 @@ -//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. @@ -50,7 +47,7 @@ func NewClient(vaultURL string, credential azcore.TokenCredential, options *Clie if err != nil { return nil, err } - return &Client{endpoint: vaultURL, internal: azcoreClient}, nil + return &Client{vaultBaseUrl: vaultURL, internal: azcoreClient}, nil } // ID is a key's unique ID, containing its version, if any, and name. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models.go index 6faae411ef9..36bdd166bfc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models.go @@ -1,10 +1,6 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys @@ -26,7 +22,9 @@ type CreateKeyParameters struct { // The attributes of a key managed by the key vault service. KeyAttributes *KeyAttributes - KeyOps []*KeyOperation + + // Json web key operations. + KeyOps []*KeyOperation // The key size in bits. For example: 2048, 3072, or 4096 for RSA. KeySize *int32 @@ -99,8 +97,8 @@ type DeletedKeyPropertiesListResult struct { // READ-ONLY; The URL to get the next set of deleted keys. NextLink *string - // READ-ONLY; A response message containing a list of deleted keys in the vault along with a link to the next page of deleted - // keys + // READ-ONLY; A response message containing a list of deleted keys in the key vault along with a link to the next page of + // deleted keys. Value []*DeletedKeyProperties } @@ -149,7 +147,9 @@ type JSONWebKey struct { K []byte // Key identifier. - KID *ID + KID *ID + + // Json web key operations. KeyOps []*KeyOperation // JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. @@ -202,8 +202,8 @@ type KeyAttributes struct { RecoverableDays *int32 // READ-ONLY; Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' - // the key can be permanently deleted by a privileged user; otherwise, only the system - // can purge the key, at the end of the retention interval. + // the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of the + // retention interval. RecoveryLevel *string // READ-ONLY; Last updated time in UTC. @@ -234,7 +234,7 @@ type KeyOperationParameters struct { // REQUIRED; algorithm identifier Algorithm *EncryptionAlgorithm - // REQUIRED + // REQUIRED; The value to operate on. Value []byte // Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. @@ -249,19 +249,19 @@ type KeyOperationParameters struct { // KeyOperationResult - The key operation result. type KeyOperationResult struct { - // READ-ONLY + // READ-ONLY; Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. AdditionalAuthenticatedData []byte - // READ-ONLY + // READ-ONLY; The tag to authenticate when performing decryption with an authenticated algorithm. AuthenticationTag []byte - // READ-ONLY + // READ-ONLY; Cryptographically random, non-repeating initialization vector for symmetric algorithms. IV []byte // READ-ONLY; Key identifier KID *ID - // READ-ONLY + // READ-ONLY; The result of the operation. Result []byte } @@ -315,8 +315,8 @@ type KeyRotationPolicy struct { Attributes *KeyRotationPolicyAttributes // Actions that will be performed by Key Vault over the lifetime of a key. For preview, lifetimeActions can only have two - // items at maximum: one for rotate, one for notify. Notification time would be - // default to 30 days before expiry and it is not configurable. + // items at maximum: one for rotate, one for notify. Notification time would be default to 30 days before expiry and it is + // not configurable. LifetimeActions []*LifetimeAction // READ-ONLY; The key policy id. @@ -396,7 +396,7 @@ type SignParameters struct { // REQUIRED; The signing/verification algorithm identifier. Algorithm *SignatureAlgorithm - // REQUIRED + // REQUIRED; The value to operate on. Value []byte } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models_serde.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models_serde.go index d33da63e18e..1f0a620c910 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models_serde.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/models_serde.go @@ -1,25 +1,24 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys import ( "encoding/json" "fmt" + "reflect" + "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 BackupKeyResult. func (b BackupKeyResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateByteArray(objectMap, "value", b.Value, runtime.Base64URLFormat) + populateByteArray(objectMap, "value", b.Value, func() any { + return runtime.EncodeByteArray(b.Value, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -33,7 +32,9 @@ func (b *BackupKeyResult) UnmarshalJSON(data []byte) error { var err error switch key { case "value": - err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -309,21 +310,45 @@ func (i *ImportKeyParameters) UnmarshalJSON(data []byte) error { func (j JSONWebKey) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "crv", j.Crv) - populateByteArray(objectMap, "d", j.D, runtime.Base64URLFormat) - populateByteArray(objectMap, "dp", j.DP, runtime.Base64URLFormat) - populateByteArray(objectMap, "dq", j.DQ, runtime.Base64URLFormat) - populateByteArray(objectMap, "e", j.E, runtime.Base64URLFormat) - populateByteArray(objectMap, "k", j.K, runtime.Base64URLFormat) + populateByteArray(objectMap, "d", j.D, func() any { + return runtime.EncodeByteArray(j.D, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "dp", j.DP, func() any { + return runtime.EncodeByteArray(j.DP, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "dq", j.DQ, func() any { + return runtime.EncodeByteArray(j.DQ, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "e", j.E, func() any { + return runtime.EncodeByteArray(j.E, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "k", j.K, func() any { + return runtime.EncodeByteArray(j.K, runtime.Base64URLFormat) + }) populate(objectMap, "kid", j.KID) populate(objectMap, "key_ops", j.KeyOps) populate(objectMap, "kty", j.Kty) - populateByteArray(objectMap, "n", j.N, runtime.Base64URLFormat) - populateByteArray(objectMap, "p", j.P, runtime.Base64URLFormat) - populateByteArray(objectMap, "q", j.Q, runtime.Base64URLFormat) - populateByteArray(objectMap, "qi", j.QI, runtime.Base64URLFormat) - populateByteArray(objectMap, "key_hsm", j.T, runtime.Base64URLFormat) - populateByteArray(objectMap, "x", j.X, runtime.Base64URLFormat) - populateByteArray(objectMap, "y", j.Y, runtime.Base64URLFormat) + populateByteArray(objectMap, "n", j.N, func() any { + return runtime.EncodeByteArray(j.N, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "p", j.P, func() any { + return runtime.EncodeByteArray(j.P, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "q", j.Q, func() any { + return runtime.EncodeByteArray(j.Q, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "qi", j.QI, func() any { + return runtime.EncodeByteArray(j.QI, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "key_hsm", j.T, func() any { + return runtime.EncodeByteArray(j.T, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "x", j.X, func() any { + return runtime.EncodeByteArray(j.X, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "y", j.Y, func() any { + return runtime.EncodeByteArray(j.Y, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -340,19 +365,29 @@ func (j *JSONWebKey) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Crv", &j.Crv) delete(rawMsg, key) case "d": - err = runtime.DecodeByteArray(string(val), &j.D, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.D, runtime.Base64URLFormat) + } delete(rawMsg, key) case "dp": - err = runtime.DecodeByteArray(string(val), &j.DP, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.DP, runtime.Base64URLFormat) + } delete(rawMsg, key) case "dq": - err = runtime.DecodeByteArray(string(val), &j.DQ, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.DQ, runtime.Base64URLFormat) + } delete(rawMsg, key) case "e": - err = runtime.DecodeByteArray(string(val), &j.E, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.E, runtime.Base64URLFormat) + } delete(rawMsg, key) case "k": - err = runtime.DecodeByteArray(string(val), &j.K, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.K, runtime.Base64URLFormat) + } delete(rawMsg, key) case "kid": err = unpopulate(val, "KID", &j.KID) @@ -364,25 +399,39 @@ func (j *JSONWebKey) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Kty", &j.Kty) delete(rawMsg, key) case "n": - err = runtime.DecodeByteArray(string(val), &j.N, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.N, runtime.Base64URLFormat) + } delete(rawMsg, key) case "p": - err = runtime.DecodeByteArray(string(val), &j.P, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.P, runtime.Base64URLFormat) + } delete(rawMsg, key) case "q": - err = runtime.DecodeByteArray(string(val), &j.Q, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Q, runtime.Base64URLFormat) + } delete(rawMsg, key) case "qi": - err = runtime.DecodeByteArray(string(val), &j.QI, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.QI, runtime.Base64URLFormat) + } delete(rawMsg, key) case "key_hsm": - err = runtime.DecodeByteArray(string(val), &j.T, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.T, runtime.Base64URLFormat) + } delete(rawMsg, key) case "x": - err = runtime.DecodeByteArray(string(val), &j.X, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.X, runtime.Base64URLFormat) + } delete(rawMsg, key) case "y": - err = runtime.DecodeByteArray(string(val), &j.Y, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Y, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -399,7 +448,7 @@ func (k KeyAttributes) MarshalJSON() ([]byte, error) { populate(objectMap, "enabled", k.Enabled) populateTimeUnix(objectMap, "exp", k.Expires) populate(objectMap, "exportable", k.Exportable) - populate(objectMap, "HSMPlatform", k.HSMPlatform) + populate(objectMap, "hsmPlatform", k.HSMPlatform) populateTimeUnix(objectMap, "nbf", k.NotBefore) populate(objectMap, "recoverableDays", k.RecoverableDays) populate(objectMap, "recoveryLevel", k.RecoveryLevel) @@ -428,7 +477,7 @@ func (k *KeyAttributes) UnmarshalJSON(data []byte) error { case "exportable": err = unpopulate(val, "Exportable", &k.Exportable) delete(rawMsg, key) - case "HSMPlatform": + case "hsmPlatform": err = unpopulate(val, "HSMPlatform", &k.HSMPlatform) delete(rawMsg, key) case "nbf": @@ -497,11 +546,19 @@ func (k *KeyBundle) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type KeyOperationParameters. func (k KeyOperationParameters) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, func() any { + return runtime.EncodeByteArray(k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + }) populate(objectMap, "alg", k.Algorithm) - populateByteArray(objectMap, "tag", k.AuthenticationTag, runtime.Base64URLFormat) - populateByteArray(objectMap, "iv", k.IV, runtime.Base64URLFormat) - populateByteArray(objectMap, "value", k.Value, runtime.Base64URLFormat) + populateByteArray(objectMap, "tag", k.AuthenticationTag, func() any { + return runtime.EncodeByteArray(k.AuthenticationTag, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "iv", k.IV, func() any { + return runtime.EncodeByteArray(k.IV, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", k.Value, func() any { + return runtime.EncodeByteArray(k.Value, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -515,19 +572,27 @@ func (k *KeyOperationParameters) UnmarshalJSON(data []byte) error { var err error switch key { case "aad": - err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + } delete(rawMsg, key) case "alg": err = unpopulate(val, "Algorithm", &k.Algorithm) delete(rawMsg, key) case "tag": - err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + } delete(rawMsg, key) case "iv": - err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + } delete(rawMsg, key) case "value": - err = runtime.DecodeByteArray(string(val), &k.Value, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Value, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -540,11 +605,19 @@ func (k *KeyOperationParameters) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type KeyOperationResult. func (k KeyOperationResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, runtime.Base64URLFormat) - populateByteArray(objectMap, "tag", k.AuthenticationTag, runtime.Base64URLFormat) - populateByteArray(objectMap, "iv", k.IV, runtime.Base64URLFormat) + populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, func() any { + return runtime.EncodeByteArray(k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "tag", k.AuthenticationTag, func() any { + return runtime.EncodeByteArray(k.AuthenticationTag, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "iv", k.IV, func() any { + return runtime.EncodeByteArray(k.IV, runtime.Base64URLFormat) + }) populate(objectMap, "kid", k.KID) - populateByteArray(objectMap, "value", k.Result, runtime.Base64URLFormat) + populateByteArray(objectMap, "value", k.Result, func() any { + return runtime.EncodeByteArray(k.Result, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -558,19 +631,27 @@ func (k *KeyOperationResult) UnmarshalJSON(data []byte) error { var err error switch key { case "aad": - err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + } delete(rawMsg, key) case "tag": - err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + } delete(rawMsg, key) case "iv": - err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + } delete(rawMsg, key) case "kid": err = unpopulate(val, "KID", &k.KID) delete(rawMsg, key) case "value": - err = runtime.DecodeByteArray(string(val), &k.Result, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Result, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -654,7 +735,9 @@ func (k *KeyPropertiesListResult) UnmarshalJSON(data []byte) error { func (k KeyReleasePolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "contentType", k.ContentType) - populateByteArray(objectMap, "data", k.EncodedPolicy, runtime.Base64URLFormat) + populateByteArray(objectMap, "data", k.EncodedPolicy, func() any { + return runtime.EncodeByteArray(k.EncodedPolicy, runtime.Base64URLFormat) + }) populate(objectMap, "immutable", k.Immutable) return json.Marshal(objectMap) } @@ -672,7 +755,9 @@ func (k *KeyReleasePolicy) UnmarshalJSON(data []byte) error { err = unpopulate(val, "ContentType", &k.ContentType) delete(rawMsg, key) case "data": - err = runtime.DecodeByteArray(string(val), &k.EncodedPolicy, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.EncodedPolicy, runtime.Base64URLFormat) + } delete(rawMsg, key) case "immutable": err = unpopulate(val, "Immutable", &k.Immutable) @@ -901,7 +986,9 @@ func (l *LifetimeActionType) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type RandomBytes. func (r RandomBytes) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateByteArray(objectMap, "value", r.Value, runtime.Base64URLFormat) + populateByteArray(objectMap, "value", r.Value, func() any { + return runtime.EncodeByteArray(r.Value, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -915,7 +1002,9 @@ func (r *RandomBytes) UnmarshalJSON(data []byte) error { var err error switch key { case "value": - err = runtime.DecodeByteArray(string(val), &r.Value, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &r.Value, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -963,7 +1052,9 @@ func (r *ReleaseParameters) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type RestoreKeyParameters. func (r RestoreKeyParameters) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateByteArray(objectMap, "value", r.KeyBackup, runtime.Base64URLFormat) + populateByteArray(objectMap, "value", r.KeyBackup, func() any { + return runtime.EncodeByteArray(r.KeyBackup, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -977,7 +1068,9 @@ func (r *RestoreKeyParameters) UnmarshalJSON(data []byte) error { var err error switch key { case "value": - err = runtime.DecodeByteArray(string(val), &r.KeyBackup, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &r.KeyBackup, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -991,7 +1084,9 @@ func (r *RestoreKeyParameters) UnmarshalJSON(data []byte) error { func (s SignParameters) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "alg", s.Algorithm) - populateByteArray(objectMap, "value", s.Value, runtime.Base64URLFormat) + populateByteArray(objectMap, "value", s.Value, func() any { + return runtime.EncodeByteArray(s.Value, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -1008,7 +1103,9 @@ func (s *SignParameters) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Algorithm", &s.Algorithm) delete(rawMsg, key) case "value": - err = runtime.DecodeByteArray(string(val), &s.Value, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.Value, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -1061,8 +1158,12 @@ func (u *UpdateKeyParameters) UnmarshalJSON(data []byte) error { func (v VerifyParameters) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "alg", v.Algorithm) - populateByteArray(objectMap, "digest", v.Digest, runtime.Base64URLFormat) - populateByteArray(objectMap, "value", v.Signature, runtime.Base64URLFormat) + populateByteArray(objectMap, "digest", v.Digest, func() any { + return runtime.EncodeByteArray(v.Digest, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", v.Signature, func() any { + return runtime.EncodeByteArray(v.Signature, runtime.Base64URLFormat) + }) return json.Marshal(objectMap) } @@ -1079,10 +1180,14 @@ func (v *VerifyParameters) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Algorithm", &v.Algorithm) delete(rawMsg, key) case "digest": - err = runtime.DecodeByteArray(string(val), &v.Digest, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.Digest, runtime.Base64URLFormat) + } delete(rawMsg, key) case "value": - err = runtime.DecodeByteArray(string(val), &v.Signature, runtime.Base64URLFormat) + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.Signature, runtime.Base64URLFormat) + } delete(rawMsg, key) } if err != nil { @@ -1102,18 +1207,18 @@ func populate(m map[string]any, k string, v any) { } } -func populateByteArray(m map[string]any, k string, b []byte, f runtime.Base64Encoding) { +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { if azcore.IsNullValue(b) { m[k] = nil } else if len(b) == 0 { return } else { - m[k] = runtime.EncodeByteArray(b, f) + m[k] = convert() } } func unpopulate(data json.RawMessage, fn string, v any) error { - if data == nil { + if data == nil || string(data) == "null" { return nil } if err := json.Unmarshal(data, v); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/options.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/options.go index e3043e7a17e..3fa3e088814 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/options.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/options.go @@ -1,10 +1,6 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys @@ -58,8 +54,7 @@ type ImportKeyOptions struct { // placeholder for future optional parameters } -// ListDeletedKeyPropertiesOptions contains the optional parameters for the Client.NewListDeletedKeyPropertiesPager -// method. +// ListDeletedKeyPropertiesOptions contains the optional parameters for the Client.NewListDeletedKeyPropertiesPager method. type ListDeletedKeyPropertiesOptions struct { // placeholder for future optional parameters } @@ -69,8 +64,7 @@ type ListKeyPropertiesOptions struct { // placeholder for future optional parameters } -// ListKeyPropertiesVersionsOptions contains the optional parameters for the Client.NewListKeyPropertiesVersionsPager -// method. +// ListKeyPropertiesVersionsOptions contains the optional parameters for the Client.NewListKeyPropertiesVersionsPager method. type ListKeyPropertiesVersionsOptions struct { // placeholder for future optional parameters } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/response_types.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/responses.go similarity index 95% rename from vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/response_types.go rename to vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/responses.go index b1b4678ea65..17e2451be13 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/response_types.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/responses.go @@ -1,10 +1,6 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/time_unix.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/time_unix.go index 63591b5df9f..922f0854756 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/time_unix.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/time_unix.go @@ -1,20 +1,16 @@ -//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. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package azkeys import ( "encoding/json" "fmt" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" "reflect" - "strings" "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) type timeUnix time.Time @@ -49,7 +45,7 @@ func populateTimeUnix(m map[string]any, k string, t *time.Time) { } func unpopulateTimeUnix(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux timeUnix diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/tsp-location.yaml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/tsp-location.yaml new file mode 100644 index 00000000000..cecc0869850 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/tsp-location.yaml @@ -0,0 +1,6 @@ +directory: specification/keyvault/Security.KeyVault.Keys +commit: de825aa1e9bc91476240630a2142d42a380de1c9 +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common/ +# https://github.com/Azure/azure-rest-api-specs/tree/de825aa1e9bc91476240630a2142d42a380de1c9/specification/keyvault/Security.KeyVault.Keys diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/version.go index ca940117456..7be3860c79e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys/version.go @@ -1,6 +1,3 @@ -//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. @@ -8,5 +5,5 @@ package azkeys const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys" - version = "v1.3.0" + version = "v1.3.1" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/CHANGELOG.md index 873368aa1a0..8027787cd66 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/CHANGELOG.md @@ -1,5 +1,10 @@ # Release History +## 1.1.1 (2025-02-13) + +### Bugs Fixed +* Fixed data race when using Client from multiple goroutines concurrently (thanks, @strager) + ## 1.1.0 (2024-10-21) ### Features Added diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/challenge_policy.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/challenge_policy.go index 408ae052b3a..b6d21970b70 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/challenge_policy.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/challenge_policy.go @@ -13,6 +13,7 @@ import ( "net/http" "net/url" "strings" + "sync" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" @@ -30,7 +31,12 @@ type KeyVaultChallengePolicyOptions struct { type keyVaultAuthorizer struct { // tro is the policy's authentication parameters. These are discovered from an authentication challenge // elicited ahead of the first client request. - tro policy.TokenRequestOptions + // + // Protected by troLock. + tro policy.TokenRequestOptions + // Lock protecting tro in case there are multiple concurrent initial requests. + troLock sync.RWMutex + verifyChallengeResource bool } @@ -55,7 +61,8 @@ func NewKeyVaultChallengePolicy(cred azcore.TokenCredential, opts *KeyVaultChall } func (k *keyVaultAuthorizer) authorize(req *policy.Request, authNZ func(policy.TokenRequestOptions) error) error { - if len(k.tro.Scopes) == 0 || k.tro.TenantID == "" { + tro := k.getTokenRequestOptions() + if len(tro.Scopes) == 0 || tro.TenantID == "" { if body := req.Body(); body != nil { // We don't know the scope or tenant ID because we haven't seen a challenge yet. We elicit one now by sending // the request without authorization, first removing its body, if any. authorizeOnChallenge will reattach the @@ -70,7 +77,7 @@ func (k *keyVaultAuthorizer) authorize(req *policy.Request, authNZ func(policy.T return nil } // else we know the auth parameters and can authorize the request as normal - return authNZ(k.tro) + return authNZ(tro) } func (k *keyVaultAuthorizer) authorizeOnChallenge(req *policy.Request, res *http.Response, authNZ func(policy.TokenRequestOptions) error) error { @@ -87,7 +94,7 @@ func (k *keyVaultAuthorizer) authorizeOnChallenge(req *policy.Request, res *http } } // authenticate with the parameters supplied by Key Vault, authorize the request, send it again - return authNZ(k.tro) + return authNZ(k.getTokenRequestOptions()) } // parses Tenant ID from auth challenge @@ -126,7 +133,6 @@ func (k *keyVaultAuthorizer) updateTokenRequestOptions(resp *http.Response, req } } - k.tro.TenantID = parseTenant(vals["authorization"]) scope := "" if v, ok := vals["scope"]; ok { scope = v @@ -149,6 +155,25 @@ func (k *keyVaultAuthorizer) updateTokenRequestOptions(resp *http.Response, req if !strings.HasSuffix(scope, "/.default") { scope += "/.default" } - k.tro.Scopes = []string{scope} + k.setTokenRequestOptions(policy.TokenRequestOptions{ + TenantID: parseTenant(vals["authorization"]), + Scopes: []string{scope}, + }) return nil } + +// Returns a (possibly-zero) copy of TokenRequestOptions. +// +// The returned value's Scopes and other fields must not be modified. +func (k *keyVaultAuthorizer) getTokenRequestOptions() policy.TokenRequestOptions { + k.troLock.RLock() + defer k.troLock.RUnlock() + return k.tro // Copy. +} + +// After calling this function, tro.Scopes and other fields must not be modified. +func (k *keyVaultAuthorizer) setTokenRequestOptions(tro policy.TokenRequestOptions) { + k.troLock.Lock() + defer k.troLock.Unlock() + k.tro = tro // Copy. +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/ci.keyvault.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/ci.keyvault.yml index ba8690ac3d0..5f419255b3c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/ci.keyvault.yml +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/ci.keyvault.yml @@ -26,3 +26,4 @@ extends: parameters: ServiceDirectory: 'security/keyvault/internal' RunLiveTests: false + EnableRaceDetector: true diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/constants.go index 5a037978fa0..40eef60bd1f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/constants.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal/constants.go @@ -7,5 +7,5 @@ package internal const ( - version = "v1.1.0" //nolint + version = "v1.1.1" //nolint ) diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go index 57d0e2777e1..549d68ab991 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go @@ -65,6 +65,13 @@ type AuthenticationScheme = authority.AuthenticationScheme type Account = shared.Account +type TokenSource = base.TokenSource + +const ( + TokenSourceIdentityProvider = base.TokenSourceIdentityProvider + TokenSourceCache = base.TokenSourceCache +) + // CertFromPEM converts a PEM file (.pem or .key) for use with [NewCredFromCert]. The file // must contain the public certificate and the private key. If a PEM block is encrypted and // password is not an empty string, it attempts to decrypt the PEM blocks using the password. @@ -305,7 +312,9 @@ func WithInstanceDiscovery(enabled bool) Option { // If an invalid region name is provided, the non-regional endpoint MIGHT be used or the token request MIGHT fail. func WithAzureRegion(val string) Option { return func(o *clientOptions) { - o.azureRegion = val + if val != "" { + o.azureRegion = val + } } } @@ -429,6 +438,7 @@ func WithClaims(claims string) interface { AcquireByAuthCodeOption AcquireByCredentialOption AcquireOnBehalfOfOption + AcquireByUsernamePasswordOption AcquireSilentOption AuthCodeURLOption options.CallOption @@ -437,6 +447,7 @@ func WithClaims(claims string) interface { AcquireByAuthCodeOption AcquireByCredentialOption AcquireOnBehalfOfOption + AcquireByUsernamePasswordOption AcquireSilentOption AuthCodeURLOption options.CallOption @@ -450,6 +461,8 @@ func WithClaims(claims string) interface { t.claims = claims case *acquireTokenOnBehalfOfOptions: t.claims = claims + case *acquireTokenByUsernamePasswordOptions: + t.claims = claims case *acquireTokenSilentOptions: t.claims = claims case *authCodeURLOptions: @@ -496,6 +509,7 @@ func WithTenantID(tenantID string) interface { AcquireByAuthCodeOption AcquireByCredentialOption AcquireOnBehalfOfOption + AcquireByUsernamePasswordOption AcquireSilentOption AuthCodeURLOption options.CallOption @@ -504,6 +518,7 @@ func WithTenantID(tenantID string) interface { AcquireByAuthCodeOption AcquireByCredentialOption AcquireOnBehalfOfOption + AcquireByUsernamePasswordOption AcquireSilentOption AuthCodeURLOption options.CallOption @@ -517,6 +532,8 @@ func WithTenantID(tenantID string) interface { t.tenantID = tenantID case *acquireTokenOnBehalfOfOptions: t.tenantID = tenantID + case *acquireTokenByUsernamePasswordOptions: + t.tenantID = tenantID case *acquireTokenSilentOptions: t.tenantID = tenantID case *authCodeURLOptions: @@ -592,6 +609,46 @@ func (cca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts return cca.base.AcquireTokenSilent(ctx, silentParameters) } +// acquireTokenByUsernamePasswordOptions contains optional configuration for AcquireTokenByUsernamePassword +type acquireTokenByUsernamePasswordOptions struct { + claims, tenantID string + authnScheme AuthenticationScheme +} + +// AcquireByUsernamePasswordOption is implemented by options for AcquireTokenByUsernamePassword +type AcquireByUsernamePasswordOption interface { + acquireByUsernamePasswordOption() +} + +// AcquireTokenByUsernamePassword acquires a security token from the authority, via Username/Password Authentication. +// NOTE: this flow is NOT recommended. +// +// Options: [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username, password string, opts ...AcquireByUsernamePasswordOption) (AuthResult, error) { + o := acquireTokenByUsernamePasswordOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + authParams, err := cca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATUsernamePassword + authParams.Claims = o.claims + authParams.Username = username + authParams.Password = password + if o.authnScheme != nil { + authParams.AuthnScheme = o.authnScheme + } + + token, err := cca.base.Token.UsernamePassword(ctx, authParams) + if err != nil { + return AuthResult{}, err + } + return cca.base.AuthResultFromToken(ctx, authParams, token) +} + // acquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow. type acquireTokenByAuthCodeOptions struct { challenge, claims, tenantID string @@ -683,7 +740,7 @@ func (cca Client) AcquireTokenByCredential(ctx context.Context, scopes []string, if err != nil { return AuthResult{}, err } - return cca.base.AuthResultFromToken(ctx, authParams, token, true) + return cca.base.AuthResultFromToken(ctx, authParams, token) } // acquireTokenOnBehalfOfOptions contains optional configuration for AcquireTokenOnBehalfOf diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go index c9b8dbed088..b5cbb572177 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go @@ -64,11 +64,20 @@ type CallErr struct { Err error } +type InvalidJsonErr struct { + Err error +} + // Errors implements error.Error(). func (e CallErr) Error() string { return e.Err.Error() } +// Errors implements error.Error(). +func (e InvalidJsonErr) Error() string { + return e.Err.Error() +} + // Verbose prints a versbose error message with the request or response. func (e CallErr) Verbose() string { e.Resp.Request = nil // This brings in a bunch of TLS crap we don't need diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go index e473d1267da..61c1c4cec1e 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go @@ -5,16 +5,17 @@ package base import ( "context" - "errors" "fmt" "net/url" "reflect" "strings" "sync" + "sync/atomic" "time" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" - "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" @@ -94,6 +95,7 @@ type AuthResult struct { // AuthResultMetadata which contains meta data for the AuthResult type AuthResultMetadata struct { + RefreshOn time.Time TokenSource TokenSource } @@ -101,9 +103,8 @@ type TokenSource int // These are all the types of token flows. const ( - SourceUnknown TokenSource = 0 - IdentityProvider TokenSource = 1 - Cache TokenSource = 2 + TokenSourceIdentityProvider TokenSource = 0 + TokenSourceCache TokenSource = 1 ) // AuthResultFromStorage creates an AuthResult from a storage token response (which is generated from the cache). @@ -111,7 +112,6 @@ func AuthResultFromStorage(storageTokenResponse storage.TokenResponse) (AuthResu if err := storageTokenResponse.AccessToken.Validate(); err != nil { return AuthResult{}, fmt.Errorf("problem with access token in StorageTokenResponse: %w", err) } - account := storageTokenResponse.Account accessToken := storageTokenResponse.AccessToken.Secret grantedScopes := strings.Split(storageTokenResponse.AccessToken.Scopes, scopeSeparator) @@ -132,7 +132,8 @@ func AuthResultFromStorage(storageTokenResponse storage.TokenResponse) (AuthResu GrantedScopes: grantedScopes, DeclinedScopes: nil, Metadata: AuthResultMetadata{ - TokenSource: Cache, + TokenSource: TokenSourceCache, + RefreshOn: storageTokenResponse.AccessToken.RefreshOn.T, }, }, nil } @@ -146,10 +147,11 @@ func NewAuthResult(tokenResponse accesstokens.TokenResponse, account shared.Acco Account: account, IDToken: tokenResponse.IDToken, AccessToken: tokenResponse.AccessToken, - ExpiresOn: tokenResponse.ExpiresOn.T, + ExpiresOn: tokenResponse.ExpiresOn, GrantedScopes: tokenResponse.GrantedScopes.Slice, Metadata: AuthResultMetadata{ - TokenSource: IdentityProvider, + TokenSource: TokenSourceIdentityProvider, + RefreshOn: tokenResponse.RefreshOn.T, }, }, nil } @@ -165,6 +167,8 @@ type Client struct { AuthParams authority.AuthParams // DO NOT EVER MAKE THIS A POINTER! See "Note" in New(). cacheAccessor cache.ExportReplace cacheAccessorMu *sync.RWMutex + canRefresh map[string]*atomic.Value + canRefreshMu *sync.Mutex } // Option is an optional argument to the New constructor. @@ -241,6 +245,8 @@ func New(clientID string, authorityURI string, token *oauth.Client, options ...O cacheAccessorMu: &sync.RWMutex{}, manager: storage.New(token), pmanager: storage.NewPartitionedManager(token), + canRefresh: make(map[string]*atomic.Value), + canRefreshMu: &sync.Mutex{}, } for _, o := range options { if err = o(&client); err != nil { @@ -345,6 +351,28 @@ func (b Client) AcquireTokenSilent(ctx context.Context, silent AcquireTokenSilen if silent.Claims == "" { ar, err = AuthResultFromStorage(storageTokenResponse) if err == nil { + if rt := storageTokenResponse.AccessToken.RefreshOn.T; !rt.IsZero() && Now().After(rt) { + b.canRefreshMu.Lock() + refreshValue, ok := b.canRefresh[tenant] + if !ok { + refreshValue = &atomic.Value{} + refreshValue.Store(false) + b.canRefresh[tenant] = refreshValue + } + b.canRefreshMu.Unlock() + if refreshValue.CompareAndSwap(false, true) { + defer refreshValue.Store(false) + // Added a check to see if the token is still same because there is a chance + // that the token is already refreshed by another thread. + // If the token is not same, we don't need to refresh it. + // Which means it refreshed. + if str, err := m.Read(ctx, authParams); err == nil && str.AccessToken.Secret == ar.AccessToken { + if tr, er := b.Token.Credential(ctx, authParams, silent.Credential); er == nil { + return b.AuthResultFromToken(ctx, authParams, tr) + } + } + } + } ar.AccessToken, err = authParams.AuthnScheme.FormatAccessToken(ar.AccessToken) return ar, err } @@ -362,7 +390,7 @@ func (b Client) AcquireTokenSilent(ctx context.Context, silent AcquireTokenSilen if err != nil { return ar, err } - return b.AuthResultFromToken(ctx, authParams, token, true) + return b.AuthResultFromToken(ctx, authParams, token) } func (b Client) AcquireTokenByAuthCode(ctx context.Context, authCodeParams AcquireTokenAuthCodeParameters) (AuthResult, error) { @@ -391,7 +419,7 @@ func (b Client) AcquireTokenByAuthCode(ctx context.Context, authCodeParams Acqui return AuthResult{}, err } - return b.AuthResultFromToken(ctx, authParams, token, true) + return b.AuthResultFromToken(ctx, authParams, token) } // AcquireTokenOnBehalfOf acquires a security token for an app using middle tier apps access token. @@ -420,15 +448,12 @@ func (b Client) AcquireTokenOnBehalfOf(ctx context.Context, onBehalfOfParams Acq authParams.UserAssertion = onBehalfOfParams.UserAssertion token, err := b.Token.OnBehalfOf(ctx, authParams, onBehalfOfParams.Credential) if err == nil { - ar, err = b.AuthResultFromToken(ctx, authParams, token, true) + ar, err = b.AuthResultFromToken(ctx, authParams, token) } return ar, err } -func (b Client) AuthResultFromToken(ctx context.Context, authParams authority.AuthParams, token accesstokens.TokenResponse, cacheWrite bool) (AuthResult, error) { - if !cacheWrite { - return NewAuthResult(token, shared.Account{}) - } +func (b Client) AuthResultFromToken(ctx context.Context, authParams authority.AuthParams, token accesstokens.TokenResponse) (AuthResult, error) { var m manager = b.manager if authParams.AuthorizationType == authority.ATOnBehalfOf { m = b.pmanager @@ -458,6 +483,10 @@ func (b Client) AuthResultFromToken(ctx context.Context, authParams authority.Au return ar, err } +// This function wraps time.Now() and is used for refreshing the application +// was created to test the function against refreshin +var Now = time.Now + func (b Client) AllAccounts(ctx context.Context) ([]shared.Account, error) { if b.cacheAccessor != nil { b.cacheAccessorMu.RLock() diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/items.go similarity index 95% rename from vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go rename to vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/items.go index f9be90276da..7379e2233c8 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/items.go @@ -72,6 +72,7 @@ type AccessToken struct { ClientID string `json:"client_id,omitempty"` Secret string `json:"secret,omitempty"` Scopes string `json:"target,omitempty"` + RefreshOn internalTime.Unix `json:"refresh_on,omitempty"` ExpiresOn internalTime.Unix `json:"expires_on,omitempty"` ExtendedExpiresOn internalTime.Unix `json:"extended_expires_on,omitempty"` CachedAt internalTime.Unix `json:"cached_at,omitempty"` @@ -83,7 +84,7 @@ type AccessToken struct { } // NewAccessToken is the constructor for AccessToken. -func NewAccessToken(homeID, env, realm, clientID string, cachedAt, expiresOn, extendedExpiresOn time.Time, scopes, token, tokenType, authnSchemeKeyID string) AccessToken { +func NewAccessToken(homeID, env, realm, clientID string, cachedAt, refreshOn, expiresOn, extendedExpiresOn time.Time, scopes, token, tokenType, authnSchemeKeyID string) AccessToken { return AccessToken{ HomeAccountID: homeID, Environment: env, @@ -93,6 +94,7 @@ func NewAccessToken(homeID, env, realm, clientID string, cachedAt, expiresOn, ex Secret: token, Scopes: scopes, CachedAt: internalTime.Unix{T: cachedAt.UTC()}, + RefreshOn: internalTime.Unix{T: refreshOn.UTC()}, ExpiresOn: internalTime.Unix{T: expiresOn.UTC()}, ExtendedExpiresOn: internalTime.Unix{T: extendedExpiresOn.UTC()}, TokenType: tokenType, @@ -102,8 +104,9 @@ func NewAccessToken(homeID, env, realm, clientID string, cachedAt, expiresOn, ex // Key outputs the key that can be used to uniquely look up this entry in a map. func (a AccessToken) Key() string { + ks := []string{a.HomeAccountID, a.Environment, a.CredentialType, a.ClientID, a.Realm, a.Scopes} key := strings.Join( - []string{a.HomeAccountID, a.Environment, a.CredentialType, a.ClientID, a.Realm, a.Scopes}, + ks, shared.CacheKeySeparator, ) // add token type to key for new access tokens types. skip for bearer token type to diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/partitioned_storage.go similarity index 99% rename from vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go rename to vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/partitioned_storage.go index c0931833064..ff07d4b5a4f 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/partitioned_storage.go @@ -114,7 +114,8 @@ func (m *PartitionedManager) Write(authParameters authority.AuthParams, tokenRes realm, clientID, cachedAt, - tokenResponse.ExpiresOn.T, + tokenResponse.RefreshOn.T, + tokenResponse.ExpiresOn, tokenResponse.ExtExpiresOn.T, target, tokenResponse.AccessToken, diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/storage.go similarity index 98% rename from vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go rename to vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/storage.go index 2221e60c437..84a234967ff 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage/storage.go @@ -173,6 +173,7 @@ func (m *Manager) Write(authParameters authority.AuthParams, tokenResponse acces environment := authParameters.AuthorityInfo.Host realm := authParameters.AuthorityInfo.Tenant clientID := authParameters.ClientID + target := strings.Join(tokenResponse.GrantedScopes.Slice, scopeSeparator) cachedAt := time.Now() authnSchemeKeyID := authParameters.AuthnScheme.KeyID() @@ -193,7 +194,8 @@ func (m *Manager) Write(authParameters authority.AuthParams, tokenResponse acces realm, clientID, cachedAt, - tokenResponse.ExpiresOn.T, + tokenResponse.RefreshOn.T, + tokenResponse.ExpiresOn, tokenResponse.ExtExpiresOn.T, target, tokenResponse.AccessToken, @@ -265,6 +267,9 @@ func (m *Manager) aadMetadataFromCache(ctx context.Context, authorityInfo author } func (m *Manager) aadMetadata(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + if m.requests == nil { + return authority.InstanceDiscoveryMetadata{}, fmt.Errorf("httpclient in oauth instance for fetching metadata is nil") + } m.aadCacheMu.Lock() defer m.aadCacheMu.Unlock() discoveryResponse, err := m.requests.AADInstanceDiscovery(ctx, authorityInfo) @@ -459,6 +464,7 @@ func (m *Manager) readAccount(homeAccountID string, envAliases []string, realm s func (m *Manager) writeAccount(account shared.Account) error { key := account.Key() + m.contractMu.Lock() defer m.contractMu.Unlock() m.contract.Accounts[key] = account diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go index 7b673e3fe12..de1bf381f41 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go @@ -31,4 +31,6 @@ type TokenProviderResult struct { AccessToken string // ExpiresInSeconds is the lifetime of the token in seconds ExpiresInSeconds int + // RefreshInSeconds indicates the suggested time to refresh the token, if any + RefreshInSeconds int } diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go index fda5d7dd333..cda678e3342 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go @@ -146,7 +146,8 @@ func (s *Server) handler(w http.ResponseWriter, r *http.Request) { // Note: It is a little weird we handle some errors by not going to the failPage. If they all should, // change this to s.error() and make s.error() write the failPage instead of an error code. _, _ = w.Write([]byte(fmt.Sprintf(failPage, headerErr, desc))) - s.putResult(Result{Err: fmt.Errorf(desc)}) + s.putResult(Result{Err: fmt.Errorf("%s", desc)}) + return } diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go index e0653134448..738a29eb9d7 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go @@ -111,7 +111,7 @@ func (t *Client) Credential(ctx context.Context, authParams authority.AuthParams Scopes: scopes, TenantID: authParams.AuthorityInfo.Tenant, } - tr, err := cred.TokenProvider(ctx, params) + pr, err := cred.TokenProvider(ctx, params) if err != nil { if len(scopes) == 0 { err = fmt.Errorf("token request had an empty authority.AuthParams.Scopes, which may cause the following error: %w", err) @@ -119,14 +119,18 @@ func (t *Client) Credential(ctx context.Context, authParams authority.AuthParams } return accesstokens.TokenResponse{}, err } - return accesstokens.TokenResponse{ - TokenType: authParams.AuthnScheme.AccessTokenType(), - AccessToken: tr.AccessToken, - ExpiresOn: internalTime.DurationTime{ - T: now.Add(time.Duration(tr.ExpiresInSeconds) * time.Second), - }, + tr := accesstokens.TokenResponse{ + TokenType: authParams.AuthnScheme.AccessTokenType(), + AccessToken: pr.AccessToken, + ExpiresOn: now.Add(time.Duration(pr.ExpiresInSeconds) * time.Second), GrantedScopes: accesstokens.Scopes{Slice: authParams.Scopes}, - }, nil + } + if pr.RefreshInSeconds > 0 { + tr.RefreshOn = internalTime.DurationTime{ + T: now.Add(time.Duration(pr.RefreshInSeconds) * time.Second), + } + } + return tr, nil } if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go index a7b7b0742d8..d738c7591ee 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go @@ -17,6 +17,7 @@ import ( /* #nosec */ "crypto/sha1" + "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/json" @@ -68,7 +69,7 @@ type DeviceCodeResponse struct { UserCode string `json:"user_code"` DeviceCode string `json:"device_code"` - VerificationURL string `json:"verification_url"` + VerificationURL string `json:"verification_uri"` ExpiresIn int `json:"expires_in"` Interval int `json:"interval"` Message string `json:"message"` @@ -112,19 +113,31 @@ func (c *Credential) JWT(ctx context.Context, authParams authority.AuthParams) ( } return c.AssertionCallback(ctx, options) } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + claims := jwt.MapClaims{ "aud": authParams.Endpoints.TokenEndpoint, "exp": json.Number(strconv.FormatInt(time.Now().Add(10*time.Minute).Unix(), 10)), "iss": authParams.ClientID, "jti": uuid.New().String(), "nbf": json.Number(strconv.FormatInt(time.Now().Unix(), 10)), "sub": authParams.ClientID, - }) + } + + isADFSorDSTS := authParams.AuthorityInfo.AuthorityType == authority.ADFS || + authParams.AuthorityInfo.AuthorityType == authority.DSTS + + var signingMethod jwt.SigningMethod = jwt.SigningMethodPS256 + thumbprintKey := "x5t#S256" + + if isADFSorDSTS { + signingMethod = jwt.SigningMethodRS256 + thumbprintKey = "x5t" + } + + token := jwt.NewWithClaims(signingMethod, claims) token.Header = map[string]interface{}{ - "alg": "RS256", - "typ": "JWT", - "x5t": base64.StdEncoding.EncodeToString(thumbprint(c.Cert)), + "alg": signingMethod.Alg(), + "typ": "JWT", + thumbprintKey: base64.StdEncoding.EncodeToString(thumbprint(c.Cert, signingMethod.Alg())), } if authParams.SendX5C { @@ -133,17 +146,23 @@ func (c *Credential) JWT(ctx context.Context, authParams authority.AuthParams) ( assertion, err := token.SignedString(c.Key) if err != nil { - return "", fmt.Errorf("unable to sign a JWT token using private key: %w", err) + return "", fmt.Errorf("unable to sign JWT token: %w", err) } + return assertion, nil } // thumbprint runs the asn1.Der bytes through sha1 for use in the x5t parameter of JWT. // https://tools.ietf.org/html/rfc7517#section-4.8 -func thumbprint(cert *x509.Certificate) []byte { - /* #nosec */ - a := sha1.Sum(cert.Raw) - return a[:] +func thumbprint(cert *x509.Certificate, alg string) []byte { + switch alg { + case jwt.SigningMethodRS256.Name: // identity providers like ADFS don't support SHA256 assertions, so need to support this + hash := sha1.Sum(cert.Raw) /* #nosec */ + return hash[:] + default: + hash := sha256.Sum256(cert.Raw) + return hash[:] + } } // Client represents the REST calls to get tokens from token generator backends. @@ -262,11 +281,7 @@ func (c Client) FromClientSecret(ctx context.Context, authParameters authority.A qv.Set(clientID, authParameters.ClientID) addScopeQueryParam(qv, authParameters) - token, err := c.doTokenResp(ctx, authParameters, qv) - if err != nil { - return token, fmt.Errorf("FromClientSecret(): %w", err) - } - return token, nil + return c.doTokenResp(ctx, authParameters, qv) } func (c Client) FromAssertion(ctx context.Context, authParameters authority.AuthParams, assertion string) (TokenResponse, error) { @@ -281,11 +296,7 @@ func (c Client) FromAssertion(ctx context.Context, authParameters authority.Auth qv.Set(clientInfo, clientInfoVal) addScopeQueryParam(qv, authParameters) - token, err := c.doTokenResp(ctx, authParameters, qv) - if err != nil { - return token, fmt.Errorf("FromAssertion(): %w", err) - } - return token, nil + return c.doTokenResp(ctx, authParameters, qv) } func (c Client) FromUserAssertionClientSecret(ctx context.Context, authParameters authority.AuthParams, userAssertion string, clientSecret string) (TokenResponse, error) { diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go index 3107b45c113..32dde7b76b9 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "reflect" + "strconv" "strings" "time" @@ -173,14 +174,75 @@ type TokenResponse struct { FamilyID string `json:"foci"` IDToken IDToken `json:"id_token"` ClientInfo ClientInfo `json:"client_info"` - ExpiresOn internalTime.DurationTime `json:"expires_in"` + RefreshOn internalTime.DurationTime `json:"refresh_in,omitempty"` + ExpiresOn time.Time `json:"-"` ExtExpiresOn internalTime.DurationTime `json:"ext_expires_in"` GrantedScopes Scopes `json:"scope"` DeclinedScopes []string // This is derived AdditionalFields map[string]interface{} + scopesComputed bool +} + +func (tr *TokenResponse) UnmarshalJSON(data []byte) error { + type Alias TokenResponse + aux := &struct { + ExpiresIn internalTime.DurationTime `json:"expires_in,omitempty"` + ExpiresOn any `json:"expires_on,omitempty"` + *Alias + }{ + Alias: (*Alias)(tr), + } + + // Unmarshal the JSON data into the aux struct + if err := json.Unmarshal(data, &aux); err != nil { + return err + } + + // Function to parse different date formats + // This is a workaround for the issue described here: + // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/4963 + parseExpiresOn := func(expiresOn string) (time.Time, error) { + var formats = []string{ + "01/02/2006 15:04:05", // MM/dd/yyyy HH:mm:ss + "2006-01-02 15:04:05", // yyyy-MM-dd HH:mm:ss + time.RFC3339Nano, // ISO 8601 (with nanosecond precision) + } + + for _, format := range formats { + if t, err := time.Parse(format, expiresOn); err == nil { + return t, nil + } + } + return time.Time{}, fmt.Errorf("invalid ExpiresOn format: %s", expiresOn) + } - scopesComputed bool + if expiresOnStr, ok := aux.ExpiresOn.(string); ok { + if ts, err := strconv.ParseInt(expiresOnStr, 10, 64); err == nil { + tr.ExpiresOn = time.Unix(ts, 0) + return nil + } + if expiresOnStr != "" { + if t, err := parseExpiresOn(expiresOnStr); err != nil { + return err + } else { + tr.ExpiresOn = t + return nil + } + } + } + + // Check if ExpiresOn is a number (Unix timestamp or ISO 8601) + if expiresOnNum, ok := aux.ExpiresOn.(float64); ok { + tr.ExpiresOn = time.Unix(int64(expiresOnNum), 0) + return nil + } + + if !aux.ExpiresIn.T.IsZero() { + tr.ExpiresOn = aux.ExpiresIn.T + return nil + } + return errors.New("expires_in and expires_on are both missing or invalid") } // ComputeScope computes the final scopes based on what was granted by the server and diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go index 362406554f2..c3c4a96fc30 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go @@ -380,8 +380,9 @@ func NewInfoFromAuthorityURI(authority string, validateAuthority bool, instanceD return Info{}, errors.New(`authority must be an URL such as "https://login.microsoftonline.com/"`) } - var authorityType, tenant string - switch pathParts[1] { + authorityType := AAD + tenant := pathParts[1] + switch tenant { case "adfs": authorityType = ADFS case "dstsv2": @@ -393,9 +394,6 @@ func NewInfoFromAuthorityURI(authority string, validateAuthority bool, instanceD } authorityType = DSTS tenant = DSTSTenant - default: - authorityType = AAD - tenant = pathParts[1] } // u.Host includes the port, if any, which is required for private cloud deployments diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go index d62aac74eb9..79068036694 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go @@ -98,7 +98,7 @@ func (c *Client) JSONCall(ctx context.Context, endpoint string, headers http.Hea if resp != nil { if err := unmarshal(data, resp); err != nil { - return fmt.Errorf("json decode error: %w\njson message bytes were: %s", err, string(data)) + return errors.InvalidJsonErr{Err: fmt.Errorf("json decode error: %w\njson message bytes were: %s", err, string(data))} } } return nil @@ -221,7 +221,7 @@ func (c *Client) URLFormCall(ctx context.Context, endpoint string, qv url.Values } if resp != nil { if err := unmarshal(data, resp); err != nil { - return fmt.Errorf("json decode error: %w\nraw message was: %s", err, string(data)) + return errors.InvalidJsonErr{Err: fmt.Errorf("json decode error: %w\nraw message was: %s", err, string(data))} } } return nil diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go index eb16b405c4b..5e551abc83e 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go @@ -5,4 +5,4 @@ package version // Version is the version of this client package that is communicated to the server. -const Version = "1.2.0" +const Version = "1.4.2" diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/azure_ml.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/azure_ml.go new file mode 100644 index 00000000000..d7cffc295e9 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/azure_ml.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package managedidentity + +import ( + "context" + "net/http" + "os" +) + +func createAzureMLAuthRequest(ctx context.Context, id ID, resource string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, os.Getenv(msiEndpointEnvVar), nil) + if err != nil { + return nil, err + } + + req.Header.Set("secret", os.Getenv(msiSecretEnvVar)) + q := req.URL.Query() + q.Set(apiVersionQueryParameterName, azureMLAPIVersion) + q.Set(resourceQueryParameterName, resource) + q.Set("clientid", os.Getenv("DEFAULT_IDENTITY_CLIENT_ID")) + if cid, ok := id.(UserAssignedClientID); ok { + q.Set("clientid", string(cid)) + } + req.URL.RawQuery = q.Encode() + return req, nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/cloud_shell.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/cloud_shell.go new file mode 100644 index 00000000000..be9a0bca382 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/cloud_shell.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package managedidentity + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" +) + +func createCloudShellAuthRequest(ctx context.Context, resource string) (*http.Request, error) { + msiEndpoint := os.Getenv(msiEndpointEnvVar) + msiEndpointParsed, err := url.Parse(msiEndpoint) + if err != nil { + return nil, fmt.Errorf("couldn't parse %q: %s", msiEndpoint, err) + } + + data := url.Values{} + data.Set(resourceQueryParameterName, resource) + msiDataEncoded := data.Encode() + body := io.NopCloser(strings.NewReader(msiDataEncoded)) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, msiEndpointParsed.String(), body) + if err != nil { + return nil, fmt.Errorf("error creating http request %s", err) + } + + req.Header.Set(metaHTTPHeaderName, "true") + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + return req, nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/managedidentity.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/managedidentity.go new file mode 100644 index 00000000000..ca3de4325f4 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/managedidentity.go @@ -0,0 +1,717 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package managedidentity provides a client for retrieval of Managed Identity applications. +The Managed Identity Client is used to acquire a token for managed identity assigned to +an azure resource such as Azure function, app service, virtual machine, etc. to acquire a token +without using credentials. +*/ +package managedidentity + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// AuthResult contains the results of one token acquisition operation. +// For details see https://aka.ms/msal-net-authenticationresult +type AuthResult = base.AuthResult + +type TokenSource = base.TokenSource + +const ( + TokenSourceIdentityProvider = base.TokenSourceIdentityProvider + TokenSourceCache = base.TokenSourceCache +) + +const ( + // DefaultToIMDS indicates that the source is defaulted to IMDS when no environment variables are set. + DefaultToIMDS Source = "DefaultToIMDS" + AzureArc Source = "AzureArc" + ServiceFabric Source = "ServiceFabric" + CloudShell Source = "CloudShell" + AzureML Source = "AzureML" + AppService Source = "AppService" + + // General request query parameter names + metaHTTPHeaderName = "Metadata" + apiVersionQueryParameterName = "api-version" + resourceQueryParameterName = "resource" + wwwAuthenticateHeaderName = "www-authenticate" + + // UAMI query parameter name + miQueryParameterClientId = "client_id" + miQueryParameterObjectId = "object_id" + miQueryParameterPrincipalId = "principal_id" + miQueryParameterResourceIdIMDS = "msi_res_id" + miQueryParameterResourceId = "mi_res_id" + + // IMDS + imdsDefaultEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" + imdsAPIVersion = "2018-02-01" + systemAssignedManagedIdentity = "system_assigned_managed_identity" + + // Azure Arc + azureArcEndpoint = "http://127.0.0.1:40342/metadata/identity/oauth2/token" + azureArcAPIVersion = "2020-06-01" + azureArcFileExtension = ".key" + azureArcMaxFileSizeBytes int64 = 4096 + linuxTokenPath = "/var/opt/azcmagent/tokens" // #nosec G101 + linuxHimdsPath = "/opt/azcmagent/bin/himds" + azureConnectedMachine = "AzureConnectedMachineAgent" + himdsExecutableName = "himds.exe" + tokenName = "Tokens" + + // App Service + appServiceAPIVersion = "2019-08-01" + + // AzureML + azureMLAPIVersion = "2017-09-01" + // Service Fabric + serviceFabricAPIVersion = "2019-07-01-preview" + + // Environment Variables + identityEndpointEnvVar = "IDENTITY_ENDPOINT" + identityHeaderEnvVar = "IDENTITY_HEADER" + azurePodIdentityAuthorityHostEnvVar = "AZURE_POD_IDENTITY_AUTHORITY_HOST" + imdsEndVar = "IMDS_ENDPOINT" + msiEndpointEnvVar = "MSI_ENDPOINT" + msiSecretEnvVar = "MSI_SECRET" + identityServerThumbprintEnvVar = "IDENTITY_SERVER_THUMBPRINT" + + defaultRetryCount = 3 +) + +var retryCodesForIMDS = []int{ + http.StatusNotFound, // 404 + http.StatusGone, // 410 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusNotImplemented, // 501 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + http.StatusHTTPVersionNotSupported, // 505 + http.StatusVariantAlsoNegotiates, // 506 + http.StatusInsufficientStorage, // 507 + http.StatusLoopDetected, // 508 + http.StatusNotExtended, // 510 + http.StatusNetworkAuthenticationRequired, // 511 +} + +var retryStatusCodes = []int{ + http.StatusRequestTimeout, // 408 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 +} + +var getAzureArcPlatformPath = func(platform string) string { + switch platform { + case "windows": + return filepath.Join(os.Getenv("ProgramData"), azureConnectedMachine, tokenName) + case "linux": + return linuxTokenPath + default: + return "" + } +} + +var getAzureArcHimdsFilePath = func(platform string) string { + switch platform { + case "windows": + return filepath.Join(os.Getenv("ProgramData"), azureConnectedMachine, himdsExecutableName) + case "linux": + return linuxHimdsPath + default: + return "" + } +} + +type Source string + +type ID interface { + value() string +} + +type systemAssignedValue string // its private for a reason to make the input consistent. +type UserAssignedClientID string +type UserAssignedObjectID string +type UserAssignedResourceID string + +func (s systemAssignedValue) value() string { return string(s) } +func (c UserAssignedClientID) value() string { return string(c) } +func (o UserAssignedObjectID) value() string { return string(o) } +func (r UserAssignedResourceID) value() string { return string(r) } +func SystemAssigned() ID { + return systemAssignedValue(systemAssignedManagedIdentity) +} + +// cache never uses the client because instance discovery is always disabled. +var cacheManager *storage.Manager = storage.New(nil) + +type Client struct { + httpClient ops.HTTPClient + miType ID + source Source + authParams authority.AuthParams + retryPolicyEnabled bool + canRefresh *atomic.Value +} + +type AcquireTokenOptions struct { + claims string +} + +type ClientOption func(*Client) + +type AcquireTokenOption func(o *AcquireTokenOptions) + +// WithClaims sets additional claims to request for the token, such as those required by token revocation or conditional access policies. +// Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded. +func WithClaims(claims string) AcquireTokenOption { + return func(o *AcquireTokenOptions) { + o.claims = claims + } +} + +// WithHTTPClient allows for a custom HTTP client to be set. +func WithHTTPClient(httpClient ops.HTTPClient) ClientOption { + return func(c *Client) { + c.httpClient = httpClient + } +} + +func WithRetryPolicyDisabled() ClientOption { + return func(c *Client) { + c.retryPolicyEnabled = false + } +} + +// Client to be used to acquire tokens for managed identity. +// ID: [SystemAssigned], [UserAssignedClientID], [UserAssignedResourceID], [UserAssignedObjectID] +// +// Options: [WithHTTPClient] +func New(id ID, options ...ClientOption) (Client, error) { + source, err := GetSource() + if err != nil { + return Client{}, err + } + + // Check for user-assigned restrictions based on the source + switch source { + case AzureArc: + switch id.(type) { + case UserAssignedClientID, UserAssignedResourceID, UserAssignedObjectID: + return Client{}, errors.New("Azure Arc doesn't support user-assigned managed identities") + } + case AzureML: + switch id.(type) { + case UserAssignedObjectID, UserAssignedResourceID: + return Client{}, errors.New("Azure ML supports specifying a user-assigned managed identity by client ID only") + } + case CloudShell: + switch id.(type) { + case UserAssignedClientID, UserAssignedResourceID, UserAssignedObjectID: + return Client{}, errors.New("Cloud Shell doesn't support user-assigned managed identities") + } + case ServiceFabric: + switch id.(type) { + case UserAssignedClientID, UserAssignedResourceID, UserAssignedObjectID: + return Client{}, errors.New("Service Fabric API doesn't support specifying a user-assigned identity. The identity is determined by cluster resource configuration. See https://aka.ms/servicefabricmi") + } + } + + switch t := id.(type) { + case UserAssignedClientID: + if len(string(t)) == 0 { + return Client{}, fmt.Errorf("empty %T", t) + } + case UserAssignedResourceID: + if len(string(t)) == 0 { + return Client{}, fmt.Errorf("empty %T", t) + } + case UserAssignedObjectID: + if len(string(t)) == 0 { + return Client{}, fmt.Errorf("empty %T", t) + } + case systemAssignedValue: + default: + return Client{}, fmt.Errorf("unsupported type %T", id) + } + zero := atomic.Value{} + zero.Store(false) + client := Client{ + miType: id, + httpClient: shared.DefaultClient, + retryPolicyEnabled: true, + source: source, + canRefresh: &zero, + } + for _, option := range options { + option(&client) + } + fakeAuthInfo, err := authority.NewInfoFromAuthorityURI("https://login.microsoftonline.com/managed_identity", false, true) + if err != nil { + return Client{}, err + } + client.authParams = authority.NewAuthParams(client.miType.value(), fakeAuthInfo) + return client, nil +} + +// GetSource detects and returns the managed identity source available on the environment. +func GetSource() (Source, error) { + identityEndpoint := os.Getenv(identityEndpointEnvVar) + identityHeader := os.Getenv(identityHeaderEnvVar) + identityServerThumbprint := os.Getenv(identityServerThumbprintEnvVar) + msiEndpoint := os.Getenv(msiEndpointEnvVar) + msiSecret := os.Getenv(msiSecretEnvVar) + imdsEndpoint := os.Getenv(imdsEndVar) + + if identityEndpoint != "" && identityHeader != "" { + if identityServerThumbprint != "" { + return ServiceFabric, nil + } + return AppService, nil + } else if msiEndpoint != "" { + if msiSecret != "" { + return AzureML, nil + } else { + return CloudShell, nil + } + } else if isAzureArcEnvironment(identityEndpoint, imdsEndpoint) { + return AzureArc, nil + } + + return DefaultToIMDS, nil +} + +// This function wraps time.Now() and is used for refreshing the application +// was created to test the function against refreshin +var now = time.Now + +// Acquires tokens from the configured managed identity on an azure resource. +// +// Resource: scopes application is requesting access to +// Options: [WithClaims] +func (c Client) AcquireToken(ctx context.Context, resource string, options ...AcquireTokenOption) (AuthResult, error) { + resource = strings.TrimSuffix(resource, "/.default") + o := AcquireTokenOptions{} + for _, option := range options { + option(&o) + } + c.authParams.Scopes = []string{resource} + + // ignore cached access tokens when given claims + if o.claims == "" { + stResp, err := cacheManager.Read(ctx, c.authParams) + if err != nil { + return AuthResult{}, err + } + ar, err := base.AuthResultFromStorage(stResp) + if err == nil { + if !stResp.AccessToken.RefreshOn.T.IsZero() && !stResp.AccessToken.RefreshOn.T.After(now()) && c.canRefresh.CompareAndSwap(false, true) { + defer c.canRefresh.Store(false) + if tr, er := c.getToken(ctx, resource); er == nil { + return tr, nil + } + } + ar.AccessToken, err = c.authParams.AuthnScheme.FormatAccessToken(ar.AccessToken) + return ar, err + } + } + return c.getToken(ctx, resource) +} + +func (c Client) getToken(ctx context.Context, resource string) (AuthResult, error) { + switch c.source { + case AzureArc: + return c.acquireTokenForAzureArc(ctx, resource) + case AzureML: + return c.acquireTokenForAzureML(ctx, resource) + case CloudShell: + return c.acquireTokenForCloudShell(ctx, resource) + case DefaultToIMDS: + return c.acquireTokenForIMDS(ctx, resource) + case AppService: + return c.acquireTokenForAppService(ctx, resource) + case ServiceFabric: + return c.acquireTokenForServiceFabric(ctx, resource) + default: + return AuthResult{}, fmt.Errorf("unsupported source %q", c.source) + } +} + +func (c Client) acquireTokenForAppService(ctx context.Context, resource string) (AuthResult, error) { + req, err := createAppServiceAuthRequest(ctx, c.miType, resource) + if err != nil { + return AuthResult{}, err + } + tokenResponse, err := c.getTokenForRequest(req, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func (c Client) acquireTokenForIMDS(ctx context.Context, resource string) (AuthResult, error) { + req, err := createIMDSAuthRequest(ctx, c.miType, resource) + if err != nil { + return AuthResult{}, err + } + tokenResponse, err := c.getTokenForRequest(req, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func (c Client) acquireTokenForCloudShell(ctx context.Context, resource string) (AuthResult, error) { + req, err := createCloudShellAuthRequest(ctx, resource) + if err != nil { + return AuthResult{}, err + } + tokenResponse, err := c.getTokenForRequest(req, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func (c Client) acquireTokenForAzureML(ctx context.Context, resource string) (AuthResult, error) { + req, err := createAzureMLAuthRequest(ctx, c.miType, resource) + if err != nil { + return AuthResult{}, err + } + tokenResponse, err := c.getTokenForRequest(req, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func (c Client) acquireTokenForServiceFabric(ctx context.Context, resource string) (AuthResult, error) { + req, err := createServiceFabricAuthRequest(ctx, resource) + if err != nil { + return AuthResult{}, err + } + tokenResponse, err := c.getTokenForRequest(req, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func (c Client) acquireTokenForAzureArc(ctx context.Context, resource string) (AuthResult, error) { + req, err := createAzureArcAuthRequest(ctx, resource, "") + if err != nil { + return AuthResult{}, err + } + + response, err := c.httpClient.Do(req) + if err != nil { + return AuthResult{}, err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusUnauthorized { + return AuthResult{}, fmt.Errorf("expected a 401 response, received %d", response.StatusCode) + } + + secret, err := c.getAzureArcSecretKey(response, runtime.GOOS) + if err != nil { + return AuthResult{}, err + } + + secondRequest, err := createAzureArcAuthRequest(ctx, resource, string(secret)) + if err != nil { + return AuthResult{}, err + } + + tokenResponse, err := c.getTokenForRequest(secondRequest, resource) + if err != nil { + return AuthResult{}, err + } + return authResultFromToken(c.authParams, tokenResponse) +} + +func authResultFromToken(authParams authority.AuthParams, token accesstokens.TokenResponse) (AuthResult, error) { + if cacheManager == nil { + return AuthResult{}, errors.New("cache instance is nil") + } + account, err := cacheManager.Write(authParams, token) + if err != nil { + return AuthResult{}, err + } + // if refreshOn is not set, set it to half of the time until expiry if expiry is more than 2 hours away + if token.RefreshOn.T.IsZero() { + if lifetime := time.Until(token.ExpiresOn); lifetime > 2*time.Hour { + token.RefreshOn.T = time.Now().Add(lifetime / 2) + } + } + ar, err := base.NewAuthResult(token, account) + if err != nil { + return AuthResult{}, err + } + ar.AccessToken, err = authParams.AuthnScheme.FormatAccessToken(ar.AccessToken) + return ar, err +} + +// contains checks if the element is present in the list. +func contains[T comparable](list []T, element T) bool { + for _, v := range list { + if v == element { + return true + } + } + return false +} + +// retry performs an HTTP request with retries based on the provided options. +func (c Client) retry(maxRetries int, req *http.Request) (*http.Response, error) { + var resp *http.Response + var err error + for attempt := 0; attempt < maxRetries; attempt++ { + tryCtx, tryCancel := context.WithTimeout(req.Context(), time.Minute) + defer tryCancel() + if resp != nil && resp.Body != nil { + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + cloneReq := req.Clone(tryCtx) + resp, err = c.httpClient.Do(cloneReq) + retrylist := retryStatusCodes + if c.source == DefaultToIMDS { + retrylist = retryCodesForIMDS + } + if err == nil && !contains(retrylist, resp.StatusCode) { + return resp, nil + } + select { + case <-time.After(time.Second): + case <-req.Context().Done(): + err = req.Context().Err() + return resp, err + } + } + return resp, err +} + +func (c Client) getTokenForRequest(req *http.Request, resource string) (accesstokens.TokenResponse, error) { + r := accesstokens.TokenResponse{} + var resp *http.Response + var err error + + if c.retryPolicyEnabled { + resp, err = c.retry(defaultRetryCount, req) + } else { + resp, err = c.httpClient.Do(req) + } + if err != nil { + return r, err + } + responseBytes, err := io.ReadAll(resp.Body) + defer resp.Body.Close() + if err != nil { + return r, err + } + switch resp.StatusCode { + case http.StatusOK, http.StatusAccepted: + default: + sd := strings.TrimSpace(string(responseBytes)) + if sd != "" { + return r, errors.CallErr{ + Req: req, + Resp: resp, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d:\n%s", + req.URL.String(), + req.Method, + resp.StatusCode, + sd), + } + } + return r, errors.CallErr{ + Req: req, + Resp: resp, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d", req.URL.String(), req.Method, resp.StatusCode), + } + } + + err = json.Unmarshal(responseBytes, &r) + if err != nil { + return r, errors.InvalidJsonErr{ + Err: fmt.Errorf("error parsing the json error: %s", err), + } + } + r.GrantedScopes.Slice = append(r.GrantedScopes.Slice, resource) + + return r, err +} + +func createAppServiceAuthRequest(ctx context.Context, id ID, resource string) (*http.Request, error) { + identityEndpoint := os.Getenv(identityEndpointEnvVar) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, identityEndpoint, nil) + if err != nil { + return nil, err + } + req.Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeaderEnvVar)) + q := req.URL.Query() + q.Set("api-version", appServiceAPIVersion) + q.Set("resource", resource) + switch t := id.(type) { + case UserAssignedClientID: + q.Set(miQueryParameterClientId, string(t)) + case UserAssignedResourceID: + q.Set(miQueryParameterResourceId, string(t)) + case UserAssignedObjectID: + q.Set(miQueryParameterObjectId, string(t)) + case systemAssignedValue: + default: + return nil, fmt.Errorf("unsupported type %T", id) + } + req.URL.RawQuery = q.Encode() + return req, nil +} + +func createIMDSAuthRequest(ctx context.Context, id ID, resource string) (*http.Request, error) { + msiEndpoint, err := url.Parse(imdsDefaultEndpoint) + if err != nil { + return nil, fmt.Errorf("couldn't parse %q: %s", imdsDefaultEndpoint, err) + } + msiParameters := msiEndpoint.Query() + msiParameters.Set(apiVersionQueryParameterName, imdsAPIVersion) + msiParameters.Set(resourceQueryParameterName, resource) + + switch t := id.(type) { + case UserAssignedClientID: + msiParameters.Set(miQueryParameterClientId, string(t)) + case UserAssignedResourceID: + msiParameters.Set(miQueryParameterResourceIdIMDS, string(t)) + case UserAssignedObjectID: + msiParameters.Set(miQueryParameterObjectId, string(t)) + case systemAssignedValue: // not adding anything + default: + return nil, fmt.Errorf("unsupported type %T", id) + } + + msiEndpoint.RawQuery = msiParameters.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, msiEndpoint.String(), nil) + if err != nil { + return nil, fmt.Errorf("error creating http request %s", err) + } + req.Header.Set(metaHTTPHeaderName, "true") + return req, nil +} + +func createAzureArcAuthRequest(ctx context.Context, resource string, key string) (*http.Request, error) { + identityEndpoint := os.Getenv(identityEndpointEnvVar) + if identityEndpoint == "" { + identityEndpoint = azureArcEndpoint + } + msiEndpoint, parseErr := url.Parse(identityEndpoint) + + if parseErr != nil { + return nil, fmt.Errorf("couldn't parse %q: %s", identityEndpoint, parseErr) + } + + msiParameters := msiEndpoint.Query() + msiParameters.Set(apiVersionQueryParameterName, azureArcAPIVersion) + msiParameters.Set(resourceQueryParameterName, resource) + + msiEndpoint.RawQuery = msiParameters.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, msiEndpoint.String(), nil) + if err != nil { + return nil, fmt.Errorf("error creating http request %s", err) + } + req.Header.Set(metaHTTPHeaderName, "true") + + if key != "" { + req.Header.Set("Authorization", fmt.Sprintf("Basic %s", key)) + } + + return req, nil +} + +func isAzureArcEnvironment(identityEndpoint, imdsEndpoint string) bool { + if identityEndpoint != "" && imdsEndpoint != "" { + return true + } + himdsFilePath := getAzureArcHimdsFilePath(runtime.GOOS) + if himdsFilePath != "" { + if _, err := os.Stat(himdsFilePath); err == nil { + return true + } + } + return false +} + +func (c *Client) getAzureArcSecretKey(response *http.Response, platform string) (string, error) { + wwwAuthenticateHeader := response.Header.Get(wwwAuthenticateHeaderName) + + if len(wwwAuthenticateHeader) == 0 { + return "", errors.New("response has no www-authenticate header") + } + + // check if the platform is supported + expectedSecretFilePath := getAzureArcPlatformPath(platform) + if expectedSecretFilePath == "" { + return "", errors.New("platform not supported, expected linux or windows") + } + + parts := strings.Split(wwwAuthenticateHeader, "Basic realm=") + if len(parts) < 2 { + return "", fmt.Errorf("basic realm= not found in the string, instead found: %s", wwwAuthenticateHeader) + } + + secretFilePath := parts + + // check that the file in the file path is a .key file + fileName := filepath.Base(secretFilePath[1]) + if !strings.HasSuffix(fileName, azureArcFileExtension) { + return "", fmt.Errorf("invalid file extension, expected %s, got %s", azureArcFileExtension, filepath.Ext(fileName)) + } + + // check that file path from header matches the expected file path for the platform + if expectedSecretFilePath != filepath.Dir(secretFilePath[1]) { + return "", fmt.Errorf("invalid file path, expected %s, got %s", expectedSecretFilePath, filepath.Dir(secretFilePath[1])) + } + + fileInfo, err := os.Stat(secretFilePath[1]) + if err != nil { + return "", fmt.Errorf("failed to get metadata for %s due to error: %s", secretFilePath[1], err) + } + + // Throw an error if the secret file's size is greater than 4096 bytes + if s := fileInfo.Size(); s > azureArcMaxFileSizeBytes { + return "", fmt.Errorf("invalid secret file size, expected %d, file size was %d", azureArcMaxFileSizeBytes, s) + } + + // Attempt to read the contents of the secret file + secret, err := os.ReadFile(secretFilePath[1]) + if err != nil { + return "", fmt.Errorf("failed to read %q due to error: %s", secretFilePath[1], err) + } + + return string(secret), nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/servicefabric.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/servicefabric.go new file mode 100644 index 00000000000..535065e9d9c --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity/servicefabric.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package managedidentity + +import ( + "context" + "net/http" + "os" +) + +func createServiceFabricAuthRequest(ctx context.Context, resource string) (*http.Request, error) { + identityEndpoint := os.Getenv(identityEndpointEnvVar) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, identityEndpoint, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Secret", os.Getenv(identityHeaderEnvVar)) + q := req.URL.Query() + q.Set("api-version", serviceFabricAPIVersion) + q.Set("resource", resource) + req.URL.RawQuery = q.Encode() + return req, nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go index 392e5e43f7d..7beed26174e 100644 --- a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go @@ -51,6 +51,13 @@ type AuthenticationScheme = authority.AuthenticationScheme type Account = shared.Account +type TokenSource = base.TokenSource + +const ( + TokenSourceIdentityProvider = base.TokenSourceIdentityProvider + TokenSourceCache = base.TokenSourceCache +) + var errNoAccount = errors.New("no account was specified with public.WithSilentAccount(), or the specified account is invalid") // clientOptions configures the Client's behavior. @@ -387,7 +394,7 @@ func (pca Client) AcquireTokenByUsernamePassword(ctx context.Context, scopes []s if err != nil { return AuthResult{}, err } - return pca.base.AuthResultFromToken(ctx, authParams, token, true) + return pca.base.AuthResultFromToken(ctx, authParams, token) } type DeviceCodeResult = accesstokens.DeviceCodeResult @@ -412,7 +419,7 @@ func (d DeviceCode) AuthenticationResult(ctx context.Context) (AuthResult, error if err != nil { return AuthResult{}, err } - return d.client.base.AuthResultFromToken(ctx, d.authParams, token, true) + return d.client.base.AuthResultFromToken(ctx, d.authParams, token) } // acquireTokenByDeviceCodeOptions contains optional configuration for AcquireTokenByDeviceCode @@ -687,7 +694,7 @@ func (pca Client) AcquireTokenInteractive(ctx context.Context, scopes []string, return AuthResult{}, err } - return pca.base.AuthResultFromToken(ctx, authParams, token, true) + return pca.base.AuthResultFromToken(ctx, authParams, token) } type interactiveAuthResult struct { diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go index b071cea51dd..6aba0ef1f69 100644 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go +++ b/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go @@ -436,9 +436,8 @@ func importTar(in io.ReaderAt) (*tarFile, error) { if err != nil { if err == io.EOF { break - } else { - return nil, fmt.Errorf("failed to parse tar file, %w", err) } + return nil, fmt.Errorf("failed to parse tar file, %w", err) } switch cleanEntryName(h.Name) { case PrefetchLandmark, NoPrefetchLandmark: diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go index 0ca6fd75f2e..ba650b4d1d7 100644 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go +++ b/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go @@ -26,12 +26,13 @@ import ( "archive/tar" "bytes" "compress/gzip" + "crypto/rand" "crypto/sha256" "encoding/json" "errors" "fmt" "io" - "math/rand" + "math/big" "os" "path/filepath" "reflect" @@ -45,10 +46,6 @@ import ( digest "github.com/opencontainers/go-digest" ) -func init() { - rand.Seed(time.Now().UnixNano()) -} - // TestingController is Compression with some helper methods necessary for testing. type TestingController interface { Compression @@ -920,9 +917,11 @@ func checkVerifyInvalidTOCEntryFail(filename string) check { } if sampleEntry == nil { t.Fatalf("TOC must contain at least one regfile or chunk entry other than the rewrite target") + return } if targetEntry == nil { t.Fatalf("rewrite target not found") + return } targetEntry.Offset = sampleEntry.Offset }, @@ -2291,7 +2290,11 @@ var runes = []rune("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX func randomContents(n int) string { b := make([]rune, n) for i := range b { - b[i] = runes[rand.Intn(len(runes))] + bi, err := rand.Int(rand.Reader, big.NewInt(int64(len(runes)))) + if err != nil { + panic(err) + } + b[i] = runes[int(bi.Int64())] } return string(b) } diff --git a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go index 3b8955994dc..95406281501 100644 --- a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go +++ b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go @@ -25,8 +25,13 @@ func NewFileStore(file store) Store { return &fileStore{file: file} } -// Erase removes the given credentials from the file store. +// Erase removes the given credentials from the file store.This function is +// idempotent and does not update the file if credentials did not change. func (c *fileStore) Erase(serverAddress string) error { + if _, exists := c.file.GetAuthConfigs()[serverAddress]; !exists { + // nothing to do; no credentials found for the given serverAddress + return nil + } delete(c.file.GetAuthConfigs(), serverAddress) return c.file.Save() } @@ -52,9 +57,14 @@ func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) { return c.file.GetAuthConfigs(), nil } -// Store saves the given credentials in the file store. +// Store saves the given credentials in the file store. This function is +// idempotent and does not update the file if credentials did not change. func (c *fileStore) Store(authConfig types.AuthConfig) error { authConfigs := c.file.GetAuthConfigs() + if oldAuthConfig, ok := authConfigs[authConfig.ServerAddress]; ok && oldAuthConfig == authConfig { + // Credentials didn't change, so skip updating the configuration file. + return nil + } authConfigs[authConfig.ServerAddress] = authConfig return c.file.Save() } diff --git a/vendor/github.com/docker/docker-credential-helpers/client/client.go b/vendor/github.com/docker/docker-credential-helpers/client/client.go index d1d0434cb55..7ca5ab72228 100644 --- a/vendor/github.com/docker/docker-credential-helpers/client/client.go +++ b/vendor/github.com/docker/docker-credential-helpers/client/client.go @@ -16,17 +16,15 @@ func isValidCredsMessage(msg string) error { if credentials.IsCredentialsMissingServerURLMessage(msg) { return credentials.NewErrCredentialsMissingServerURL() } - if credentials.IsCredentialsMissingUsernameMessage(msg) { return credentials.NewErrCredentialsMissingUsername() } - return nil } // Store uses an external program to save credentials. func Store(program ProgramFunc, creds *credentials.Credentials) error { - cmd := program("store") + cmd := program(credentials.ActionStore) buffer := new(bytes.Buffer) if err := json.NewEncoder(buffer).Encode(creds); err != nil { @@ -36,13 +34,10 @@ func Store(program ProgramFunc, creds *credentials.Credentials) error { out, err := cmd.Output() if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { + if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil { err = isValidErr } - - return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) + return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out))) } return nil @@ -50,22 +45,20 @@ func Store(program ProgramFunc, creds *credentials.Credentials) error { // Get executes an external program to get the credentials from a native store. func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { - cmd := program("get") + cmd := program(credentials.ActionGet) cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { - t := strings.TrimSpace(string(out)) - - if credentials.IsErrCredentialsNotFoundMessage(t) { + if credentials.IsErrCredentialsNotFoundMessage(string(out)) { return nil, credentials.NewErrCredentialsNotFound() } - if isValidErr := isValidCredsMessage(t); isValidErr != nil { + if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil { err = isValidErr } - return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) + return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out))) } resp := &credentials.Credentials{ @@ -81,7 +74,7 @@ func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error // Erase executes a program to remove the server credentials from the native store. func Erase(program ProgramFunc, serverURL string) error { - cmd := program("erase") + cmd := program(credentials.ActionErase) cmd.Input(strings.NewReader(serverURL)) out, err := cmd.Output() if err != nil { @@ -99,7 +92,7 @@ func Erase(program ProgramFunc, serverURL string) error { // List executes a program to list server credentials in the native store. func List(program ProgramFunc) (map[string]string, error) { - cmd := program("list") + cmd := program(credentials.ActionList) cmd.Input(strings.NewReader("unused")) out, err := cmd.Output() if err != nil { diff --git a/vendor/github.com/docker/docker-credential-helpers/client/command.go b/vendor/github.com/docker/docker-credential-helpers/client/command.go index 0183c063939..1936234befd 100644 --- a/vendor/github.com/docker/docker-credential-helpers/client/command.go +++ b/vendor/github.com/docker/docker-credential-helpers/client/command.go @@ -1,11 +1,9 @@ package client import ( - "fmt" "io" "os" - - exec "golang.org/x/sys/execabs" + "os/exec" ) // Program is an interface to execute external programs. @@ -31,27 +29,26 @@ func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc func createProgramCmdRedirectErr(commandName string, args []string, env *map[string]string) *exec.Cmd { programCmd := exec.Command(commandName, args...) - programCmd.Env = os.Environ() if env != nil { for k, v := range *env { - programCmd.Env = append(programCmd.Env, fmt.Sprintf("%s=%s", k, v)) + programCmd.Env = append(programCmd.Environ(), k+"="+v) } } programCmd.Stderr = os.Stderr return programCmd } -// Shell invokes shell commands to talk with a remote credentials helper. +// Shell invokes shell commands to talk with a remote credentials-helper. type Shell struct { cmd *exec.Cmd } -// Output returns responses from the remote credentials helper. +// Output returns responses from the remote credentials-helper. func (s *Shell) Output() ([]byte, error) { return s.cmd.Output() } -// Input sets the input to send to a remote credentials helper. +// Input sets the input to send to a remote credentials-helper. func (s *Shell) Input(in io.Reader) { s.cmd.Stdin = in } diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go index 91d9d4bbae9..eac55188497 100644 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go +++ b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go @@ -10,6 +10,20 @@ import ( "strings" ) +// Action defines the name of an action (sub-command) supported by a +// credential-helper binary. It is an alias for "string", and mostly +// for convenience. +type Action = string + +// List of actions (sub-commands) supported by credential-helper binaries. +const ( + ActionStore Action = "store" + ActionGet Action = "get" + ActionErase Action = "erase" + ActionList Action = "list" + ActionVersion Action = "version" +) + // Credentials holds the information shared between docker and the credentials store. type Credentials struct { ServerURL string @@ -43,42 +57,52 @@ func SetCredsLabel(label string) { CredsLabel = label } -// Serve initializes the credentials helper and parses the action argument. +// Serve initializes the credentials-helper and parses the action argument. // This function is designed to be called from a command line interface. // It uses os.Args[1] as the key for the action. // It uses os.Stdin as input and os.Stdout as output. // This function terminates the program with os.Exit(1) if there is an error. func Serve(helper Helper) { - var err error if len(os.Args) != 2 { - err = fmt.Errorf("Usage: %s ", os.Args[0]) + _, _ = fmt.Fprintln(os.Stdout, usage()) + os.Exit(1) } - if err == nil { - err = HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout) + switch os.Args[1] { + case "--version", "-v": + _ = PrintVersion(os.Stdout) + os.Exit(0) + case "--help", "-h": + _, _ = fmt.Fprintln(os.Stdout, usage()) + os.Exit(0) } - if err != nil { - fmt.Fprintf(os.Stdout, "%v\n", err) + if err := HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout); err != nil { + _, _ = fmt.Fprintln(os.Stdout, err) os.Exit(1) } } -// HandleCommand uses a helper and a key to run a credential action. -func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { - switch key { - case "store": +func usage() string { + return fmt.Sprintf("Usage: %s ", Name) +} + +// HandleCommand runs a helper to execute a credential action. +func HandleCommand(helper Helper, action Action, in io.Reader, out io.Writer) error { + switch action { + case ActionStore: return Store(helper, in) - case "get": + case ActionGet: return Get(helper, in, out) - case "erase": + case ActionErase: return Erase(helper, in) - case "list": + case ActionList: return List(helper, out) - case "version": + case ActionVersion: return PrintVersion(out) + default: + return fmt.Errorf("%s: unknown action: %s", Name, action) } - return fmt.Errorf("Unknown credential action `%s`", key) } // Store uses a helper and an input reader to save credentials. @@ -132,18 +156,17 @@ func Get(helper Helper, reader io.Reader, writer io.Writer) error { return err } - resp := Credentials{ + buffer.Reset() + err = json.NewEncoder(buffer).Encode(Credentials{ ServerURL: serverURL, Username: username, Secret: secret, - } - - buffer.Reset() - if err := json.NewEncoder(buffer).Encode(resp); err != nil { + }) + if err != nil { return err } - fmt.Fprint(writer, buffer.String()) + _, _ = fmt.Fprint(writer, buffer.String()) return nil } @@ -181,6 +204,6 @@ func List(helper Helper, writer io.Writer) error { // PrintVersion outputs the current version. func PrintVersion(writer io.Writer) error { - fmt.Fprintf(writer, "%s (%s) %s\n", Name, Package, Version) + _, _ = fmt.Fprintf(writer, "%s (%s) %s\n", Name, Package, Version) return nil } diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go index fe6a5aef45c..2283d5a44c7 100644 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go +++ b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go @@ -1,5 +1,10 @@ package credentials +import ( + "errors" + "strings" +) + const ( // ErrCredentialsNotFound standardizes the not found error, so every helper returns // the same message and docker can handle it properly. @@ -21,6 +26,11 @@ func (errCredentialsNotFound) Error() string { return errCredentialsNotFoundMessage } +// NotFound implements the [ErrNotFound][errdefs.ErrNotFound] interface. +// +// [errdefs.ErrNotFound]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrNotFound +func (errCredentialsNotFound) NotFound() {} + // NewErrCredentialsNotFound creates a new error // for when the credentials are not in the store. func NewErrCredentialsNotFound() error { @@ -30,8 +40,8 @@ func NewErrCredentialsNotFound() error { // IsErrCredentialsNotFound returns true if the error // was caused by not having a set of credentials in a store. func IsErrCredentialsNotFound(err error) bool { - _, ok := err.(errCredentialsNotFound) - return ok + var target errCredentialsNotFound + return errors.As(err, &target) } // IsErrCredentialsNotFoundMessage returns true if the error @@ -40,7 +50,7 @@ func IsErrCredentialsNotFound(err error) bool { // This function helps to check messages returned by an // external program via its standard output. func IsErrCredentialsNotFoundMessage(err string) bool { - return err == errCredentialsNotFoundMessage + return strings.TrimSpace(err) == errCredentialsNotFoundMessage } // errCredentialsMissingServerURL represents an error raised @@ -53,6 +63,12 @@ func (errCredentialsMissingServerURL) Error() string { return errCredentialsMissingServerURLMessage } +// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter] +// interface. +// +// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter +func (errCredentialsMissingServerURL) InvalidParameter() {} + // errCredentialsMissingUsername represents an error raised // when the credentials object has no username or when no // username is provided to a credentials operation requiring @@ -63,6 +79,12 @@ func (errCredentialsMissingUsername) Error() string { return errCredentialsMissingUsernameMessage } +// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter] +// interface. +// +// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter +func (errCredentialsMissingUsername) InvalidParameter() {} + // NewErrCredentialsMissingServerURL creates a new error for // errCredentialsMissingServerURL. func NewErrCredentialsMissingServerURL() error { @@ -78,25 +100,25 @@ func NewErrCredentialsMissingUsername() error { // IsCredentialsMissingServerURL returns true if the error // was an errCredentialsMissingServerURL. func IsCredentialsMissingServerURL(err error) bool { - _, ok := err.(errCredentialsMissingServerURL) - return ok + var target errCredentialsMissingServerURL + return errors.As(err, &target) } // IsCredentialsMissingServerURLMessage checks for an // errCredentialsMissingServerURL in the error message. func IsCredentialsMissingServerURLMessage(err string) bool { - return err == errCredentialsMissingServerURLMessage + return strings.TrimSpace(err) == errCredentialsMissingServerURLMessage } // IsCredentialsMissingUsername returns true if the error // was an errCredentialsMissingUsername. func IsCredentialsMissingUsername(err error) bool { - _, ok := err.(errCredentialsMissingUsername) - return ok + var target errCredentialsMissingUsername + return errors.As(err, &target) } // IsCredentialsMissingUsernameMessage checks for an // errCredentialsMissingUsername in the error message. func IsCredentialsMissingUsernameMessage(err string) bool { - return err == errCredentialsMissingUsernameMessage + return strings.TrimSpace(err) == errCredentialsMissingUsernameMessage } diff --git a/vendor/github.com/google/go-containerregistry/internal/redact/redact.go b/vendor/github.com/google/go-containerregistry/internal/redact/redact.go index b2e3f186ccb..6d475700761 100644 --- a/vendor/github.com/google/go-containerregistry/internal/redact/redact.go +++ b/vendor/github.com/google/go-containerregistry/internal/redact/redact.go @@ -51,7 +51,7 @@ func Error(err error) error { if perr != nil { return err // If the URL can't be parsed, just return the original error. } - uerr.URL = URL(u).String() // Update the URL to the redacted URL. + uerr.URL = URL(u) // Update the URL to the redacted URL. return uerr } @@ -73,7 +73,7 @@ var paramAllowlist = map[string]struct{}{ } // URL redacts potentially sensitive query parameter values from the URL's query string. -func URL(u *url.URL) *url.URL { +func URL(u *url.URL) string { qs := u.Query() for k, v := range qs { for i := range v { @@ -85,5 +85,5 @@ func URL(u *url.URL) *url.URL { } r := *u r.RawQuery = qs.Encode() - return &r + return r.Redacted() } diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go b/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go index f4c452bdc3a..6e8814d8084 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go +++ b/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go @@ -84,7 +84,7 @@ func (dk *defaultKeychain) Resolve(target Resource) (Authenticator, error) { } // Resolve implements Keychain. -func (dk *defaultKeychain) ResolveContext(ctx context.Context, target Resource) (Authenticator, error) { +func (dk *defaultKeychain) ResolveContext(_ context.Context, target Resource) (Authenticator, error) { dk.mu.Lock() defer dk.mu.Unlock() @@ -204,7 +204,7 @@ func (w wrapper) Resolve(r Resource) (Authenticator, error) { return w.ResolveContext(context.Background(), r) } -func (w wrapper) ResolveContext(ctx context.Context, r Resource) (Authenticator, error) { +func (w wrapper) ResolveContext(_ context.Context, r Resource) (Authenticator, error) { u, p, err := w.h.Get(r.RegistryStr()) if err != nil { return Anonymous, nil diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/ref.go b/vendor/github.com/google/go-containerregistry/pkg/name/ref.go index 912ab33018f..0a048677230 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/name/ref.go +++ b/vendor/github.com/google/go-containerregistry/pkg/name/ref.go @@ -44,7 +44,7 @@ func ParseReference(s string, opts ...Option) (Reference, error) { if d, err := NewDigest(s, opts...); err == nil { return d, nil } - return nil, newErrBadName("could not parse reference: " + s) + return nil, newErrBadName("could not parse reference: %s", s) } type stringConst string diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go index 1a24b10d76b..4207740c358 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go +++ b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go @@ -21,6 +21,7 @@ import ( "errors" "fmt" "io" + "maps" "path/filepath" "strings" "time" @@ -165,16 +166,16 @@ func Annotations(f partial.WithRawManifest, anns map[string]string) partial.With if img, ok := f.(v1.Image); ok { return &image{ base: img, - annotations: anns, + annotations: maps.Clone(anns), } } if idx, ok := f.(v1.ImageIndex); ok { return &index{ base: idx, - annotations: anns, + annotations: maps.Clone(anns), } } - return arbitraryRawManifest{a: f, anns: anns} + return arbitraryRawManifest{a: f, anns: maps.Clone(anns)} } type arbitraryRawManifest struct { diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go index 48e3835f9c0..4bc6f70a853 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go +++ b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go @@ -61,7 +61,7 @@ func (f *fetcher) fetchReferrers(ctx context.Context, filter map[string]string, } defer resp.Body.Close() - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound, http.StatusBadRequest); err != nil { + if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound, http.StatusBadRequest, http.StatusNotAcceptable); err != nil { return nil, err } diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go index be3bec9c377..ea652d4ae81 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go +++ b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go @@ -24,8 +24,10 @@ import ( "net/http" "net/url" "strings" + "sync" authchallenge "github.com/docker/distribution/registry/client/auth/challenge" + "github.com/google/go-containerregistry/internal/redact" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/logs" @@ -98,6 +100,7 @@ func fromChallenge(reg name.Registry, auth authn.Authenticator, t http.RoundTrip } type bearerTransport struct { + mx sync.RWMutex // Wrapped by bearerTransport. inner http.RoundTripper // Basic credentials that we exchange for bearer tokens. @@ -139,7 +142,10 @@ func (bt *bearerTransport) RoundTrip(in *http.Request) (*http.Response, error) { // the registry with which we are interacting. // In case of redirect http.Client can use an empty Host, check URL too. if matchesHost(bt.registry.RegistryStr(), in, bt.scheme) { - hdr := fmt.Sprintf("Bearer %s", bt.bearer.RegistryToken) + bt.mx.RLock() + localToken := bt.bearer.RegistryToken + bt.mx.RUnlock() + hdr := fmt.Sprintf("Bearer %s", localToken) in.Header.Set("Authorization", hdr) } return bt.inner.RoundTrip(in) @@ -156,11 +162,12 @@ func (bt *bearerTransport) RoundTrip(in *http.Request) (*http.Response, error) { res.Body.Close() newScopes := []string{} + bt.mx.Lock() + got := stringSet(bt.scopes) for _, wac := range challenges { // TODO(jonjohnsonjr): Should we also update "realm" or "service"? if want, ok := wac.Parameters["scope"]; ok { // Add any scopes that we don't already request. - got := stringSet(bt.scopes) if _, ok := got[want]; !ok { newScopes = append(newScopes, want) } @@ -172,6 +179,7 @@ func (bt *bearerTransport) RoundTrip(in *http.Request) (*http.Response, error) { // otherwise the registry might just ignore it :/ newScopes = append(newScopes, bt.scopes...) bt.scopes = newScopes + bt.mx.Unlock() // TODO(jonjohnsonjr): Teach transport.Error about "error" and "error_description" from challenge. @@ -196,7 +204,9 @@ func (bt *bearerTransport) refresh(ctx context.Context) error { } if auth.RegistryToken != "" { + bt.mx.Lock() bt.bearer.RegistryToken = auth.RegistryToken + bt.mx.Unlock() return nil } @@ -212,7 +222,9 @@ func (bt *bearerTransport) refresh(ctx context.Context) error { // Find a token to turn into a Bearer authenticator if response.Token != "" { + bt.mx.Lock() bt.bearer.RegistryToken = response.Token + bt.mx.Unlock() } // If we obtained a refresh token from the oauth flow, use that for refresh() now. @@ -306,7 +318,9 @@ func (bt *bearerTransport) refreshOauth(ctx context.Context) ([]byte, error) { } v := url.Values{} + bt.mx.RLock() v.Set("scope", strings.Join(bt.scopes, " ")) + bt.mx.RUnlock() if bt.service != "" { v.Set("service", bt.service) } @@ -362,7 +376,9 @@ func (bt *bearerTransport) refreshBasic(ctx context.Context) ([]byte, error) { client := http.Client{Transport: b} v := u.Query() + bt.mx.RLock() v["scope"] = bt.scopes + bt.mx.RUnlock() v.Set("service", bt.service) u.RawQuery = v.Encode() diff --git a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go index 2c5c99efde2..40725bd79c3 100644 --- a/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go +++ b/vendor/github.com/sigstore/protobuf-specs/gen/pb-go/common/v1/sigstore_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.3 -// protoc v5.29.3 +// protoc-gen-go v1.36.5 +// protoc v5.29.4 // source: sigstore_common.proto package v1 @@ -27,6 +27,7 @@ import ( timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -149,6 +150,13 @@ const ( // Ed 25519 PublicKeyDetails_PKIX_ED25519 PublicKeyDetails = 7 // See RFC8032 PublicKeyDetails_PKIX_ED25519_PH PublicKeyDetails = 8 + // These algorithms are deprecated and should not be used, but they + // were/are being used by most Sigstore clients implementations. + // + // Deprecated: Marked as deprecated in sigstore_common.proto. + PublicKeyDetails_PKIX_ECDSA_P384_SHA_256 PublicKeyDetails = 19 + // Deprecated: Marked as deprecated in sigstore_common.proto. + PublicKeyDetails_PKIX_ECDSA_P521_SHA_256 PublicKeyDetails = 20 // LMS and LM-OTS // // These keys and signatures may be used by private Sigstore @@ -186,6 +194,8 @@ var ( 13: "PKIX_ECDSA_P521_SHA_512", 7: "PKIX_ED25519", 8: "PKIX_ED25519_PH", + 19: "PKIX_ECDSA_P384_SHA_256", + 20: "PKIX_ECDSA_P521_SHA_256", 14: "LMS_SHA256", 15: "LMOTS_SHA256", } @@ -207,6 +217,8 @@ var ( "PKIX_ECDSA_P521_SHA_512": 13, "PKIX_ED25519": 7, "PKIX_ED25519_PH": 8, + "PKIX_ECDSA_P384_SHA_256": 19, + "PKIX_ECDSA_P521_SHA_256": 20, "LMS_SHA256": 14, "LMOTS_SHA256": 15, } @@ -1026,7 +1038,7 @@ func (x *TimeRange) GetEnd() *timestamppb.Timestamp { var File_sigstore_common_proto protoreflect.FileDescriptor -var file_sigstore_common_proto_rawDesc = []byte{ +var file_sigstore_common_proto_rawDesc = string([]byte{ 0x0a, 0x15, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x16, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x1a, @@ -1122,7 +1134,7 @@ var file_sigstore_common_proto_rawDesc = []byte{ 0x48, 0x41, 0x32, 0x5f, 0x33, 0x38, 0x34, 0x10, 0x02, 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x48, 0x41, 0x32, 0x5f, 0x35, 0x31, 0x32, 0x10, 0x03, 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x48, 0x41, 0x33, 0x5f, 0x32, 0x35, 0x36, 0x10, 0x04, 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x48, 0x41, 0x33, 0x5f, 0x33, 0x38, - 0x34, 0x10, 0x05, 0x2a, 0xa7, 0x04, 0x0a, 0x10, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, + 0x34, 0x10, 0x05, 0x2a, 0xe9, 0x04, 0x0a, 0x10, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x12, 0x22, 0x0a, 0x1e, 0x50, 0x55, 0x42, 0x4c, 0x49, 0x43, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x44, 0x45, 0x54, 0x41, 0x49, 0x4c, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x19, 0x0a, 0x11, @@ -1154,35 +1166,39 @@ var file_sigstore_common_proto_rawDesc = []byte{ 0x50, 0x35, 0x32, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x5f, 0x35, 0x31, 0x32, 0x10, 0x0d, 0x12, 0x10, 0x0a, 0x0c, 0x50, 0x4b, 0x49, 0x58, 0x5f, 0x45, 0x44, 0x32, 0x35, 0x35, 0x31, 0x39, 0x10, 0x07, 0x12, 0x13, 0x0a, 0x0f, 0x50, 0x4b, 0x49, 0x58, 0x5f, 0x45, 0x44, 0x32, 0x35, 0x35, 0x31, 0x39, - 0x5f, 0x50, 0x48, 0x10, 0x08, 0x12, 0x0e, 0x0a, 0x0a, 0x4c, 0x4d, 0x53, 0x5f, 0x53, 0x48, 0x41, - 0x32, 0x35, 0x36, 0x10, 0x0e, 0x12, 0x10, 0x0a, 0x0c, 0x4c, 0x4d, 0x4f, 0x54, 0x53, 0x5f, 0x53, - 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x0f, 0x22, 0x04, 0x08, 0x13, 0x10, 0x32, 0x2a, 0x6f, 0x0a, - 0x1a, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, - 0x69, 0x76, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x2d, 0x0a, 0x29, 0x53, - 0x55, 0x42, 0x4a, 0x45, 0x43, 0x54, 0x5f, 0x41, 0x4c, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x54, 0x49, - 0x56, 0x45, 0x5f, 0x4e, 0x41, 0x4d, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, - 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x4d, - 0x41, 0x49, 0x4c, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x52, 0x49, 0x10, 0x02, 0x12, 0x0e, - 0x0a, 0x0a, 0x4f, 0x54, 0x48, 0x45, 0x52, 0x5f, 0x4e, 0x41, 0x4d, 0x45, 0x10, 0x03, 0x42, 0x7c, - 0x0a, 0x1c, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x42, 0x0b, - 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x36, 0x67, - 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, - 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2d, 0x73, 0x70, 0x65, 0x63, - 0x73, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x70, 0x62, 0x2d, 0x67, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, - 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0xea, 0x02, 0x14, 0x53, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, - 0x3a, 0x3a, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, -} + 0x5f, 0x50, 0x48, 0x10, 0x08, 0x12, 0x1f, 0x0a, 0x17, 0x50, 0x4b, 0x49, 0x58, 0x5f, 0x45, 0x43, + 0x44, 0x53, 0x41, 0x5f, 0x50, 0x33, 0x38, 0x34, 0x5f, 0x53, 0x48, 0x41, 0x5f, 0x32, 0x35, 0x36, + 0x10, 0x13, 0x1a, 0x02, 0x08, 0x01, 0x12, 0x1f, 0x0a, 0x17, 0x50, 0x4b, 0x49, 0x58, 0x5f, 0x45, + 0x43, 0x44, 0x53, 0x41, 0x5f, 0x50, 0x35, 0x32, 0x31, 0x5f, 0x53, 0x48, 0x41, 0x5f, 0x32, 0x35, + 0x36, 0x10, 0x14, 0x1a, 0x02, 0x08, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x4c, 0x4d, 0x53, 0x5f, 0x53, + 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x0e, 0x12, 0x10, 0x0a, 0x0c, 0x4c, 0x4d, 0x4f, 0x54, 0x53, + 0x5f, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x10, 0x0f, 0x22, 0x04, 0x08, 0x15, 0x10, 0x32, 0x2a, + 0x6f, 0x0a, 0x1a, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, + 0x61, 0x74, 0x69, 0x76, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x2d, 0x0a, + 0x29, 0x53, 0x55, 0x42, 0x4a, 0x45, 0x43, 0x54, 0x5f, 0x41, 0x4c, 0x54, 0x45, 0x52, 0x4e, 0x41, + 0x54, 0x49, 0x56, 0x45, 0x5f, 0x4e, 0x41, 0x4d, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, + 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, + 0x45, 0x4d, 0x41, 0x49, 0x4c, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x52, 0x49, 0x10, 0x02, + 0x12, 0x0e, 0x0a, 0x0a, 0x4f, 0x54, 0x48, 0x45, 0x52, 0x5f, 0x4e, 0x41, 0x4d, 0x45, 0x10, 0x03, + 0x42, 0x7c, 0x0a, 0x1c, 0x64, 0x65, 0x76, 0x2e, 0x73, 0x69, 0x67, 0x73, 0x74, 0x6f, 0x72, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, + 0x42, 0x0b, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, + 0x36, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x69, 0x67, 0x73, + 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2d, 0x73, 0x70, + 0x65, 0x63, 0x73, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x70, 0x62, 0x2d, 0x67, 0x6f, 0x2f, 0x63, 0x6f, + 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0xea, 0x02, 0x14, 0x53, 0x69, 0x67, 0x73, 0x74, 0x6f, + 0x72, 0x65, 0x3a, 0x3a, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +}) var ( file_sigstore_common_proto_rawDescOnce sync.Once - file_sigstore_common_proto_rawDescData = file_sigstore_common_proto_rawDesc + file_sigstore_common_proto_rawDescData []byte ) func file_sigstore_common_proto_rawDescGZIP() []byte { file_sigstore_common_proto_rawDescOnce.Do(func() { - file_sigstore_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_sigstore_common_proto_rawDescData) + file_sigstore_common_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_sigstore_common_proto_rawDesc), len(file_sigstore_common_proto_rawDesc))) }) return file_sigstore_common_proto_rawDescData } @@ -1240,7 +1256,7 @@ func file_sigstore_common_proto_init() { out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_sigstore_common_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_sigstore_common_proto_rawDesc), len(file_sigstore_common_proto_rawDesc)), NumEnums: 3, NumMessages: 13, NumExtensions: 0, @@ -1252,7 +1268,6 @@ func file_sigstore_common_proto_init() { MessageInfos: file_sigstore_common_proto_msgTypes, }.Build() File_sigstore_common_proto = out.File - file_sigstore_common_proto_rawDesc = nil file_sigstore_common_proto_goTypes = nil file_sigstore_common_proto_depIdxs = nil } diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/azure/client.go b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/azure/client.go index 2d8cc39b632..c961829cd9c 100644 --- a/vendor/github.com/sigstore/sigstore/pkg/signature/kms/azure/client.go +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/kms/azure/client.go @@ -34,7 +34,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" - "github.com/go-jose/go-jose/v3" + "github.com/go-jose/go-jose/v4" "github.com/jellydator/ttlcache/v3" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/reader.go b/vendor/github.com/vbatts/tar-split/archive/tar/reader.go index fcf32155397..6a6b3e01824 100644 --- a/vendor/github.com/vbatts/tar-split/archive/tar/reader.go +++ b/vendor/github.com/vbatts/tar-split/archive/tar/reader.go @@ -7,7 +7,6 @@ package tar import ( "bytes" "io" - "io/ioutil" "strconv" "strings" "time" @@ -57,6 +56,11 @@ func (tr *Reader) RawBytes() []byte { } +// ExpectedPadding returns the number of bytes of padding expected after the last header returned by Next() +func (tr *Reader) ExpectedPadding() int64 { + return tr.pad +} + // NewReader creates a new Reader reading from r. func NewReader(r io.Reader) *Reader { return &Reader{r: r, curr: ®FileReader{r, 0}} @@ -140,7 +144,7 @@ func (tr *Reader) next() (*Header, error) { continue // This is a meta header affecting the next header case TypeGNULongName, TypeGNULongLink: format.mayOnlyBe(FormatGNU) - realname, err := ioutil.ReadAll(tr) + realname, err := io.ReadAll(tr) if err != nil { return nil, err } @@ -334,7 +338,7 @@ func mergePAX(hdr *Header, paxHdrs map[string]string) (err error) { // parsePAX parses PAX headers. // If an extended header (type 'x') is invalid, ErrHeader is returned func parsePAX(r io.Reader) (map[string]string, error) { - buf, err := ioutil.ReadAll(r) + buf, err := io.ReadAll(r) if err != nil { return nil, err } @@ -916,7 +920,7 @@ func discard(tr *Reader, n int64) error { } } - copySkipped, err = io.CopyN(ioutil.Discard, r, n-seekSkipped) + copySkipped, err = io.CopyN(io.Discard, r, n-seekSkipped) out: if err == io.EOF && seekSkipped+copySkipped < n { err = io.ErrUnexpectedEOF diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go index 6aae83bfd20..b25641c55d3 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go @@ -18,7 +18,7 @@ var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)} // Get is a convenient replacement for http.Get that adds a span around the request. func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "GET", targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil) if err != nil { return nil, err } @@ -27,7 +27,7 @@ func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) // Head is a convenient replacement for http.Head that adds a span around the request. func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "HEAD", targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodHead, targetURL, nil) if err != nil { return nil, err } @@ -36,7 +36,7 @@ func Head(ctx context.Context, targetURL string) (resp *http.Response, err error // Post is a convenient replacement for http.Post that adds a span around the request. func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "POST", targetURL, body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, body) if err != nil { return nil, err } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go index 5d6e6156b7b..a83a026274a 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go @@ -18,13 +18,6 @@ const ( WriteErrorKey = attribute.Key("http.write_error") // if an error occurred while writing a reply, the string of the error (io.EOF is not recorded) ) -// Client HTTP metrics. -const ( - clientRequestSize = "http.client.request.size" // Outgoing request bytes total - clientResponseSize = "http.client.response.size" // Outgoing response bytes total - clientDuration = "http.client.duration" // Outgoing end to end duration, milliseconds -) - // Filter is a predicate used to determine whether a given http.request should // be traced. A Filter must return true if the request should be traced. type Filter func(*http.Request) bool diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index 33580a35b77..e555a475f13 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -81,12 +81,6 @@ func (h *middleware) configure(c *config) { h.semconv = semconv.NewHTTPServer(c.Meter) } -func handleErr(err error) { - if err != nil { - otel.Handle(err) - } -} - // serveHTTP sets up tracing and calls the given next http.Handler with the span // context injected into the request context. func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http.Handler) { @@ -123,6 +117,11 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http } } + if startTime := StartTimeFromContext(ctx); !startTime.IsZero() { + opts = append(opts, trace.WithTimestamp(startTime)) + requestStartTime = startTime + } + ctx, span := tracer.Start(ctx, h.spanNameFormatter(h.operation, r), opts...) defer span.End() @@ -190,14 +189,18 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - h.semconv.RecordMetrics(ctx, semconv.MetricData{ - ServerName: h.server, - Req: r, - StatusCode: statusCode, - AdditionalAttributes: labeler.Get(), - RequestSize: bw.BytesRead(), - ResponseSize: bytesWritten, - ElapsedTime: elapsedTime, + h.semconv.RecordMetrics(ctx, semconv.ServerMetricData{ + ServerName: h.server, + ResponseSize: bytesWritten, + MetricAttributes: semconv.MetricAttributes{ + Req: r, + StatusCode: statusCode, + AdditionalAttributes: labeler.Get(), + }, + MetricData: semconv.MetricData{ + RequestSize: bw.BytesRead(), + ElapsedTime: elapsedTime, + }, }) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go index aea171fb260..fbc344cbdda 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go @@ -44,7 +44,9 @@ func (w *RespWriterWrapper) Write(p []byte) (int, error) { w.mu.Lock() defer w.mu.Unlock() - w.writeHeader(http.StatusOK) + if !w.wroteHeader { + w.writeHeader(http.StatusOK) + } n, err := w.ResponseWriter.Write(p) n1 := int64(n) @@ -80,7 +82,12 @@ func (w *RespWriterWrapper) writeHeader(statusCode int) { // Flush implements [http.Flusher]. func (w *RespWriterWrapper) Flush() { - w.WriteHeader(http.StatusOK) + w.mu.Lock() + defer w.mu.Unlock() + + if !w.wroteHeader { + w.writeHeader(http.StatusOK) + } if f, ok := w.ResponseWriter.(http.Flusher); ok { f.Flush() diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go index 9cae4cab86a..3b036f8a37b 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "strings" + "sync" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" @@ -50,9 +51,9 @@ type HTTPServer struct { // The req Host will be used to determine the server instead. func (s HTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { if s.duplicate { - return append(oldHTTPServer{}.RequestTraceAttrs(server, req), newHTTPServer{}.RequestTraceAttrs(server, req)...) + return append(OldHTTPServer{}.RequestTraceAttrs(server, req), CurrentHTTPServer{}.RequestTraceAttrs(server, req)...) } - return oldHTTPServer{}.RequestTraceAttrs(server, req) + return OldHTTPServer{}.RequestTraceAttrs(server, req) } // ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. @@ -60,14 +61,14 @@ func (s HTTPServer) RequestTraceAttrs(server string, req *http.Request) []attrib // If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. func (s HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { if s.duplicate { - return append(oldHTTPServer{}.ResponseTraceAttrs(resp), newHTTPServer{}.ResponseTraceAttrs(resp)...) + return append(OldHTTPServer{}.ResponseTraceAttrs(resp), CurrentHTTPServer{}.ResponseTraceAttrs(resp)...) } - return oldHTTPServer{}.ResponseTraceAttrs(resp) + return OldHTTPServer{}.ResponseTraceAttrs(resp) } // Route returns the attribute for the route. func (s HTTPServer) Route(route string) attribute.KeyValue { - return oldHTTPServer{}.Route(route) + return OldHTTPServer{}.Route(route) } // Status returns a span status code and message for an HTTP status code @@ -83,29 +84,46 @@ func (s HTTPServer) Status(code int) (codes.Code, string) { return codes.Unset, "" } -type MetricData struct { - ServerName string +type ServerMetricData struct { + ServerName string + ResponseSize int64 + + MetricData + MetricAttributes +} + +type MetricAttributes struct { Req *http.Request StatusCode int AdditionalAttributes []attribute.KeyValue +} - RequestSize int64 - ResponseSize int64 - ElapsedTime float64 +type MetricData struct { + RequestSize int64 + ElapsedTime float64 +} + +var metricAddOptionPool = &sync.Pool{ + New: func() interface{} { + return &[]metric.AddOption{} + }, } -func (s HTTPServer) RecordMetrics(ctx context.Context, md MetricData) { +func (s HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { if s.requestBytesCounter == nil || s.responseBytesCounter == nil || s.serverLatencyMeasure == nil { - // This will happen if an HTTPServer{} is used insted of NewHTTPServer. + // This will happen if an HTTPServer{} is used instead of NewHTTPServer. return } - attributes := oldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) + attributes := OldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) o := metric.WithAttributeSet(attribute.NewSet(attributes...)) - addOpts := []metric.AddOption{o} // Allocate vararg slice once. - s.requestBytesCounter.Add(ctx, md.RequestSize, addOpts...) - s.responseBytesCounter.Add(ctx, md.ResponseSize, addOpts...) + addOpts := metricAddOptionPool.Get().(*[]metric.AddOption) + *addOpts = append(*addOpts, o) + s.requestBytesCounter.Add(ctx, md.RequestSize, *addOpts...) + s.responseBytesCounter.Add(ctx, md.ResponseSize, *addOpts...) s.serverLatencyMeasure.Record(ctx, md.ElapsedTime, o) + *addOpts = (*addOpts)[:0] + metricAddOptionPool.Put(addOpts) // TODO: Duplicate Metrics } @@ -116,34 +134,43 @@ func NewHTTPServer(meter metric.Meter) HTTPServer { server := HTTPServer{ duplicate: duplicate, } - server.requestBytesCounter, server.responseBytesCounter, server.serverLatencyMeasure = oldHTTPServer{}.createMeasures(meter) + server.requestBytesCounter, server.responseBytesCounter, server.serverLatencyMeasure = OldHTTPServer{}.createMeasures(meter) return server } type HTTPClient struct { duplicate bool + + // old metrics + requestBytesCounter metric.Int64Counter + responseBytesCounter metric.Int64Counter + latencyMeasure metric.Float64Histogram } -func NewHTTPClient() HTTPClient { +func NewHTTPClient(meter metric.Meter) HTTPClient { env := strings.ToLower(os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")) - return HTTPClient{duplicate: env == "http/dup"} + client := HTTPClient{ + duplicate: env == "http/dup", + } + client.requestBytesCounter, client.responseBytesCounter, client.latencyMeasure = OldHTTPClient{}.createMeasures(meter) + return client } // RequestTraceAttrs returns attributes for an HTTP request made by a client. func (c HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { if c.duplicate { - return append(oldHTTPClient{}.RequestTraceAttrs(req), newHTTPClient{}.RequestTraceAttrs(req)...) + return append(OldHTTPClient{}.RequestTraceAttrs(req), CurrentHTTPClient{}.RequestTraceAttrs(req)...) } - return oldHTTPClient{}.RequestTraceAttrs(req) + return OldHTTPClient{}.RequestTraceAttrs(req) } // ResponseTraceAttrs returns metric attributes for an HTTP request made by a client. func (c HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { if c.duplicate { - return append(oldHTTPClient{}.ResponseTraceAttrs(resp), newHTTPClient{}.ResponseTraceAttrs(resp)...) + return append(OldHTTPClient{}.ResponseTraceAttrs(resp), CurrentHTTPClient{}.ResponseTraceAttrs(resp)...) } - return oldHTTPClient{}.ResponseTraceAttrs(resp) + return OldHTTPClient{}.ResponseTraceAttrs(resp) } func (c HTTPClient) Status(code int) (codes.Code, string) { @@ -158,8 +185,53 @@ func (c HTTPClient) Status(code int) (codes.Code, string) { func (c HTTPClient) ErrorType(err error) attribute.KeyValue { if c.duplicate { - return newHTTPClient{}.ErrorType(err) + return CurrentHTTPClient{}.ErrorType(err) } return attribute.KeyValue{} } + +type MetricOpts struct { + measurement metric.MeasurementOption + addOptions metric.AddOption +} + +func (o MetricOpts) MeasurementOption() metric.MeasurementOption { + return o.measurement +} + +func (o MetricOpts) AddOptions() metric.AddOption { + return o.addOptions +} + +func (c HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts { + attributes := OldHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) + // TODO: Duplicate Metrics + set := metric.WithAttributeSet(attribute.NewSet(attributes...)) + return MetricOpts{ + measurement: set, + addOptions: set, + } +} + +func (s HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts MetricOpts) { + if s.requestBytesCounter == nil || s.latencyMeasure == nil { + // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). + return + } + + s.requestBytesCounter.Add(ctx, md.RequestSize, opts.AddOptions()) + s.latencyMeasure.Record(ctx, md.ElapsedTime, opts.MeasurementOption()) + + // TODO: Duplicate Metrics +} + +func (s HTTPClient) RecordResponseSize(ctx context.Context, responseData int64, opts metric.AddOption) { + if s.responseBytesCounter == nil { + // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). + return + } + + s.responseBytesCounter.Add(ctx, responseData, opts) + // TODO: Duplicate Metrics +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go index 745b8c67bc4..dc9ec7bc39e 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go @@ -14,7 +14,7 @@ import ( semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" ) -type newHTTPServer struct{} +type CurrentHTTPServer struct{} // TraceRequest returns trace attributes for an HTTP request received by a // server. @@ -32,18 +32,18 @@ type newHTTPServer struct{} // // If the primary server name is not known, server should be an empty string. // The req Host will be used to determine the server instead. -func (n newHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { +func (n CurrentHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { count := 3 // ServerAddress, Method, Scheme var host string var p int if server == "" { - host, p = splitHostPort(req.Host) + host, p = SplitHostPort(req.Host) } else { // Prioritize the primary server name. - host, p = splitHostPort(server) + host, p = SplitHostPort(server) if p < 0 { - _, p = splitHostPort(req.Host) + _, p = SplitHostPort(req.Host) } } @@ -59,7 +59,7 @@ func (n newHTTPServer) RequestTraceAttrs(server string, req *http.Request) []att scheme := n.scheme(req.TLS != nil) - if peer, peerPort := splitHostPort(req.RemoteAddr); peer != "" { + if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a // file-path that would be interpreted with a sock family. count++ @@ -104,7 +104,7 @@ func (n newHTTPServer) RequestTraceAttrs(server string, req *http.Request) []att attrs = append(attrs, methodOriginal) } - if peer, peerPort := splitHostPort(req.RemoteAddr); peer != "" { + if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a // file-path that would be interpreted with a sock family. attrs = append(attrs, semconvNew.NetworkPeerAddress(peer)) @@ -135,7 +135,7 @@ func (n newHTTPServer) RequestTraceAttrs(server string, req *http.Request) []att return attrs } -func (n newHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { +func (n CurrentHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { if method == "" { return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} } @@ -150,7 +150,7 @@ func (n newHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyV return semconvNew.HTTPRequestMethodGet, orig } -func (n newHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive +func (n CurrentHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive if https { return semconvNew.URLScheme("https") } @@ -160,7 +160,7 @@ func (n newHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive // TraceResponse returns trace attributes for telemetry from an HTTP response. // // If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (n newHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { +func (n CurrentHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { var count int if resp.ReadBytes > 0 { @@ -195,14 +195,14 @@ func (n newHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.Ke } // Route returns the attribute for the route. -func (n newHTTPServer) Route(route string) attribute.KeyValue { +func (n CurrentHTTPServer) Route(route string) attribute.KeyValue { return semconvNew.HTTPRoute(route) } -type newHTTPClient struct{} +type CurrentHTTPClient struct{} // RequestTraceAttrs returns trace attributes for an HTTP request made by a client. -func (n newHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { +func (n CurrentHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { /* below attributes are returned: - http.request.method @@ -222,7 +222,7 @@ func (n newHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue var requestHost string var requestPort int for _, hostport := range []string{urlHost, req.Header.Get("Host")} { - requestHost, requestPort = splitHostPort(hostport) + requestHost, requestPort = SplitHostPort(hostport) if requestHost != "" || requestPort > 0 { break } @@ -284,7 +284,7 @@ func (n newHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue } // ResponseTraceAttrs returns trace attributes for an HTTP response made by a client. -func (n newHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { +func (n CurrentHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { /* below attributes are returned: - http.response.status_code @@ -311,7 +311,7 @@ func (n newHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyVa return attrs } -func (n newHTTPClient) ErrorType(err error) attribute.KeyValue { +func (n CurrentHTTPClient) ErrorType(err error) attribute.KeyValue { t := reflect.TypeOf(err) var value string if t.PkgPath() == "" && t.Name() == "" { @@ -328,7 +328,7 @@ func (n newHTTPClient) ErrorType(err error) attribute.KeyValue { return semconvNew.ErrorTypeKey.String(value) } -func (n newHTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) { +func (n CurrentHTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) { if method == "" { return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go index e6e14924f57..93e8d0f94c1 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go @@ -14,14 +14,14 @@ import ( semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" ) -// splitHostPort splits a network address hostport of the form "host", +// SplitHostPort splits a network address hostport of the form "host", // "host%zone", "[host]", "[host%zone], "host:port", "host%zone:port", // "[host]:port", "[host%zone]:port", or ":port" into host or host%zone and // port. // // An empty host is returned if it is not provided or unparsable. A negative // port is returned if it is not provided or unparsable. -func splitHostPort(hostport string) (host string, port int) { +func SplitHostPort(hostport string) (host string, port int) { port = -1 if strings.HasPrefix(hostport, "[") { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go index c999b05e675..c042249dd72 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go @@ -17,7 +17,7 @@ import ( semconv "go.opentelemetry.io/otel/semconv/v1.20.0" ) -type oldHTTPServer struct{} +type OldHTTPServer struct{} // RequestTraceAttrs returns trace attributes for an HTTP request received by a // server. @@ -35,14 +35,14 @@ type oldHTTPServer struct{} // // If the primary server name is not known, server should be an empty string. // The req Host will be used to determine the server instead. -func (o oldHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { +func (o OldHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { return semconvutil.HTTPServerRequest(server, req) } // ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. // // If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (o oldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { +func (o OldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { attributes := []attribute.KeyValue{} if resp.ReadBytes > 0 { @@ -67,7 +67,7 @@ func (o oldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.Ke } // Route returns the attribute for the route. -func (o oldHTTPServer) Route(route string) attribute.KeyValue { +func (o OldHTTPServer) Route(route string) attribute.KeyValue { return semconv.HTTPRoute(route) } @@ -84,7 +84,7 @@ const ( serverDuration = "http.server.duration" // Incoming end to end duration, milliseconds ) -func (h oldHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { +func (h OldHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { if meter == nil { return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} } @@ -113,17 +113,17 @@ func (h oldHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Counter, return requestBytesCounter, responseBytesCounter, serverLatencyMeasure } -func (o oldHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { +func (o OldHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { n := len(additionalAttributes) + 3 var host string var p int if server == "" { - host, p = splitHostPort(req.Host) + host, p = SplitHostPort(req.Host) } else { // Prioritize the primary server name. - host, p = splitHostPort(server) + host, p = SplitHostPort(server) if p < 0 { - _, p = splitHostPort(req.Host) + _, p = SplitHostPort(req.Host) } } hostPort := requiredHTTPPort(req.TLS != nil, p) @@ -144,7 +144,7 @@ func (o oldHTTPServer) MetricAttributes(server string, req *http.Request, status attributes := slices.Grow(additionalAttributes, n) attributes = append(attributes, - o.methodMetric(req.Method), + standardizeHTTPMethodMetric(req.Method), o.scheme(req.TLS != nil), semconv.NetHostName(host)) @@ -164,29 +164,111 @@ func (o oldHTTPServer) MetricAttributes(server string, req *http.Request, status return attributes } -func (o oldHTTPServer) methodMetric(method string) attribute.KeyValue { - method = strings.ToUpper(method) - switch method { - case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: - default: - method = "_OTHER" - } - return semconv.HTTPMethod(method) -} - -func (o oldHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive +func (o OldHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive if https { return semconv.HTTPSchemeHTTPS } return semconv.HTTPSchemeHTTP } -type oldHTTPClient struct{} +type OldHTTPClient struct{} -func (o oldHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { +func (o OldHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { return semconvutil.HTTPClientRequest(req) } -func (o oldHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { +func (o OldHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { return semconvutil.HTTPClientResponse(resp) } + +func (o OldHTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + /* The following semantic conventions are returned if present: + http.method string + http.status_code int + net.peer.name string + net.peer.port int + */ + + n := 2 // method, peer name. + var h string + if req.URL != nil { + h = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{h, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if port > 0 { + n++ + } + + if statusCode > 0 { + n++ + } + + attributes := slices.Grow(additionalAttributes, n) + attributes = append(attributes, + standardizeHTTPMethodMetric(req.Method), + semconv.NetPeerName(requestHost), + ) + + if port > 0 { + attributes = append(attributes, semconv.NetPeerPort(port)) + } + + if statusCode > 0 { + attributes = append(attributes, semconv.HTTPStatusCode(statusCode)) + } + return attributes +} + +// Client HTTP metrics. +const ( + clientRequestSize = "http.client.request.size" // Incoming request bytes total + clientResponseSize = "http.client.response.size" // Incoming response bytes total + clientDuration = "http.client.duration" // Incoming end to end duration, milliseconds +) + +func (o OldHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { + if meter == nil { + return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} + } + requestBytesCounter, err := meter.Int64Counter( + clientRequestSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP request messages."), + ) + handleErr(err) + + responseBytesCounter, err := meter.Int64Counter( + clientResponseSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP response messages."), + ) + handleErr(err) + + latencyMeasure, err := meter.Float64Histogram( + clientDuration, + metric.WithUnit("ms"), + metric.WithDescription("Measures the duration of outbound HTTP requests."), + ) + handleErr(err) + + return requestBytesCounter, responseBytesCounter, latencyMeasure +} + +func standardizeHTTPMethodMetric(method string) attribute.KeyValue { + method = strings.ToUpper(method) + switch method { + case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: + default: + method = "_OTHER" + } + return semconv.HTTPMethod(method) +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go new file mode 100644 index 00000000000..9476ef01b01 --- /dev/null +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go @@ -0,0 +1,29 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + +import ( + "context" + "time" +) + +type startTimeContextKeyType int + +const startTimeContextKey startTimeContextKeyType = 0 + +// ContextWithStartTime returns a new context with the provided start time. The +// start time will be used for metrics and traces emitted by the +// instrumentation. Only one labeller can be injected into the context. +// Injecting it multiple times will override the previous calls. +func ContextWithStartTime(parent context.Context, start time.Time) context.Context { + return context.WithValue(parent, startTimeContextKey, start) +} + +// StartTimeFromContext retrieves a time.Time from the provided context if one +// is available. If no start time was found in the provided context, a new, +// zero start time is returned and the second return value is false. +func StartTimeFromContext(ctx context.Context) time.Time { + t, _ := ctx.Value(startTimeContextKey).(time.Time) + return t +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go index b4119d3438b..39681ad4b09 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go @@ -13,11 +13,9 @@ import ( "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" @@ -29,7 +27,6 @@ type Transport struct { rt http.RoundTripper tracer trace.Tracer - meter metric.Meter propagators propagation.TextMapPropagator spanStartOptions []trace.SpanStartOption filters []Filter @@ -37,10 +34,7 @@ type Transport struct { clientTrace func(context.Context) *httptrace.ClientTrace metricAttributesFn func(*http.Request) []attribute.KeyValue - semconv semconv.HTTPClient - requestBytesCounter metric.Int64Counter - responseBytesCounter metric.Int64Counter - latencyMeasure metric.Float64Histogram + semconv semconv.HTTPClient } var _ http.RoundTripper = &Transport{} @@ -57,8 +51,7 @@ func NewTransport(base http.RoundTripper, opts ...Option) *Transport { } t := Transport{ - rt: base, - semconv: semconv.NewHTTPClient(), + rt: base, } defaultOpts := []Option{ @@ -68,46 +61,21 @@ func NewTransport(base http.RoundTripper, opts ...Option) *Transport { c := newConfig(append(defaultOpts, opts...)...) t.applyConfig(c) - t.createMeasures() return &t } func (t *Transport) applyConfig(c *config) { t.tracer = c.Tracer - t.meter = c.Meter t.propagators = c.Propagators t.spanStartOptions = c.SpanStartOptions t.filters = c.Filters t.spanNameFormatter = c.SpanNameFormatter t.clientTrace = c.ClientTrace + t.semconv = semconv.NewHTTPClient(c.Meter) t.metricAttributesFn = c.MetricAttributesFn } -func (t *Transport) createMeasures() { - var err error - t.requestBytesCounter, err = t.meter.Int64Counter( - clientRequestSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP request messages."), - ) - handleErr(err) - - t.responseBytesCounter, err = t.meter.Int64Counter( - clientResponseSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP response messages."), - ) - handleErr(err) - - t.latencyMeasure, err = t.meter.Float64Histogram( - clientDuration, - metric.WithUnit("ms"), - metric.WithDescription("Measures the duration of outbound HTTP requests."), - ) - handleErr(err) -} - func defaultTransportFormatter(_ string, r *http.Request) string { return "HTTP " + r.Method } @@ -177,16 +145,15 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { } // metrics - metricAttrs := append(append(labeler.Get(), semconvutil.HTTPClientRequestMetrics(r)...), t.metricAttributesFromRequest(r)...) - if res.StatusCode > 0 { - metricAttrs = append(metricAttrs, semconv.HTTPStatusCode(res.StatusCode)) - } - o := metric.WithAttributeSet(attribute.NewSet(metricAttrs...)) + metricOpts := t.semconv.MetricOptions(semconv.MetricAttributes{ + Req: r, + StatusCode: res.StatusCode, + AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), + }) - t.requestBytesCounter.Add(ctx, bw.BytesRead(), o) // For handling response bytes we leverage a callback when the client reads the http response readRecordFunc := func(n int64) { - t.responseBytesCounter.Add(ctx, n, o) + t.semconv.RecordResponseSize(ctx, n, metricOpts.AddOptions()) } // traces @@ -198,9 +165,12 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - t.latencyMeasure.Record(ctx, elapsedTime, o) + t.semconv.RecordMetrics(ctx, semconv.MetricData{ + RequestSize: bw.BytesRead(), + ElapsedTime: elapsedTime, + }, metricOpts) - return res, err + return res, nil } func (t *Transport) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index 502c1bdafc7..353e43b91fd 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -5,7 +5,7 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.54.0" + return "0.58.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/golang.org/x/sys/execabs/execabs.go b/vendor/golang.org/x/sys/execabs/execabs.go deleted file mode 100644 index 3bf40fdfecd..00000000000 --- a/vendor/golang.org/x/sys/execabs/execabs.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package execabs is a drop-in replacement for os/exec -// that requires PATH lookups to find absolute paths. -// That is, execabs.Command("cmd") runs the same PATH lookup -// as exec.Command("cmd"), but if the result is a path -// which is relative, the Run and Start methods will report -// an error instead of running the executable. -// -// See https://blog.golang.org/path-security for more information -// about when it may be necessary or appropriate to use this package. -package execabs - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "reflect" - "unsafe" -) - -// ErrNotFound is the error resulting if a path search failed to find an executable file. -// It is an alias for exec.ErrNotFound. -var ErrNotFound = exec.ErrNotFound - -// Cmd represents an external command being prepared or run. -// It is an alias for exec.Cmd. -type Cmd = exec.Cmd - -// Error is returned by LookPath when it fails to classify a file as an executable. -// It is an alias for exec.Error. -type Error = exec.Error - -// An ExitError reports an unsuccessful exit by a command. -// It is an alias for exec.ExitError. -type ExitError = exec.ExitError - -func relError(file, path string) error { - return fmt.Errorf("%s resolves to executable in current directory (.%c%s)", file, filepath.Separator, path) -} - -// LookPath searches for an executable named file in the directories -// named by the PATH environment variable. If file contains a slash, -// it is tried directly and the PATH is not consulted. The result will be -// an absolute path. -// -// LookPath differs from exec.LookPath in its handling of PATH lookups, -// which are used for file names without slashes. If exec.LookPath's -// PATH lookup would have returned an executable from the current directory, -// LookPath instead returns an error. -func LookPath(file string) (string, error) { - path, err := exec.LookPath(file) - if err != nil && !isGo119ErrDot(err) { - return "", err - } - if filepath.Base(file) == file && !filepath.IsAbs(path) { - return "", relError(file, path) - } - return path, nil -} - -func fixCmd(name string, cmd *exec.Cmd) { - if filepath.Base(name) == name && !filepath.IsAbs(cmd.Path) && !isGo119ErrFieldSet(cmd) { - // exec.Command was called with a bare binary name and - // exec.LookPath returned a path which is not absolute. - // Set cmd.lookPathErr and clear cmd.Path so that it - // cannot be run. - lookPathErr := (*error)(unsafe.Pointer(reflect.ValueOf(cmd).Elem().FieldByName("lookPathErr").Addr().Pointer())) - if *lookPathErr == nil { - *lookPathErr = relError(name, cmd.Path) - } - cmd.Path = "" - } -} - -// CommandContext is like Command but includes a context. -// -// The provided context is used to kill the process (by calling os.Process.Kill) -// if the context becomes done before the command completes on its own. -func CommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, name, arg...) - fixCmd(name, cmd) - return cmd - -} - -// Command returns the Cmd struct to execute the named program with the given arguments. -// See exec.Command for most details. -// -// Command differs from exec.Command in its handling of PATH lookups, -// which are used when the program name contains no slashes. -// If exec.Command would have returned an exec.Cmd configured to run an -// executable from the current directory, Command instead -// returns an exec.Cmd that will return an error from Start or Run. -func Command(name string, arg ...string) *exec.Cmd { - cmd := exec.Command(name, arg...) - fixCmd(name, cmd) - return cmd -} diff --git a/vendor/golang.org/x/sys/execabs/execabs_go118.go b/vendor/golang.org/x/sys/execabs/execabs_go118.go deleted file mode 100644 index 5627d70e398..00000000000 --- a/vendor/golang.org/x/sys/execabs/execabs_go118.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.19 - -package execabs - -import "os/exec" - -func isGo119ErrDot(err error) bool { - return false -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return false -} diff --git a/vendor/golang.org/x/sys/execabs/execabs_go119.go b/vendor/golang.org/x/sys/execabs/execabs_go119.go deleted file mode 100644 index d60ab1b4195..00000000000 --- a/vendor/golang.org/x/sys/execabs/execabs_go119.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.19 - -package execabs - -import ( - "errors" - "os/exec" -) - -func isGo119ErrDot(err error) bool { - return errors.Is(err, exec.ErrDot) -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return cmd.Err != nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index b0c4049640b..a33bccf9db7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -60,8 +60,8 @@ github.com/42wim/httpsig ## explicit github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/runtime/2019-08-15-preview/containerregistry github.com/Azure/azure-sdk-for-go/version -# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 -## explicit; go 1.18 +# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0 +## explicit; go 1.23.0 github.com/Azure/azure-sdk-for-go/sdk/azcore github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/internal/resource github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy @@ -82,12 +82,12 @@ 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/azcore/tracing -# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 -## explicit; go 1.18 +# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.9.0 +## explicit; go 1.23.0 github.com/Azure/azure-sdk-for-go/sdk/azidentity github.com/Azure/azure-sdk-for-go/sdk/azidentity/internal -# github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 -## explicit; go 1.18 +# github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 +## explicit; go 1.23.0 github.com/Azure/azure-sdk-for-go/sdk/internal/diag github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo github.com/Azure/azure-sdk-for-go/sdk/internal/exported @@ -95,10 +95,10 @@ 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/security/keyvault/azkeys v1.3.0 +# github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys -# github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 +# github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1 ## explicit; go 1.18 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal # github.com/Azure/go-autorest v14.2.0+incompatible @@ -126,13 +126,13 @@ github.com/Azure/go-autorest/logger # github.com/Azure/go-autorest/tracing v0.6.0 ## explicit; go 1.12 github.com/Azure/go-autorest/tracing -# github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 +# github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 ## explicit; go 1.18 github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base -github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/storage github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time @@ -148,6 +148,7 @@ github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/o github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version +github.com/AzureAD/microsoft-authentication-library-for-go/apps/managedidentity github.com/AzureAD/microsoft-authentication-library-for-go/apps/public # github.com/Microsoft/go-winio v0.6.2 ## explicit; go 1.21 @@ -328,8 +329,8 @@ github.com/cloudevents/sdk-go/v2/event/datacodec/xml github.com/cloudevents/sdk-go/v2/protocol github.com/cloudevents/sdk-go/v2/protocol/http github.com/cloudevents/sdk-go/v2/types -# github.com/containerd/stargz-snapshotter/estargz v0.14.3 -## explicit; go 1.19 +# github.com/containerd/stargz-snapshotter/estargz v0.16.3 +## explicit; go 1.22.0 github.com/containerd/stargz-snapshotter/estargz github.com/containerd/stargz-snapshotter/estargz/errorutil # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc @@ -341,17 +342,17 @@ github.com/davidmz/go-pageant # github.com/dimchansky/utfbom v1.1.1 ## explicit github.com/dimchansky/utfbom -# github.com/docker/cli v27.1.1+incompatible +# github.com/docker/cli v27.5.0+incompatible ## explicit github.com/docker/cli/cli/config github.com/docker/cli/cli/config/configfile github.com/docker/cli/cli/config/credentials github.com/docker/cli/cli/config/types -# github.com/docker/distribution v2.8.2+incompatible +# github.com/docker/distribution v2.8.3+incompatible ## explicit github.com/docker/distribution/registry/client/auth/challenge -# github.com/docker/docker-credential-helpers v0.7.0 -## explicit; go 1.18 +# github.com/docker/docker-credential-helpers v0.8.2 +## explicit; go 1.19 github.com/docker/docker-credential-helpers/client github.com/docker/docker-credential-helpers/credentials # github.com/emicklei/go-restful/v3 v3.12.1 @@ -469,8 +470,8 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/go-containerregistry v0.20.2 -## explicit; go 1.18 +# github.com/google/go-containerregistry v0.20.3 +## explicit; go 1.23.0 github.com/google/go-containerregistry/internal/and github.com/google/go-containerregistry/internal/compression github.com/google/go-containerregistry/internal/estargz @@ -748,7 +749,7 @@ github.com/shurcooL/githubv4 github.com/shurcooL/graphql github.com/shurcooL/graphql/ident github.com/shurcooL/graphql/internal/jsonutil -# github.com/sigstore/protobuf-specs v0.4.0 +# github.com/sigstore/protobuf-specs v0.4.1 ## explicit; go 1.22.0 github.com/sigstore/protobuf-specs/gen/pb-go/common/v1 # github.com/sigstore/sigstore v1.8.15 @@ -766,8 +767,8 @@ github.com/sigstore/sigstore/pkg/signature/payload # github.com/sigstore/sigstore/pkg/signature/kms/aws v1.8.15 ## explicit; go 1.22.0 github.com/sigstore/sigstore/pkg/signature/kms/aws -# github.com/sigstore/sigstore/pkg/signature/kms/azure v1.8.15 -## explicit; go 1.22.0 +# github.com/sigstore/sigstore/pkg/signature/kms/azure v1.9.4 +## explicit; go 1.23.0 github.com/sigstore/sigstore/pkg/signature/kms/azure # github.com/sigstore/sigstore/pkg/signature/kms/gcp v1.8.15 ## explicit; go 1.22.0 @@ -817,8 +818,8 @@ github.com/tektoncd/plumbing/scripts # github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 ## explicit github.com/titanous/rocacheck -# github.com/vbatts/tar-split v0.11.3 -## explicit; go 1.15 +# github.com/vbatts/tar-split v0.11.6 +## explicit; go 1.17 github.com/vbatts/tar-split/archive/tar # github.com/x448/float16 v0.8.4 ## explicit; go 1.11 @@ -855,8 +856,8 @@ go.opentelemetry.io/auto/sdk/internal/telemetry ## explicit; go 1.21 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 -## explicit; go 1.21 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 +## explicit; go 1.22.0 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv @@ -1005,7 +1006,6 @@ golang.org/x/sync/singleflight # golang.org/x/sys v0.32.0 ## explicit; go 1.23.0 golang.org/x/sys/cpu -golang.org/x/sys/execabs golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows