diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 340ea8aa3..aea4f56d8 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -220,7 +220,7 @@ importers: version: 0.39.1(@azure-tools/cadl-ranch-expect@0.15.6)(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0)(@typespec/xml@0.62.0) '@azure-tools/typespec-autorest': specifier: '>=0.48.0 <1.0.0' - version: 0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@azure-tools/typespec-azure-resource-manager@0.48.0)(@azure-tools/typespec-client-generator-core@0.48.2)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) + version: 0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@azure-tools/typespec-azure-resource-manager@0.48.0)(@azure-tools/typespec-client-generator-core@0.48.4)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) '@azure-tools/typespec-azure-core': specifier: '>=0.48.0 <1.0.0' version: 0.48.0(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/rest@0.62.0) @@ -228,8 +228,8 @@ importers: specifier: '>=0.48.0 <1.0.0' version: 0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) '@azure-tools/typespec-client-generator-core': - specifier: '>=0.48.2 <1.0.0' - version: 0.48.2(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) + specifier: '>=0.48.3 <1.0.0' + version: 0.48.4(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) '@types/jest': specifier: ~26.0.24 version: 26.0.24 @@ -524,7 +524,7 @@ packages: engines: {node: '>=10.12.0'} dev: false - /@azure-tools/typespec-autorest@0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@azure-tools/typespec-azure-resource-manager@0.48.0)(@azure-tools/typespec-client-generator-core@0.48.2)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0): + /@azure-tools/typespec-autorest@0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@azure-tools/typespec-azure-resource-manager@0.48.0)(@azure-tools/typespec-client-generator-core@0.48.4)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0): resolution: {integrity: sha512-AyoNMq3EORugHynFF8bN0TJh+zYxui/ApU5DoVEL7Xr1yMD6k9p5b90VD4HiCsP0dz8470ApFnjt5Vl6xCSzig==} engines: {node: '>=18.0.0'} peerDependencies: @@ -539,7 +539,7 @@ packages: dependencies: '@azure-tools/typespec-azure-core': 0.48.0(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/rest@0.62.0) '@azure-tools/typespec-azure-resource-manager': 0.48.0(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) - '@azure-tools/typespec-client-generator-core': 0.48.2(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) + '@azure-tools/typespec-client-generator-core': 0.48.4(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0) '@typespec/compiler': 0.62.0 '@typespec/http': 0.62.0(@typespec/compiler@0.62.0) '@typespec/openapi': 0.62.0(@typespec/compiler@0.62.0)(@typespec/http@0.62.0) @@ -581,8 +581,8 @@ packages: pluralize: 8.0.0 dev: true - /@azure-tools/typespec-client-generator-core@0.48.2(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0): - resolution: {integrity: sha512-5hb+J703pgn6tA3NwPCn2zJ1kWn/YJUkmDC+wfXcWmikp9sEZRE1etMktR0MekJHNO3crDHAK3egsjttnds9nw==} + /@azure-tools/typespec-client-generator-core@0.48.4(@azure-tools/typespec-azure-core@0.48.0)(@typespec/compiler@0.62.0)(@typespec/http@0.62.0)(@typespec/openapi@0.62.0)(@typespec/rest@0.62.0)(@typespec/versioning@0.62.0): + resolution: {integrity: sha512-TvX84FiQ3rax0e838m6kpVj8F24OzKAbyLgUXXZ/TjfxhvZb1u0ojMjSKAvmcal2klROJqRlj4d9tImidPYpgA==} engines: {node: '>=18.0.0'} peerDependencies: '@azure-tools/typespec-azure-core': ~0.48.0 diff --git a/packages/typespec-go/.scripts/tspcompile.js b/packages/typespec-go/.scripts/tspcompile.js index d8eb0cf56..36dd86fc2 100644 --- a/packages/typespec-go/.scripts/tspcompile.js +++ b/packages/typespec-go/.scripts/tspcompile.js @@ -155,6 +155,9 @@ generate('armcontainerorchestratorruntime', armcontainerorchestratorruntime, 'te const azmodelsonly = pkgRoot + 'test/tsp/ModelsOnlyWithBaseTypes'; generate('azmodelsonly', azmodelsonly, 'test/azmodelsonly'); +const azkeys = pkgRoot + 'test/tsp/KeyVault.Keys'; +generate('azkeys', azkeys, 'test/azkeys'); + for (const module in cadlRanch) { const values = cadlRanch[module]; let perTestOptions; diff --git a/packages/typespec-go/CHANGELOG.md b/packages/typespec-go/CHANGELOG.md index 390f1ff64..5f5206004 100644 --- a/packages/typespec-go/CHANGELOG.md +++ b/packages/typespec-go/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 0.3.4 (2024-12-03) + +### Other Fixes + +* Updated dependencies (fixes missing parameters in some cases). + ## 0.3.3 (2024-11-19) ### Other Fixes diff --git a/packages/typespec-go/package.json b/packages/typespec-go/package.json index 24f91fbed..75cb48cef 100644 --- a/packages/typespec-go/package.json +++ b/packages/typespec-go/package.json @@ -1,6 +1,6 @@ { "name": "@azure-tools/typespec-go", - "version": "0.3.3", + "version": "0.3.4", "description": "TypeSpec emitter for Go SDKs", "type": "module", "main": "dist/typespec-go/src/index.js", @@ -52,7 +52,7 @@ "@azure-tools/typespec-autorest": ">=0.48.0 <1.0.0", "@azure-tools/typespec-azure-core": ">=0.48.0 <1.0.0", "@azure-tools/typespec-azure-resource-manager": ">=0.48.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.48.2 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.48.3 <1.0.0", "@types/js-yaml": "~4.0.6", "@types/node": "^18.16.3", "@typescript-eslint/eslint-plugin": "~4.1.1", @@ -70,7 +70,7 @@ "typescript": "~5.1.3" }, "peerDependencies": { - "@azure-tools/typespec-client-generator-core": ">=0.48.2 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.48.3 <1.0.0", "@typespec/compiler": ">=0.62.0 <1.0.0", "@typespec/http": ">=0.62.0 <1.0.0" }, diff --git a/packages/typespec-go/test/azkeys/fake/zz_internal.go b/packages/typespec-go/test/azkeys/fake/zz_internal.go new file mode 100644 index 000000000..88d11305e --- /dev/null +++ b/packages/typespec-go/test/azkeys/fake/zz_internal.go @@ -0,0 +1,76 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func contains[T comparable](s []T, v T) bool { + for _, vv := range s { + if vv == v { + return true + } + } + return false +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, err +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/packages/typespec-go/test/azkeys/fake/zz_keyvault_server.go b/packages/typespec-go/test/azkeys/fake/zz_keyvault_server.go new file mode 100644 index 000000000..2f261a66d --- /dev/null +++ b/packages/typespec-go/test/azkeys/fake/zz_keyvault_server.go @@ -0,0 +1,1067 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azkeys" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// KeyVaultServer is a fake server for instances of the azkeys.KeyVaultClient type. +type KeyVaultServer struct { + // BackupKey is the fake for method KeyVaultClient.BackupKey + // HTTP status codes to indicate success: http.StatusOK + BackupKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientBackupKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientBackupKeyResponse], errResp azfake.ErrorResponder) + + // CreateKey is the fake for method KeyVaultClient.CreateKey + // HTTP status codes to indicate success: http.StatusOK + CreateKey func(ctx context.Context, keyName string, parameters azkeys.KeyCreateParameters, options *azkeys.KeyVaultClientCreateKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientCreateKeyResponse], errResp azfake.ErrorResponder) + + // Decrypt is the fake for method KeyVaultClient.Decrypt + // HTTP status codes to indicate success: http.StatusOK + Decrypt func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyOperationsParameters, options *azkeys.KeyVaultClientDecryptOptions) (resp azfake.Responder[azkeys.KeyVaultClientDecryptResponse], errResp azfake.ErrorResponder) + + // DeleteKey is the fake for method KeyVaultClient.DeleteKey + // HTTP status codes to indicate success: http.StatusOK + DeleteKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientDeleteKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientDeleteKeyResponse], errResp azfake.ErrorResponder) + + // Encrypt is the fake for method KeyVaultClient.Encrypt + // HTTP status codes to indicate success: http.StatusOK + Encrypt func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyOperationsParameters, options *azkeys.KeyVaultClientEncryptOptions) (resp azfake.Responder[azkeys.KeyVaultClientEncryptResponse], errResp azfake.ErrorResponder) + + // GetDeletedKey is the fake for method KeyVaultClient.GetDeletedKey + // HTTP status codes to indicate success: http.StatusOK + GetDeletedKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientGetDeletedKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientGetDeletedKeyResponse], errResp azfake.ErrorResponder) + + // NewGetDeletedKeysPager is the fake for method KeyVaultClient.NewGetDeletedKeysPager + // HTTP status codes to indicate success: http.StatusOK + NewGetDeletedKeysPager func(options *azkeys.KeyVaultClientGetDeletedKeysOptions) (resp azfake.PagerResponder[azkeys.KeyVaultClientGetDeletedKeysResponse]) + + // GetKey is the fake for method KeyVaultClient.GetKey + // HTTP status codes to indicate success: http.StatusOK + GetKey func(ctx context.Context, keyName string, keyVersion string, options *azkeys.KeyVaultClientGetKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientGetKeyResponse], errResp azfake.ErrorResponder) + + // GetKeyRotationPolicy is the fake for method KeyVaultClient.GetKeyRotationPolicy + // HTTP status codes to indicate success: http.StatusOK + GetKeyRotationPolicy func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientGetKeyRotationPolicyOptions) (resp azfake.Responder[azkeys.KeyVaultClientGetKeyRotationPolicyResponse], errResp azfake.ErrorResponder) + + // NewGetKeyVersionsPager is the fake for method KeyVaultClient.NewGetKeyVersionsPager + // HTTP status codes to indicate success: http.StatusOK + NewGetKeyVersionsPager func(keyName string, options *azkeys.KeyVaultClientGetKeyVersionsOptions) (resp azfake.PagerResponder[azkeys.KeyVaultClientGetKeyVersionsResponse]) + + // NewGetKeysPager is the fake for method KeyVaultClient.NewGetKeysPager + // HTTP status codes to indicate success: http.StatusOK + NewGetKeysPager func(options *azkeys.KeyVaultClientGetKeysOptions) (resp azfake.PagerResponder[azkeys.KeyVaultClientGetKeysResponse]) + + // GetRandomBytes is the fake for method KeyVaultClient.GetRandomBytes + // HTTP status codes to indicate success: http.StatusOK + GetRandomBytes func(ctx context.Context, parameters azkeys.GetRandomBytesRequest, options *azkeys.KeyVaultClientGetRandomBytesOptions) (resp azfake.Responder[azkeys.KeyVaultClientGetRandomBytesResponse], errResp azfake.ErrorResponder) + + // ImportKey is the fake for method KeyVaultClient.ImportKey + // HTTP status codes to indicate success: http.StatusOK + ImportKey func(ctx context.Context, keyName string, parameters azkeys.KeyImportParameters, options *azkeys.KeyVaultClientImportKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientImportKeyResponse], errResp azfake.ErrorResponder) + + // PurgeDeletedKey is the fake for method KeyVaultClient.PurgeDeletedKey + // HTTP status codes to indicate success: http.StatusNoContent + PurgeDeletedKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientPurgeDeletedKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientPurgeDeletedKeyResponse], errResp azfake.ErrorResponder) + + // RecoverDeletedKey is the fake for method KeyVaultClient.RecoverDeletedKey + // HTTP status codes to indicate success: http.StatusOK + RecoverDeletedKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientRecoverDeletedKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientRecoverDeletedKeyResponse], errResp azfake.ErrorResponder) + + // Release is the fake for method KeyVaultClient.Release + // HTTP status codes to indicate success: http.StatusOK + Release func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyReleaseParameters, options *azkeys.KeyVaultClientReleaseOptions) (resp azfake.Responder[azkeys.KeyVaultClientReleaseResponse], errResp azfake.ErrorResponder) + + // RestoreKey is the fake for method KeyVaultClient.RestoreKey + // HTTP status codes to indicate success: http.StatusOK + RestoreKey func(ctx context.Context, parameters azkeys.KeyRestoreParameters, options *azkeys.KeyVaultClientRestoreKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientRestoreKeyResponse], errResp azfake.ErrorResponder) + + // RotateKey is the fake for method KeyVaultClient.RotateKey + // HTTP status codes to indicate success: http.StatusOK + RotateKey func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientRotateKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientRotateKeyResponse], errResp azfake.ErrorResponder) + + // Sign is the fake for method KeyVaultClient.Sign + // HTTP status codes to indicate success: http.StatusOK + Sign func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeySignParameters, options *azkeys.KeyVaultClientSignOptions) (resp azfake.Responder[azkeys.KeyVaultClientSignResponse], errResp azfake.ErrorResponder) + + // UnwrapKey is the fake for method KeyVaultClient.UnwrapKey + // HTTP status codes to indicate success: http.StatusOK + UnwrapKey func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyOperationsParameters, options *azkeys.KeyVaultClientUnwrapKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientUnwrapKeyResponse], errResp azfake.ErrorResponder) + + // UpdateKey is the fake for method KeyVaultClient.UpdateKey + // HTTP status codes to indicate success: http.StatusOK + UpdateKey func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyUpdateParameters, options *azkeys.KeyVaultClientUpdateKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientUpdateKeyResponse], errResp azfake.ErrorResponder) + + // UpdateKeyRotationPolicy is the fake for method KeyVaultClient.UpdateKeyRotationPolicy + // HTTP status codes to indicate success: http.StatusOK + UpdateKeyRotationPolicy func(ctx context.Context, keyName string, keyRotationPolicy azkeys.KeyRotationPolicy, options *azkeys.KeyVaultClientUpdateKeyRotationPolicyOptions) (resp azfake.Responder[azkeys.KeyVaultClientUpdateKeyRotationPolicyResponse], errResp azfake.ErrorResponder) + + // Verify is the fake for method KeyVaultClient.Verify + // HTTP status codes to indicate success: http.StatusOK + Verify func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyVerifyParameters, options *azkeys.KeyVaultClientVerifyOptions) (resp azfake.Responder[azkeys.KeyVaultClientVerifyResponse], errResp azfake.ErrorResponder) + + // WrapKey is the fake for method KeyVaultClient.WrapKey + // HTTP status codes to indicate success: http.StatusOK + WrapKey func(ctx context.Context, keyName string, keyVersion string, parameters azkeys.KeyOperationsParameters, options *azkeys.KeyVaultClientWrapKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientWrapKeyResponse], errResp azfake.ErrorResponder) +} + +// NewKeyVaultServerTransport creates a new instance of KeyVaultServerTransport with the provided implementation. +// The returned KeyVaultServerTransport instance is connected to an instance of azkeys.KeyVaultClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewKeyVaultServerTransport(srv *KeyVaultServer) *KeyVaultServerTransport { + return &KeyVaultServerTransport{ + srv: srv, + newGetDeletedKeysPager: newTracker[azfake.PagerResponder[azkeys.KeyVaultClientGetDeletedKeysResponse]](), + newGetKeyVersionsPager: newTracker[azfake.PagerResponder[azkeys.KeyVaultClientGetKeyVersionsResponse]](), + newGetKeysPager: newTracker[azfake.PagerResponder[azkeys.KeyVaultClientGetKeysResponse]](), + } +} + +// KeyVaultServerTransport connects instances of azkeys.KeyVaultClient to instances of KeyVaultServer. +// Don't use this type directly, use NewKeyVaultServerTransport instead. +type KeyVaultServerTransport struct { + srv *KeyVaultServer + newGetDeletedKeysPager *tracker[azfake.PagerResponder[azkeys.KeyVaultClientGetDeletedKeysResponse]] + newGetKeyVersionsPager *tracker[azfake.PagerResponder[azkeys.KeyVaultClientGetKeyVersionsResponse]] + newGetKeysPager *tracker[azfake.PagerResponder[azkeys.KeyVaultClientGetKeysResponse]] +} + +// Do implements the policy.Transporter interface for KeyVaultServerTransport. +func (k *KeyVaultServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return k.dispatchToMethodFake(req, method) +} + +func (k *KeyVaultServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if keyVaultServerTransportInterceptor != nil { + res.resp, res.err, intercepted = keyVaultServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "KeyVaultClient.BackupKey": + res.resp, res.err = k.dispatchBackupKey(req) + case "KeyVaultClient.CreateKey": + res.resp, res.err = k.dispatchCreateKey(req) + case "KeyVaultClient.Decrypt": + res.resp, res.err = k.dispatchDecrypt(req) + case "KeyVaultClient.DeleteKey": + res.resp, res.err = k.dispatchDeleteKey(req) + case "KeyVaultClient.Encrypt": + res.resp, res.err = k.dispatchEncrypt(req) + case "KeyVaultClient.GetDeletedKey": + res.resp, res.err = k.dispatchGetDeletedKey(req) + case "KeyVaultClient.NewGetDeletedKeysPager": + res.resp, res.err = k.dispatchNewGetDeletedKeysPager(req) + case "KeyVaultClient.GetKey": + res.resp, res.err = k.dispatchGetKey(req) + case "KeyVaultClient.GetKeyRotationPolicy": + res.resp, res.err = k.dispatchGetKeyRotationPolicy(req) + case "KeyVaultClient.NewGetKeyVersionsPager": + res.resp, res.err = k.dispatchNewGetKeyVersionsPager(req) + case "KeyVaultClient.NewGetKeysPager": + res.resp, res.err = k.dispatchNewGetKeysPager(req) + case "KeyVaultClient.GetRandomBytes": + res.resp, res.err = k.dispatchGetRandomBytes(req) + case "KeyVaultClient.ImportKey": + res.resp, res.err = k.dispatchImportKey(req) + case "KeyVaultClient.PurgeDeletedKey": + res.resp, res.err = k.dispatchPurgeDeletedKey(req) + case "KeyVaultClient.RecoverDeletedKey": + res.resp, res.err = k.dispatchRecoverDeletedKey(req) + case "KeyVaultClient.Release": + res.resp, res.err = k.dispatchRelease(req) + case "KeyVaultClient.RestoreKey": + res.resp, res.err = k.dispatchRestoreKey(req) + case "KeyVaultClient.RotateKey": + res.resp, res.err = k.dispatchRotateKey(req) + case "KeyVaultClient.Sign": + res.resp, res.err = k.dispatchSign(req) + case "KeyVaultClient.UnwrapKey": + res.resp, res.err = k.dispatchUnwrapKey(req) + case "KeyVaultClient.UpdateKey": + res.resp, res.err = k.dispatchUpdateKey(req) + case "KeyVaultClient.UpdateKeyRotationPolicy": + res.resp, res.err = k.dispatchUpdateKeyRotationPolicy(req) + case "KeyVaultClient.Verify": + res.resp, res.err = k.dispatchVerify(req) + case "KeyVaultClient.WrapKey": + res.resp, res.err = k.dispatchWrapKey(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (k *KeyVaultServerTransport) dispatchBackupKey(req *http.Request) (*http.Response, error) { + if k.srv.BackupKey == nil { + return nil, &nonRetriableError{errors.New("fake for method BackupKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/backup` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.BackupKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BackupKeyResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchCreateKey(req *http.Request) (*http.Response, error) { + if k.srv.CreateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/create` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyCreateParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.CreateKey(req.Context(), keyNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchDecrypt(req *http.Request) (*http.Response, error) { + if k.srv.Decrypt == nil { + return nil, &nonRetriableError{errors.New("fake for method Decrypt not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/decrypt` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationsParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.Decrypt(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchDeleteKey(req *http.Request) (*http.Response, error) { + if k.srv.DeleteKey == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.DeleteKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeletedKeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchEncrypt(req *http.Request) (*http.Response, error) { + if k.srv.Encrypt == nil { + return nil, &nonRetriableError{errors.New("fake for method Encrypt not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encrypt` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationsParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.Encrypt(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchGetDeletedKey(req *http.Request) (*http.Response, error) { + if k.srv.GetDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.GetDeletedKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeletedKeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchNewGetDeletedKeysPager(req *http.Request) (*http.Response, error) { + if k.srv.NewGetDeletedKeysPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewGetDeletedKeysPager not implemented")} + } + newGetDeletedKeysPager := k.newGetDeletedKeysPager.get(req) + if newGetDeletedKeysPager == nil { + qp := req.URL.Query() + maxresultsUnescaped, err := url.QueryUnescape(qp.Get("maxresults")) + if err != nil { + return nil, err + } + maxresultsParam, err := parseOptional(maxresultsUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *azkeys.KeyVaultClientGetDeletedKeysOptions + if maxresultsParam != nil { + options = &azkeys.KeyVaultClientGetDeletedKeysOptions{ + Maxresults: maxresultsParam, + } + } + resp := k.srv.NewGetDeletedKeysPager(options) + newGetDeletedKeysPager = &resp + k.newGetDeletedKeysPager.add(req, newGetDeletedKeysPager) + server.PagerResponderInjectNextLinks(newGetDeletedKeysPager, req, func(page *azkeys.KeyVaultClientGetDeletedKeysResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newGetDeletedKeysPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + k.newGetDeletedKeysPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newGetDeletedKeysPager) { + k.newGetDeletedKeysPager.remove(req) + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchGetKey(req *http.Request) (*http.Response, error) { + if k.srv.GetKey == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.GetKey(req.Context(), keyNameParam, keyVersionParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchGetKeyRotationPolicy(req *http.Request) (*http.Response, error) { + if k.srv.GetKeyRotationPolicy == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKeyRotationPolicy not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotationpolicy` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.GetKeyRotationPolicy(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyRotationPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchNewGetKeyVersionsPager(req *http.Request) (*http.Response, error) { + if k.srv.NewGetKeyVersionsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewGetKeyVersionsPager not implemented")} + } + newGetKeyVersionsPager := k.newGetKeyVersionsPager.get(req) + if newGetKeyVersionsPager == nil { + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + maxresultsUnescaped, err := url.QueryUnescape(qp.Get("maxresults")) + if err != nil { + return nil, err + } + maxresultsParam, err := parseOptional(maxresultsUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *azkeys.KeyVaultClientGetKeyVersionsOptions + if maxresultsParam != nil { + options = &azkeys.KeyVaultClientGetKeyVersionsOptions{ + Maxresults: maxresultsParam, + } + } + resp := k.srv.NewGetKeyVersionsPager(keyNameParam, options) + newGetKeyVersionsPager = &resp + k.newGetKeyVersionsPager.add(req, newGetKeyVersionsPager) + server.PagerResponderInjectNextLinks(newGetKeyVersionsPager, req, func(page *azkeys.KeyVaultClientGetKeyVersionsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newGetKeyVersionsPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + k.newGetKeyVersionsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newGetKeyVersionsPager) { + k.newGetKeyVersionsPager.remove(req) + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchNewGetKeysPager(req *http.Request) (*http.Response, error) { + if k.srv.NewGetKeysPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewGetKeysPager not implemented")} + } + newGetKeysPager := k.newGetKeysPager.get(req) + if newGetKeysPager == nil { + qp := req.URL.Query() + maxresultsUnescaped, err := url.QueryUnescape(qp.Get("maxresults")) + if err != nil { + return nil, err + } + maxresultsParam, err := parseOptional(maxresultsUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *azkeys.KeyVaultClientGetKeysOptions + if maxresultsParam != nil { + options = &azkeys.KeyVaultClientGetKeysOptions{ + Maxresults: maxresultsParam, + } + } + resp := k.srv.NewGetKeysPager(options) + newGetKeysPager = &resp + k.newGetKeysPager.add(req, newGetKeysPager) + server.PagerResponderInjectNextLinks(newGetKeysPager, req, func(page *azkeys.KeyVaultClientGetKeysResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newGetKeysPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + k.newGetKeysPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newGetKeysPager) { + k.newGetKeysPager.remove(req) + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchGetRandomBytes(req *http.Request) (*http.Response, error) { + if k.srv.GetRandomBytes == nil { + return nil, &nonRetriableError{errors.New("fake for method GetRandomBytes not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azkeys.GetRandomBytesRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.GetRandomBytes(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RandomBytes, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchImportKey(req *http.Request) (*http.Response, error) { + if k.srv.ImportKey == nil { + return nil, &nonRetriableError{errors.New("fake for method ImportKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyImportParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.ImportKey(req.Context(), keyNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchPurgeDeletedKey(req *http.Request) (*http.Response, error) { + if k.srv.PurgeDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method PurgeDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.PurgeDeletedKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchRecoverDeletedKey(req *http.Request) (*http.Response, error) { + if k.srv.RecoverDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RecoverDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/recover` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.RecoverDeletedKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchRelease(req *http.Request) (*http.Response, error) { + if k.srv.Release == nil { + return nil, &nonRetriableError{errors.New("fake for method Release not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/release` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyReleaseParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.Release(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyReleaseResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchRestoreKey(req *http.Request) (*http.Response, error) { + if k.srv.RestoreKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RestoreKey not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyRestoreParameters](req) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.RestoreKey(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchRotateKey(req *http.Request) (*http.Response, error) { + if k.srv.RotateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RotateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.RotateKey(req.Context(), keyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchSign(req *http.Request) (*http.Response, error) { + if k.srv.Sign == nil { + return nil, &nonRetriableError{errors.New("fake for method Sign not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sign` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeySignParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.Sign(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchUnwrapKey(req *http.Request) (*http.Response, error) { + if k.srv.UnwrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method UnwrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/unwrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationsParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.UnwrapKey(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchUpdateKey(req *http.Request) (*http.Response, error) { + if k.srv.UpdateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyUpdateParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.UpdateKey(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchUpdateKeyRotationPolicy(req *http.Request) (*http.Response, error) { + if k.srv.UpdateKeyRotationPolicy == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateKeyRotationPolicy not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotationpolicy` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyRotationPolicy](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.UpdateKeyRotationPolicy(req.Context(), keyNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyRotationPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchVerify(req *http.Request) (*http.Response, error) { + if k.srv.Verify == nil { + return nil, &nonRetriableError{errors.New("fake for method Verify not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/verify` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyVerifyParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.Verify(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyVerifyResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (k *KeyVaultServerTransport) dispatchWrapKey(req *http.Request) (*http.Response, error) { + if k.srv.WrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method WrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/wrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationsParameters](req) + if err != nil { + return nil, err + } + keyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + keyVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := k.srv.WrapKey(req.Context(), keyNameParam, keyVersionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to KeyVaultServerTransport +var keyVaultServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/packages/typespec-go/test/azkeys/fake/zz_time_unix.go b/packages/typespec-go/test/azkeys/fake/zz_time_unix.go new file mode 100644 index 000000000..a795e8a34 --- /dev/null +++ b/packages/typespec-go/test/azkeys/fake/zz_time_unix.go @@ -0,0 +1,56 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "time" +) + +type timeUnix time.Time + +func (t timeUnix) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Time(t).Unix()) +} + +func (t *timeUnix) UnmarshalJSON(data []byte) error { + var seconds int64 + if err := json.Unmarshal(data, &seconds); err != nil { + return err + } + *t = timeUnix(time.Unix(seconds, 0)) + return nil +} + +func (t timeUnix) String() string { + return fmt.Sprintf("%d", time.Time(t).Unix()) +} + +func populateTimeUnix(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeUnix)(t) +} + +func unpopulateTimeUnix(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux timeUnix + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/packages/typespec-go/test/azkeys/fake_test.go b/packages/typespec-go/test/azkeys/fake_test.go new file mode 100644 index 000000000..abd7d4204 --- /dev/null +++ b/packages/typespec-go/test/azkeys/fake_test.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azkeys_test + +import ( + "azkeys" + "azkeys/fake" + "context" + "fmt" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/stretchr/testify/require" +) + +func TestFakeBackupKey(t *testing.T) { + const fakeKeyName = "fakeKey" + fakeKeyBlob := []byte{1, 2, 3} + server := fake.KeyVaultServer{ + BackupKey: func(ctx context.Context, keyName string, options *azkeys.KeyVaultClientBackupKeyOptions) (resp azfake.Responder[azkeys.KeyVaultClientBackupKeyResponse], errResp azfake.ErrorResponder) { + if keyName != fakeKeyName { + errResp.SetError(fmt.Errorf("bad fake key name %s", keyName)) + return + } + resp.SetResponse(http.StatusOK, azkeys.KeyVaultClientBackupKeyResponse{ + BackupKeyResult: azkeys.BackupKeyResult{ + Value: fakeKeyBlob, + }, + }, nil) + return + }, + } + + client, err := azkeys.NewKeyVaultClient("https://contoso.com/fake/vault", &azcore.ClientOptions{ + Transport: fake.NewKeyVaultServerTransport(&server), + }) + require.NoError(t, err) + + resp, err := client.BackupKey(context.Background(), fakeKeyName, nil) + require.NoError(t, err) + require.Equal(t, fakeKeyBlob, resp.Value) +} diff --git a/packages/typespec-go/test/azkeys/go.mod b/packages/typespec-go/test/azkeys/go.mod new file mode 100644 index 000000000..405a68f22 --- /dev/null +++ b/packages/typespec-go/test/azkeys/go.mod @@ -0,0 +1,17 @@ +module azkeys + +go 1.18 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 + github.com/stretchr/testify v1.9.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/text v0.18.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/packages/typespec-go/test/azkeys/go.sum b/packages/typespec-go/test/azkeys/go.sum new file mode 100644 index 000000000..26467d48e --- /dev/null +++ b/packages/typespec-go/test/azkeys/go.sum @@ -0,0 +1,21 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 h1:JZg6HRh6W6U4OLl6lk7BZ7BLisIzM9dG1R50zUk9C/M= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0/go.mod h1:YL1xnZ6QejvQHWJrX/AvhFl4WW4rqHVoKspWNVwFk0M= +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/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/packages/typespec-go/test/azkeys/keyvault_client.go b/packages/typespec-go/test/azkeys/keyvault_client.go new file mode 100644 index 000000000..b5d4a45ca --- /dev/null +++ b/packages/typespec-go/test/azkeys/keyvault_client.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azkeys + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewKeyVaultClient(vaultURL string, options *azcore.ClientOptions) (*KeyVaultClient, error) { + client, err := azcore.NewClient("azkeys", "v0.1.0", runtime.PipelineOptions{}, options) + if err != nil { + return nil, err + } + return &KeyVaultClient{ + internal: client, + vaultBaseUrl: vaultURL, + }, nil +} diff --git a/packages/typespec-go/test/azkeys/zz_constants.go b/packages/typespec-go/test/azkeys/zz_constants.go new file mode 100644 index 000000000..24536c3d0 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_constants.go @@ -0,0 +1,258 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +// JSONWebKeyCurveName - Elliptic curve name. For valid values, see JsonWebKeyCurveName. +type JSONWebKeyCurveName string + +const ( + // JSONWebKeyCurveNameP256 - The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. + JSONWebKeyCurveNameP256 JSONWebKeyCurveName = "P-256" + // JSONWebKeyCurveNameP256K - The SECG SECP256K1 elliptic curve. + JSONWebKeyCurveNameP256K JSONWebKeyCurveName = "P-256K" + // JSONWebKeyCurveNameP384 - The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. + JSONWebKeyCurveNameP384 JSONWebKeyCurveName = "P-384" + // JSONWebKeyCurveNameP521 - The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. + JSONWebKeyCurveNameP521 JSONWebKeyCurveName = "P-521" +) + +// PossibleJSONWebKeyCurveNameValues returns the possible values for the JSONWebKeyCurveName const type. +func PossibleJSONWebKeyCurveNameValues() []JSONWebKeyCurveName { + return []JSONWebKeyCurveName{ + JSONWebKeyCurveNameP256, + JSONWebKeyCurveNameP256K, + JSONWebKeyCurveNameP384, + JSONWebKeyCurveNameP521, + } +} + +// JSONWebKeyEncryptionAlgorithm - An algorithm used for encryption and decryption. +type JSONWebKeyEncryptionAlgorithm string + +const ( + // JSONWebKeyEncryptionAlgorithmA128CBC - 128-bit AES-CBC. + JSONWebKeyEncryptionAlgorithmA128CBC JSONWebKeyEncryptionAlgorithm = "A128CBC" + // JSONWebKeyEncryptionAlgorithmA128CBCPAD - 128-bit AES-CBC with PKCS padding. + JSONWebKeyEncryptionAlgorithmA128CBCPAD JSONWebKeyEncryptionAlgorithm = "A128CBCPAD" + // JSONWebKeyEncryptionAlgorithmA128GCM - 128-bit AES-GCM. + JSONWebKeyEncryptionAlgorithmA128GCM JSONWebKeyEncryptionAlgorithm = "A128GCM" + // JSONWebKeyEncryptionAlgorithmA128KW - 128-bit AES key wrap. + JSONWebKeyEncryptionAlgorithmA128KW JSONWebKeyEncryptionAlgorithm = "A128KW" + // JSONWebKeyEncryptionAlgorithmA192CBC - 192-bit AES-CBC. + JSONWebKeyEncryptionAlgorithmA192CBC JSONWebKeyEncryptionAlgorithm = "A192CBC" + // JSONWebKeyEncryptionAlgorithmA192CBCPAD - 192-bit AES-CBC with PKCS padding. + JSONWebKeyEncryptionAlgorithmA192CBCPAD JSONWebKeyEncryptionAlgorithm = "A192CBCPAD" + // JSONWebKeyEncryptionAlgorithmA192GCM - 192-bit AES-GCM. + JSONWebKeyEncryptionAlgorithmA192GCM JSONWebKeyEncryptionAlgorithm = "A192GCM" + // JSONWebKeyEncryptionAlgorithmA192KW - 192-bit AES key wrap. + JSONWebKeyEncryptionAlgorithmA192KW JSONWebKeyEncryptionAlgorithm = "A192KW" + // JSONWebKeyEncryptionAlgorithmA256CBC - 256-bit AES-CBC. + JSONWebKeyEncryptionAlgorithmA256CBC JSONWebKeyEncryptionAlgorithm = "A256CBC" + // JSONWebKeyEncryptionAlgorithmA256CBCPAD - 256-bit AES-CBC with PKCS padding. + JSONWebKeyEncryptionAlgorithmA256CBCPAD JSONWebKeyEncryptionAlgorithm = "A256CBCPAD" + // JSONWebKeyEncryptionAlgorithmA256GCM - 256-bit AES-GCM. + JSONWebKeyEncryptionAlgorithmA256GCM JSONWebKeyEncryptionAlgorithm = "A256GCM" + // JSONWebKeyEncryptionAlgorithmA256KW - 256-bit AES key wrap. + JSONWebKeyEncryptionAlgorithmA256KW JSONWebKeyEncryptionAlgorithm = "A256KW" + // JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAP - CKM AES key wrap. + JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAP JSONWebKeyEncryptionAlgorithm = "CKM_AES_KEY_WRAP" + // JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAPPAD - CKM AES key wrap with padding. + JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAPPAD JSONWebKeyEncryptionAlgorithm = "CKM_AES_KEY_WRAP_PAD" + // JSONWebKeyEncryptionAlgorithmRSA15 - RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. + JSONWebKeyEncryptionAlgorithmRSA15 JSONWebKeyEncryptionAlgorithm = "RSA1_5" + // JSONWebKeyEncryptionAlgorithmRSAOAEP - 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. + JSONWebKeyEncryptionAlgorithmRSAOAEP JSONWebKeyEncryptionAlgorithm = "RSA-OAEP" + // JSONWebKeyEncryptionAlgorithmRSAOAEP256 - RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 + // and a mask generation function of MGF1 with SHA-256. + JSONWebKeyEncryptionAlgorithmRSAOAEP256 JSONWebKeyEncryptionAlgorithm = "RSA-OAEP-256" +) + +// PossibleJSONWebKeyEncryptionAlgorithmValues returns the possible values for the JSONWebKeyEncryptionAlgorithm const type. +func PossibleJSONWebKeyEncryptionAlgorithmValues() []JSONWebKeyEncryptionAlgorithm { + return []JSONWebKeyEncryptionAlgorithm{ + JSONWebKeyEncryptionAlgorithmA128CBC, + JSONWebKeyEncryptionAlgorithmA128CBCPAD, + JSONWebKeyEncryptionAlgorithmA128GCM, + JSONWebKeyEncryptionAlgorithmA128KW, + JSONWebKeyEncryptionAlgorithmA192CBC, + JSONWebKeyEncryptionAlgorithmA192CBCPAD, + JSONWebKeyEncryptionAlgorithmA192GCM, + JSONWebKeyEncryptionAlgorithmA192KW, + JSONWebKeyEncryptionAlgorithmA256CBC, + JSONWebKeyEncryptionAlgorithmA256CBCPAD, + JSONWebKeyEncryptionAlgorithmA256GCM, + JSONWebKeyEncryptionAlgorithmA256KW, + JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAP, + JSONWebKeyEncryptionAlgorithmCKMAESKEYWRAPPAD, + JSONWebKeyEncryptionAlgorithmRSA15, + JSONWebKeyEncryptionAlgorithmRSAOAEP, + JSONWebKeyEncryptionAlgorithmRSAOAEP256, + } +} + +// JSONWebKeyOperation - JSON web key operations. For more information, see JsonWebKeyOperation. +type JSONWebKeyOperation string + +const ( + // JSONWebKeyOperationDecrypt - Indicates that the key can be used to decrypt. + JSONWebKeyOperationDecrypt JSONWebKeyOperation = "decrypt" + // JSONWebKeyOperationEncrypt - Indicates that the key can be used to encrypt. + JSONWebKeyOperationEncrypt JSONWebKeyOperation = "encrypt" + // JSONWebKeyOperationExport - Indicates that the private component of the key can be exported. + JSONWebKeyOperationExport JSONWebKeyOperation = "export" + // JSONWebKeyOperationImport - Indicates that the key can be imported during creation. + JSONWebKeyOperationImport JSONWebKeyOperation = "import" + // JSONWebKeyOperationSign - Indicates that the key can be used to sign. + JSONWebKeyOperationSign JSONWebKeyOperation = "sign" + // JSONWebKeyOperationUnwrapKey - Indicates that the key can be used to unwrap another key. + JSONWebKeyOperationUnwrapKey JSONWebKeyOperation = "unwrapKey" + // JSONWebKeyOperationVerify - Indicates that the key can be used to verify. + JSONWebKeyOperationVerify JSONWebKeyOperation = "verify" + // JSONWebKeyOperationWrapKey - Indicates that the key can be used to wrap another key. + JSONWebKeyOperationWrapKey JSONWebKeyOperation = "wrapKey" +) + +// PossibleJSONWebKeyOperationValues returns the possible values for the JSONWebKeyOperation const type. +func PossibleJSONWebKeyOperationValues() []JSONWebKeyOperation { + return []JSONWebKeyOperation{ + JSONWebKeyOperationDecrypt, + JSONWebKeyOperationEncrypt, + JSONWebKeyOperationExport, + JSONWebKeyOperationImport, + JSONWebKeyOperationSign, + JSONWebKeyOperationUnwrapKey, + JSONWebKeyOperationVerify, + JSONWebKeyOperationWrapKey, + } +} + +// JSONWebKeySignatureAlgorithm - The signing/verification algorithm identifier. For more information on possible +// algorithm types, see JsonWebKeySignatureAlgorithm. +type JSONWebKeySignatureAlgorithm string + +const ( + // JSONWebKeySignatureAlgorithmES256 - ECDSA using P-256 and SHA-256, as described in + // https://tools.ietf.org/html/rfc7518. + JSONWebKeySignatureAlgorithmES256 JSONWebKeySignatureAlgorithm = "ES256" + // JSONWebKeySignatureAlgorithmES256K - ECDSA using P-256K and SHA-256, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmES256K JSONWebKeySignatureAlgorithm = "ES256K" + // JSONWebKeySignatureAlgorithmES384 - ECDSA using P-384 and SHA-384, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmES384 JSONWebKeySignatureAlgorithm = "ES384" + // JSONWebKeySignatureAlgorithmES512 - ECDSA using P-521 and SHA-512, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmES512 JSONWebKeySignatureAlgorithm = "ES512" + // JSONWebKeySignatureAlgorithmPS256 - RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmPS256 JSONWebKeySignatureAlgorithm = "PS256" + // JSONWebKeySignatureAlgorithmPS384 - RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmPS384 JSONWebKeySignatureAlgorithm = "PS384" + // JSONWebKeySignatureAlgorithmPS512 - RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmPS512 JSONWebKeySignatureAlgorithm = "PS512" + // JSONWebKeySignatureAlgorithmRS256 - RSASSA-PKCS1-v1_5 using SHA-256, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmRS256 JSONWebKeySignatureAlgorithm = "RS256" + // JSONWebKeySignatureAlgorithmRS384 - RSASSA-PKCS1-v1_5 using SHA-384, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmRS384 JSONWebKeySignatureAlgorithm = "RS384" + // JSONWebKeySignatureAlgorithmRS512 - RSASSA-PKCS1-v1_5 using SHA-512, as described in + // https://tools.ietf.org/html/rfc7518 + JSONWebKeySignatureAlgorithmRS512 JSONWebKeySignatureAlgorithm = "RS512" + // JSONWebKeySignatureAlgorithmRSNULL - Reserved + JSONWebKeySignatureAlgorithmRSNULL JSONWebKeySignatureAlgorithm = "RSNULL" +) + +// PossibleJSONWebKeySignatureAlgorithmValues returns the possible values for the JSONWebKeySignatureAlgorithm const type. +func PossibleJSONWebKeySignatureAlgorithmValues() []JSONWebKeySignatureAlgorithm { + return []JSONWebKeySignatureAlgorithm{ + JSONWebKeySignatureAlgorithmES256, + JSONWebKeySignatureAlgorithmES256K, + JSONWebKeySignatureAlgorithmES384, + JSONWebKeySignatureAlgorithmES512, + JSONWebKeySignatureAlgorithmPS256, + JSONWebKeySignatureAlgorithmPS384, + JSONWebKeySignatureAlgorithmPS512, + JSONWebKeySignatureAlgorithmRS256, + JSONWebKeySignatureAlgorithmRS384, + JSONWebKeySignatureAlgorithmRS512, + JSONWebKeySignatureAlgorithmRSNULL, + } +} + +// JSONWebKeyType - JsonWebKey Key Type (kty), as defined in +// https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. +type JSONWebKeyType string + +const ( + // JSONWebKeyTypeEC - Elliptic Curve. + JSONWebKeyTypeEC JSONWebKeyType = "EC" + // JSONWebKeyTypeECHSM - Elliptic Curve with a private key which is stored in the HSM. + JSONWebKeyTypeECHSM JSONWebKeyType = "EC-HSM" + // JSONWebKeyTypeOct - Octet sequence (used to represent symmetric keys) + JSONWebKeyTypeOct JSONWebKeyType = "oct" + // JSONWebKeyTypeOctHSM - Octet sequence (used to represent symmetric keys) which is stored the HSM. + JSONWebKeyTypeOctHSM JSONWebKeyType = "oct-HSM" + // JSONWebKeyTypeRSA - RSA (https://tools.ietf.org/html/rfc3447) + JSONWebKeyTypeRSA JSONWebKeyType = "RSA" + // JSONWebKeyTypeRSAHSM - RSA with a private key which is stored in the HSM. + JSONWebKeyTypeRSAHSM JSONWebKeyType = "RSA-HSM" +) + +// PossibleJSONWebKeyTypeValues returns the possible values for the JSONWebKeyType const type. +func PossibleJSONWebKeyTypeValues() []JSONWebKeyType { + return []JSONWebKeyType{ + JSONWebKeyTypeEC, + JSONWebKeyTypeECHSM, + JSONWebKeyTypeOct, + JSONWebKeyTypeOctHSM, + JSONWebKeyTypeRSA, + JSONWebKeyTypeRSAHSM, + } +} + +// 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, + } +} + +// KeyRotationPolicyAction - The type of the action. The value should be compared case-insensitively. +type KeyRotationPolicyAction 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" +) + +// PossibleKeyRotationPolicyActionValues returns the possible values for the KeyRotationPolicyAction const type. +func PossibleKeyRotationPolicyActionValues() []KeyRotationPolicyAction { + return []KeyRotationPolicyAction{ + KeyRotationPolicyActionNotify, + KeyRotationPolicyActionRotate, + } +} diff --git a/packages/typespec-go/test/azkeys/zz_keyvault_client.go b/packages/typespec-go/test/azkeys/zz_keyvault_client.go new file mode 100644 index 000000000..57d8310e9 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_keyvault_client.go @@ -0,0 +1,1643 @@ +// 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) 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" + "strconv" + "strings" +) + +// KeyVaultClient - 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 KeyVaultClient struct { + 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.6-preview.1 +// - keyName - The name of the key. +// - options - KeyVaultClientBackupKeyOptions contains the optional parameters for the KeyVaultClient.BackupKey method. +func (client *KeyVaultClient) BackupKey(ctx context.Context, keyName string, options *KeyVaultClientBackupKeyOptions) (KeyVaultClientBackupKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.BackupKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.backupKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientBackupKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientBackupKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientBackupKeyResponse{}, err + } + resp, err := client.backupKeyHandleResponse(httpResp) + return resp, err +} + +// backupKeyCreateRequest creates the BackupKey request. +func (client *KeyVaultClient) backupKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientBackupKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/backup" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// backupKeyHandleResponse handles the BackupKey response. +func (client *KeyVaultClient) backupKeyHandleResponse(resp *http.Response) (KeyVaultClientBackupKeyResponse, error) { + result := KeyVaultClientBackupKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BackupKeyResult); err != nil { + return KeyVaultClientBackupKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - 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. +// - parameters - The parameters to create a key. +// - options - KeyVaultClientCreateKeyOptions contains the optional parameters for the KeyVaultClient.CreateKey method. +func (client *KeyVaultClient) CreateKey(ctx context.Context, keyName string, parameters KeyCreateParameters, options *KeyVaultClientCreateKeyOptions) (KeyVaultClientCreateKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.CreateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createKeyCreateRequest(ctx, keyName, parameters, options) + if err != nil { + return KeyVaultClientCreateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientCreateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientCreateKeyResponse{}, err + } + resp, err := client.createKeyHandleResponse(httpResp) + return resp, err +} + +// createKeyCreateRequest creates the CreateKey request. +func (client *KeyVaultClient) createKeyCreateRequest(ctx context.Context, keyName string, parameters KeyCreateParameters, _ *KeyVaultClientCreateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/create" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// createKeyHandleResponse handles the CreateKey response. +func (client *KeyVaultClient) createKeyHandleResponse(resp *http.Response) (KeyVaultClientCreateKeyResponse, error) { + result := KeyVaultClientCreateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientCreateKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for the decryption operation. +// - options - KeyVaultClientDecryptOptions contains the optional parameters for the KeyVaultClient.Decrypt method. +func (client *KeyVaultClient) Decrypt(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, options *KeyVaultClientDecryptOptions) (KeyVaultClientDecryptResponse, error) { + var err error + const operationName = "KeyVaultClient.Decrypt" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.decryptCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientDecryptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientDecryptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientDecryptResponse{}, err + } + resp, err := client.decryptHandleResponse(httpResp) + return resp, err +} + +// decryptCreateRequest creates the Decrypt request. +func (client *KeyVaultClient) decryptCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, _ *KeyVaultClientDecryptOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/decrypt" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// decryptHandleResponse handles the Decrypt response. +func (client *KeyVaultClient) decryptHandleResponse(resp *http.Response) (KeyVaultClientDecryptResponse, error) { + result := KeyVaultClientDecryptResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return KeyVaultClientDecryptResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key to delete. +// - options - KeyVaultClientDeleteKeyOptions contains the optional parameters for the KeyVaultClient.DeleteKey method. +func (client *KeyVaultClient) DeleteKey(ctx context.Context, keyName string, options *KeyVaultClientDeleteKeyOptions) (KeyVaultClientDeleteKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.DeleteKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientDeleteKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientDeleteKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientDeleteKeyResponse{}, err + } + resp, err := client.deleteKeyHandleResponse(httpResp) + return resp, err +} + +// deleteKeyCreateRequest creates the DeleteKey request. +func (client *KeyVaultClient) deleteKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientDeleteKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// deleteKeyHandleResponse handles the DeleteKey response. +func (client *KeyVaultClient) deleteKeyHandleResponse(resp *http.Response) (KeyVaultClientDeleteKeyResponse, error) { + result := KeyVaultClientDeleteKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKeyBundle); err != nil { + return KeyVaultClientDeleteKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for the encryption operation. +// - options - KeyVaultClientEncryptOptions contains the optional parameters for the KeyVaultClient.Encrypt method. +func (client *KeyVaultClient) Encrypt(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, options *KeyVaultClientEncryptOptions) (KeyVaultClientEncryptResponse, error) { + var err error + const operationName = "KeyVaultClient.Encrypt" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.encryptCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientEncryptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientEncryptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientEncryptResponse{}, err + } + resp, err := client.encryptHandleResponse(httpResp) + return resp, err +} + +// encryptCreateRequest creates the Encrypt request. +func (client *KeyVaultClient) encryptCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, _ *KeyVaultClientEncryptOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/encrypt" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// encryptHandleResponse handles the Encrypt response. +func (client *KeyVaultClient) encryptHandleResponse(resp *http.Response) (KeyVaultClientEncryptResponse, error) { + result := KeyVaultClientEncryptResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return KeyVaultClientEncryptResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - options - KeyVaultClientGetDeletedKeyOptions contains the optional parameters for the KeyVaultClient.GetDeletedKey method. +func (client *KeyVaultClient) GetDeletedKey(ctx context.Context, keyName string, options *KeyVaultClientGetDeletedKeyOptions) (KeyVaultClientGetDeletedKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.GetDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDeletedKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientGetDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientGetDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientGetDeletedKeyResponse{}, err + } + resp, err := client.getDeletedKeyHandleResponse(httpResp) + return resp, err +} + +// getDeletedKeyCreateRequest creates the GetDeletedKey request. +func (client *KeyVaultClient) getDeletedKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientGetDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/deletedkeys/{key-name}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedKeyHandleResponse handles the GetDeletedKey response. +func (client *KeyVaultClient) getDeletedKeyHandleResponse(resp *http.Response) (KeyVaultClientGetDeletedKeyResponse, error) { + result := KeyVaultClientGetDeletedKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKeyBundle); err != nil { + return KeyVaultClientGetDeletedKeyResponse{}, err + } + return result, nil +} + +// NewGetDeletedKeysPager - 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.6-preview.1 +// - options - KeyVaultClientGetDeletedKeysOptions contains the optional parameters for the KeyVaultClient.NewGetDeletedKeysPager +// method. +func (client *KeyVaultClient) NewGetDeletedKeysPager(options *KeyVaultClientGetDeletedKeysOptions) *runtime.Pager[KeyVaultClientGetDeletedKeysResponse] { + return runtime.NewPager(runtime.PagingHandler[KeyVaultClientGetDeletedKeysResponse]{ + More: func(page KeyVaultClientGetDeletedKeysResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *KeyVaultClientGetDeletedKeysResponse) (KeyVaultClientGetDeletedKeysResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "KeyVaultClient.NewGetDeletedKeysPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.getDeletedKeysCreateRequest(ctx, options) + }, nil) + if err != nil { + return KeyVaultClientGetDeletedKeysResponse{}, err + } + return client.getDeletedKeysHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getDeletedKeysCreateRequest creates the GetDeletedKeys request. +func (client *KeyVaultClient) getDeletedKeysCreateRequest(ctx context.Context, options *KeyVaultClientGetDeletedKeysOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/deletedkeys" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedKeysHandleResponse handles the GetDeletedKeys response. +func (client *KeyVaultClient) getDeletedKeysHandleResponse(resp *http.Response) (KeyVaultClientGetDeletedKeysResponse, error) { + result := KeyVaultClientGetDeletedKeysResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKeyListResult); err != nil { + return KeyVaultClientGetDeletedKeysResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key to get. +// - keyVersion - Adding the version parameter retrieves a specific version of a key. This URI +// fragment is optional. If not specified, the latest version of the key is +// returned. +// - options - KeyVaultClientGetKeyOptions contains the optional parameters for the KeyVaultClient.GetKey method. +func (client *KeyVaultClient) GetKey(ctx context.Context, keyName string, keyVersion string, options *KeyVaultClientGetKeyOptions) (KeyVaultClientGetKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.GetKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKeyCreateRequest(ctx, keyName, keyVersion, options) + if err != nil { + return KeyVaultClientGetKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientGetKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientGetKeyResponse{}, err + } + resp, err := client.getKeyHandleResponse(httpResp) + return resp, err +} + +// getKeyCreateRequest creates the GetKey request. +func (client *KeyVaultClient) getKeyCreateRequest(ctx context.Context, keyName string, keyVersion string, _ *KeyVaultClientGetKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyHandleResponse handles the GetKey response. +func (client *KeyVaultClient) getKeyHandleResponse(resp *http.Response) (KeyVaultClientGetKeyResponse, error) { + result := KeyVaultClientGetKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientGetKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key in a given key vault. +// - options - KeyVaultClientGetKeyRotationPolicyOptions contains the optional parameters for the KeyVaultClient.GetKeyRotationPolicy +// method. +func (client *KeyVaultClient) GetKeyRotationPolicy(ctx context.Context, keyName string, options *KeyVaultClientGetKeyRotationPolicyOptions) (KeyVaultClientGetKeyRotationPolicyResponse, error) { + var err error + const operationName = "KeyVaultClient.GetKeyRotationPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKeyRotationPolicyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientGetKeyRotationPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientGetKeyRotationPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientGetKeyRotationPolicyResponse{}, err + } + resp, err := client.getKeyRotationPolicyHandleResponse(httpResp) + return resp, err +} + +// getKeyRotationPolicyCreateRequest creates the GetKeyRotationPolicy request. +func (client *KeyVaultClient) getKeyRotationPolicyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientGetKeyRotationPolicyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/rotationpolicy" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyRotationPolicyHandleResponse handles the GetKeyRotationPolicy response. +func (client *KeyVaultClient) getKeyRotationPolicyHandleResponse(resp *http.Response) (KeyVaultClientGetKeyRotationPolicyResponse, error) { + result := KeyVaultClientGetKeyRotationPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyRotationPolicy); err != nil { + return KeyVaultClientGetKeyRotationPolicyResponse{}, err + } + return result, nil +} + +// NewGetKeyVersionsPager - 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.6-preview.1 +// - keyName - The name of the key. +// - options - KeyVaultClientGetKeyVersionsOptions contains the optional parameters for the KeyVaultClient.NewGetKeyVersionsPager +// method. +func (client *KeyVaultClient) NewGetKeyVersionsPager(keyName string, options *KeyVaultClientGetKeyVersionsOptions) *runtime.Pager[KeyVaultClientGetKeyVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[KeyVaultClientGetKeyVersionsResponse]{ + More: func(page KeyVaultClientGetKeyVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *KeyVaultClientGetKeyVersionsResponse) (KeyVaultClientGetKeyVersionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "KeyVaultClient.NewGetKeyVersionsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.getKeyVersionsCreateRequest(ctx, keyName, options) + }, nil) + if err != nil { + return KeyVaultClientGetKeyVersionsResponse{}, err + } + return client.getKeyVersionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getKeyVersionsCreateRequest creates the GetKeyVersions request. +func (client *KeyVaultClient) getKeyVersionsCreateRequest(ctx context.Context, keyName string, options *KeyVaultClientGetKeyVersionsOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/versions" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyVersionsHandleResponse handles the GetKeyVersions response. +func (client *KeyVaultClient) getKeyVersionsHandleResponse(resp *http.Response) (KeyVaultClientGetKeyVersionsResponse, error) { + result := KeyVaultClientGetKeyVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil { + return KeyVaultClientGetKeyVersionsResponse{}, err + } + return result, nil +} + +// NewGetKeysPager - 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.6-preview.1 +// - options - KeyVaultClientGetKeysOptions contains the optional parameters for the KeyVaultClient.NewGetKeysPager method. +func (client *KeyVaultClient) NewGetKeysPager(options *KeyVaultClientGetKeysOptions) *runtime.Pager[KeyVaultClientGetKeysResponse] { + return runtime.NewPager(runtime.PagingHandler[KeyVaultClientGetKeysResponse]{ + More: func(page KeyVaultClientGetKeysResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *KeyVaultClientGetKeysResponse) (KeyVaultClientGetKeysResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "KeyVaultClient.NewGetKeysPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.getKeysCreateRequest(ctx, options) + }, nil) + if err != nil { + return KeyVaultClientGetKeysResponse{}, err + } + return client.getKeysHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// getKeysCreateRequest creates the GetKeys request. +func (client *KeyVaultClient) getKeysCreateRequest(ctx context.Context, options *KeyVaultClientGetKeysOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeysHandleResponse handles the GetKeys response. +func (client *KeyVaultClient) getKeysHandleResponse(resp *http.Response) (KeyVaultClientGetKeysResponse, error) { + result := KeyVaultClientGetKeysResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil { + return KeyVaultClientGetKeysResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - parameters - The request object to get random bytes. +// - options - KeyVaultClientGetRandomBytesOptions contains the optional parameters for the KeyVaultClient.GetRandomBytes method. +func (client *KeyVaultClient) GetRandomBytes(ctx context.Context, parameters GetRandomBytesRequest, options *KeyVaultClientGetRandomBytesOptions) (KeyVaultClientGetRandomBytesResponse, error) { + var err error + const operationName = "KeyVaultClient.GetRandomBytes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getRandomBytesCreateRequest(ctx, parameters, options) + if err != nil { + return KeyVaultClientGetRandomBytesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientGetRandomBytesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientGetRandomBytesResponse{}, err + } + resp, err := client.getRandomBytesHandleResponse(httpResp) + return resp, err +} + +// getRandomBytesCreateRequest creates the GetRandomBytes request. +func (client *KeyVaultClient) getRandomBytesCreateRequest(ctx context.Context, parameters GetRandomBytesRequest, _ *KeyVaultClientGetRandomBytesOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/rng" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// getRandomBytesHandleResponse handles the GetRandomBytes response. +func (client *KeyVaultClient) getRandomBytesHandleResponse(resp *http.Response) (KeyVaultClientGetRandomBytesResponse, error) { + result := KeyVaultClientGetRandomBytesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RandomBytes); err != nil { + return KeyVaultClientGetRandomBytesResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - Name for the imported 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. +// - parameters - The parameters to import a key. +// - options - KeyVaultClientImportKeyOptions contains the optional parameters for the KeyVaultClient.ImportKey method. +func (client *KeyVaultClient) ImportKey(ctx context.Context, keyName string, parameters KeyImportParameters, options *KeyVaultClientImportKeyOptions) (KeyVaultClientImportKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.ImportKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.importKeyCreateRequest(ctx, keyName, parameters, options) + if err != nil { + return KeyVaultClientImportKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientImportKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientImportKeyResponse{}, err + } + resp, err := client.importKeyHandleResponse(httpResp) + return resp, err +} + +// importKeyCreateRequest creates the ImportKey request. +func (client *KeyVaultClient) importKeyCreateRequest(ctx context.Context, keyName string, parameters KeyImportParameters, _ *KeyVaultClientImportKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// importKeyHandleResponse handles the ImportKey response. +func (client *KeyVaultClient) importKeyHandleResponse(resp *http.Response) (KeyVaultClientImportKeyResponse, error) { + result := KeyVaultClientImportKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientImportKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key +// - options - KeyVaultClientPurgeDeletedKeyOptions contains the optional parameters for the KeyVaultClient.PurgeDeletedKey +// method. +func (client *KeyVaultClient) PurgeDeletedKey(ctx context.Context, keyName string, options *KeyVaultClientPurgeDeletedKeyOptions) (KeyVaultClientPurgeDeletedKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.PurgeDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.purgeDeletedKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientPurgeDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientPurgeDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientPurgeDeletedKeyResponse{}, err + } + return KeyVaultClientPurgeDeletedKeyResponse{}, nil +} + +// purgeDeletedKeyCreateRequest creates the PurgeDeletedKey request. +func (client *KeyVaultClient) purgeDeletedKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientPurgeDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/deletedkeys/{key-name}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// 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.6-preview.1 +// - keyName - The name of the deleted key. +// - options - KeyVaultClientRecoverDeletedKeyOptions contains the optional parameters for the KeyVaultClient.RecoverDeletedKey +// method. +func (client *KeyVaultClient) RecoverDeletedKey(ctx context.Context, keyName string, options *KeyVaultClientRecoverDeletedKeyOptions) (KeyVaultClientRecoverDeletedKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.RecoverDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.recoverDeletedKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientRecoverDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientRecoverDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientRecoverDeletedKeyResponse{}, err + } + resp, err := client.recoverDeletedKeyHandleResponse(httpResp) + return resp, err +} + +// recoverDeletedKeyCreateRequest creates the RecoverDeletedKey request. +func (client *KeyVaultClient) recoverDeletedKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientRecoverDeletedKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/deletedkeys/{key-name}/recover" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// recoverDeletedKeyHandleResponse handles the RecoverDeletedKey response. +func (client *KeyVaultClient) recoverDeletedKeyHandleResponse(resp *http.Response) (KeyVaultClientRecoverDeletedKeyResponse, error) { + result := KeyVaultClientRecoverDeletedKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientRecoverDeletedKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key to get. +// - keyVersion - Adding the version parameter retrieves a specific version of a key. +// - parameters - The parameters for the key release operation. +// - options - KeyVaultClientReleaseOptions contains the optional parameters for the KeyVaultClient.Release method. +func (client *KeyVaultClient) Release(ctx context.Context, keyName string, keyVersion string, parameters KeyReleaseParameters, options *KeyVaultClientReleaseOptions) (KeyVaultClientReleaseResponse, error) { + var err error + const operationName = "KeyVaultClient.Release" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.releaseCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientReleaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientReleaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientReleaseResponse{}, err + } + resp, err := client.releaseHandleResponse(httpResp) + return resp, err +} + +// releaseCreateRequest creates the Release request. +func (client *KeyVaultClient) releaseCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyReleaseParameters, _ *KeyVaultClientReleaseOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/release" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// releaseHandleResponse handles the Release response. +func (client *KeyVaultClient) releaseHandleResponse(resp *http.Response) (KeyVaultClientReleaseResponse, error) { + result := KeyVaultClientReleaseResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyReleaseResult); err != nil { + return KeyVaultClientReleaseResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - parameters - The parameters to restore the key. +// - options - KeyVaultClientRestoreKeyOptions contains the optional parameters for the KeyVaultClient.RestoreKey method. +func (client *KeyVaultClient) RestoreKey(ctx context.Context, parameters KeyRestoreParameters, options *KeyVaultClientRestoreKeyOptions) (KeyVaultClientRestoreKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.RestoreKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreKeyCreateRequest(ctx, parameters, options) + if err != nil { + return KeyVaultClientRestoreKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientRestoreKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientRestoreKeyResponse{}, err + } + resp, err := client.restoreKeyHandleResponse(httpResp) + return resp, err +} + +// restoreKeyCreateRequest creates the RestoreKey request. +func (client *KeyVaultClient) restoreKeyCreateRequest(ctx context.Context, parameters KeyRestoreParameters, _ *KeyVaultClientRestoreKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/restore" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// restoreKeyHandleResponse handles the RestoreKey response. +func (client *KeyVaultClient) restoreKeyHandleResponse(resp *http.Response) (KeyVaultClientRestoreKeyResponse, error) { + result := KeyVaultClientRestoreKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientRestoreKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of key to be rotated. The system will generate a new version in the +// specified key. +// - options - KeyVaultClientRotateKeyOptions contains the optional parameters for the KeyVaultClient.RotateKey method. +func (client *KeyVaultClient) RotateKey(ctx context.Context, keyName string, options *KeyVaultClientRotateKeyOptions) (KeyVaultClientRotateKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.RotateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rotateKeyCreateRequest(ctx, keyName, options) + if err != nil { + return KeyVaultClientRotateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientRotateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientRotateKeyResponse{}, err + } + resp, err := client.rotateKeyHandleResponse(httpResp) + return resp, err +} + +// rotateKeyCreateRequest creates the RotateKey request. +func (client *KeyVaultClient) rotateKeyCreateRequest(ctx context.Context, keyName string, _ *KeyVaultClientRotateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/rotate" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// rotateKeyHandleResponse handles the RotateKey response. +func (client *KeyVaultClient) rotateKeyHandleResponse(resp *http.Response) (KeyVaultClientRotateKeyResponse, error) { + result := KeyVaultClientRotateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientRotateKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for the signing operation. +// - options - KeyVaultClientSignOptions contains the optional parameters for the KeyVaultClient.Sign method. +func (client *KeyVaultClient) Sign(ctx context.Context, keyName string, keyVersion string, parameters KeySignParameters, options *KeyVaultClientSignOptions) (KeyVaultClientSignResponse, error) { + var err error + const operationName = "KeyVaultClient.Sign" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.signCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientSignResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientSignResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientSignResponse{}, err + } + resp, err := client.signHandleResponse(httpResp) + return resp, err +} + +// signCreateRequest creates the Sign request. +func (client *KeyVaultClient) signCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeySignParameters, _ *KeyVaultClientSignOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/sign" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// signHandleResponse handles the Sign response. +func (client *KeyVaultClient) signHandleResponse(resp *http.Response) (KeyVaultClientSignResponse, error) { + result := KeyVaultClientSignResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return KeyVaultClientSignResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for the key operation. +// - options - KeyVaultClientUnwrapKeyOptions contains the optional parameters for the KeyVaultClient.UnwrapKey method. +func (client *KeyVaultClient) UnwrapKey(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, options *KeyVaultClientUnwrapKeyOptions) (KeyVaultClientUnwrapKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.UnwrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unwrapKeyCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientUnwrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientUnwrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientUnwrapKeyResponse{}, err + } + resp, err := client.unwrapKeyHandleResponse(httpResp) + return resp, err +} + +// unwrapKeyCreateRequest creates the UnwrapKey request. +func (client *KeyVaultClient) unwrapKeyCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, _ *KeyVaultClientUnwrapKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/unwrapkey" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// unwrapKeyHandleResponse handles the UnwrapKey response. +func (client *KeyVaultClient) unwrapKeyHandleResponse(resp *http.Response) (KeyVaultClientUnwrapKeyResponse, error) { + result := KeyVaultClientUnwrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return KeyVaultClientUnwrapKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of key to update. +// - keyVersion - The version of the key to update. +// - parameters - The parameters of the key to update. +// - options - KeyVaultClientUpdateKeyOptions contains the optional parameters for the KeyVaultClient.UpdateKey method. +func (client *KeyVaultClient) UpdateKey(ctx context.Context, keyName string, keyVersion string, parameters KeyUpdateParameters, options *KeyVaultClientUpdateKeyOptions) (KeyVaultClientUpdateKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.UpdateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateKeyCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientUpdateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientUpdateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientUpdateKeyResponse{}, err + } + resp, err := client.updateKeyHandleResponse(httpResp) + return resp, err +} + +// updateKeyCreateRequest creates the UpdateKey request. +func (client *KeyVaultClient) updateKeyCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyUpdateParameters, _ *KeyVaultClientUpdateKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// updateKeyHandleResponse handles the UpdateKey response. +func (client *KeyVaultClient) updateKeyHandleResponse(resp *http.Response) (KeyVaultClientUpdateKeyResponse, error) { + result := KeyVaultClientUpdateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return KeyVaultClientUpdateKeyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key in the given vault. +// - keyRotationPolicy - The policy for the key. +// - options - KeyVaultClientUpdateKeyRotationPolicyOptions contains the optional parameters for the KeyVaultClient.UpdateKeyRotationPolicy +// method. +func (client *KeyVaultClient) UpdateKeyRotationPolicy(ctx context.Context, keyName string, keyRotationPolicy KeyRotationPolicy, options *KeyVaultClientUpdateKeyRotationPolicyOptions) (KeyVaultClientUpdateKeyRotationPolicyResponse, error) { + var err error + const operationName = "KeyVaultClient.UpdateKeyRotationPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateKeyRotationPolicyCreateRequest(ctx, keyName, keyRotationPolicy, options) + if err != nil { + return KeyVaultClientUpdateKeyRotationPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientUpdateKeyRotationPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientUpdateKeyRotationPolicyResponse{}, err + } + resp, err := client.updateKeyRotationPolicyHandleResponse(httpResp) + return resp, err +} + +// updateKeyRotationPolicyCreateRequest creates the UpdateKeyRotationPolicy request. +func (client *KeyVaultClient) updateKeyRotationPolicyCreateRequest(ctx context.Context, keyName string, keyRotationPolicy KeyRotationPolicy, _ *KeyVaultClientUpdateKeyRotationPolicyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/rotationpolicy" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// updateKeyRotationPolicyHandleResponse handles the UpdateKeyRotationPolicy response. +func (client *KeyVaultClient) updateKeyRotationPolicyHandleResponse(resp *http.Response) (KeyVaultClientUpdateKeyRotationPolicyResponse, error) { + result := KeyVaultClientUpdateKeyRotationPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyRotationPolicy); err != nil { + return KeyVaultClientUpdateKeyRotationPolicyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for verify operations. +// - options - KeyVaultClientVerifyOptions contains the optional parameters for the KeyVaultClient.Verify method. +func (client *KeyVaultClient) Verify(ctx context.Context, keyName string, keyVersion string, parameters KeyVerifyParameters, options *KeyVaultClientVerifyOptions) (KeyVaultClientVerifyResponse, error) { + var err error + const operationName = "KeyVaultClient.Verify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.verifyCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientVerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientVerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientVerifyResponse{}, err + } + resp, err := client.verifyHandleResponse(httpResp) + return resp, err +} + +// verifyCreateRequest creates the Verify request. +func (client *KeyVaultClient) verifyCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyVerifyParameters, _ *KeyVaultClientVerifyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/verify" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// verifyHandleResponse handles the Verify response. +func (client *KeyVaultClient) verifyHandleResponse(resp *http.Response) (KeyVaultClientVerifyResponse, error) { + result := KeyVaultClientVerifyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyVerifyResult); err != nil { + return KeyVaultClientVerifyResponse{}, err + } + return result, nil +} + +// 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.6-preview.1 +// - keyName - The name of the key. +// - keyVersion - The version of the key. +// - parameters - The parameters for wrap operation. +// - options - KeyVaultClientWrapKeyOptions contains the optional parameters for the KeyVaultClient.WrapKey method. +func (client *KeyVaultClient) WrapKey(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, options *KeyVaultClientWrapKeyOptions) (KeyVaultClientWrapKeyResponse, error) { + var err error + const operationName = "KeyVaultClient.WrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.wrapKeyCreateRequest(ctx, keyName, keyVersion, parameters, options) + if err != nil { + return KeyVaultClientWrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return KeyVaultClientWrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return KeyVaultClientWrapKeyResponse{}, err + } + resp, err := client.wrapKeyHandleResponse(httpResp) + return resp, err +} + +// wrapKeyCreateRequest creates the WrapKey request. +func (client *KeyVaultClient) wrapKeyCreateRequest(ctx context.Context, keyName string, keyVersion string, parameters KeyOperationsParameters, _ *KeyVaultClientWrapKeyOptions) (*policy.Request, error) { + host := "{vaultBaseUrl}" + host = strings.ReplaceAll(host, "{vaultBaseUrl}", client.vaultBaseUrl) + urlPath := "/keys/{key-name}/{key-version}/wrapkey" + if keyName == "" { + return nil, errors.New("parameter keyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(keyName)) + if keyVersion == "" { + return nil, errors.New("parameter keyVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(keyVersion)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "7.6-preview.1") + 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 + } + return req, nil +} + +// wrapKeyHandleResponse handles the WrapKey response. +func (client *KeyVaultClient) wrapKeyHandleResponse(resp *http.Response) (KeyVaultClientWrapKeyResponse, error) { + result := KeyVaultClientWrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return KeyVaultClientWrapKeyResponse{}, err + } + return result, nil +} diff --git a/packages/typespec-go/test/azkeys/zz_models.go b/packages/typespec-go/test/azkeys/zz_models.go new file mode 100644 index 000000000..9d62a8a24 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_models.go @@ -0,0 +1,448 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +import "time" + +// BackupKeyResult - The backup key result, containing the backup blob. +type BackupKeyResult struct { + // READ-ONLY; The backup blob containing the backed up key. + Value []byte +} + +// DeletedKeyBundle - A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info +type DeletedKeyBundle struct { + // The key management attributes. + Attributes *KeyAttributes + + // The Json web key. + Key *JSONWebKey + + // The url of the recovery object, used to identify and recover the deleted key. + RecoveryID *string + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; The time when the key was deleted, in UTC + DeletedDate *time.Time + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a + // certificate, then managed will be true. + Managed *bool + + // READ-ONLY; The time when the key is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time +} + +// DeletedKeyItem - The deleted key item containing the deleted key metadata and information about +// deletion. +type DeletedKeyItem struct { + // The key management attributes. + Attributes *KeyAttributes + + // Key identifier. + Kid *string + + // The url of the recovery object, used to identify and recover the deleted key. + RecoveryID *string + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; The time when the key was deleted, in UTC + DeletedDate *time.Time + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a + // certificate, then managed will be true. + Managed *bool + + // READ-ONLY; The time when the key is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time +} + +// DeletedKeyListResult - A list of keys that have been deleted in this vault. +type DeletedKeyListResult 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 key vault along with a link to the next page of + // deleted keys. + Value []*DeletedKeyItem +} + +// GetRandomBytesRequest - The get random bytes request object. +type GetRandomBytesRequest struct { + // REQUIRED; The requested number of random bytes. + Count *int32 +} + +// JSONWebKey - As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 +type JSONWebKey struct { + // Elliptic curve name. For valid values, see JsonWebKeyCurveName. + Crv *JSONWebKeyCurveName + + // RSA private exponent, or the D component of an EC private key. + D []byte + + // RSA private key parameter. + Dp []byte + + // RSA private key parameter. + Dq []byte + + // RSA public exponent. + E []byte + + // Symmetric key. + K []byte + + // Json web key operations. For more information on possible key operations, see + // JsonWebKeyOperation. + KeyOps []*string + + // Key identifier. + Kid *string + + // JsonWebKey Key Type (kty), as defined in + // https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + Kty *JSONWebKeyType + + // RSA modulus. + N []byte + + // RSA secret prime. + P []byte + + // RSA secret prime, with p < q. + Q []byte + + // RSA private key parameter. + Qi []byte + + // Protected Key, used with 'Bring Your Own Key'. + T []byte + + // X component of an EC public key. + X []byte + + // Y component of an EC public key. + Y []byte +} + +// KeyAttributes - The attributes of a key managed by the key vault service. +type KeyAttributes struct { + // Determines whether the object is enabled. + Enabled *bool + + // Expiry date in UTC. + Expires *time.Time + + // Indicates if the private key can be exported. Release policy must be provided + // when creating the first version of an exportable key. + Exportable *bool + + // Not before date in UTC. + NotBefore *time.Time + + // READ-ONLY; Creation time in UTC. + Created *time.Time + + // READ-ONLY; The underlying HSM Platform. + HsmPlatform *string + + // READ-ONLY; softDelete data retention days. Value should be >=7 and <=90 when softDelete + // enabled, otherwise 0. + 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. + RecoveryLevel *string + + // READ-ONLY; Last updated time in UTC. + Updated *time.Time +} + +// KeyBundle - A KeyBundle consisting of a WebKey plus its attributes. +type KeyBundle struct { + // The key management attributes. + Attributes *KeyAttributes + + // The Json web key. + Key *JSONWebKey + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a + // certificate, then managed will be true. + Managed *bool +} + +// KeyCreateParameters - The key create parameters. +type KeyCreateParameters struct { + // REQUIRED; The type of key to create. For valid values, see JsonWebKeyType. + Kty *JSONWebKeyType + + // Elliptic curve name. For valid values, see JsonWebKeyCurveName. + Curve *JSONWebKeyCurveName + + // The attributes of a key managed by the key vault service. + KeyAttributes *KeyAttributes + + // Json web key operations. For more information on possible key operations, see + // JsonWebKeyOperation. + KeyOps []*JSONWebKeyOperation + + // The key size in bits. For example: 2048, 3072, or 4096 for RSA. + KeySize *int32 + + // The public exponent for a RSA key. + PublicExponent *int32 + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// KeyImportParameters - The key import parameters. +type KeyImportParameters struct { + // REQUIRED; The Json web key + Key *JSONWebKey + + // Whether to import as a hardware key (HSM) or software key. + Hsm *bool + + // The key management attributes. + KeyAttributes *KeyAttributes + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// KeyItem - The key item containing key metadata. +type KeyItem struct { + // The key management attributes. + Attributes *KeyAttributes + + // Key identifier. + Kid *string + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a + // certificate, then managed will be true. + Managed *bool +} + +// KeyListResult - The key list result. +type KeyListResult struct { + // READ-ONLY; The URL to get the next set of keys. + NextLink *string + + // READ-ONLY; A response message containing a list of keys in the key vault along with a link to the next page of keys. + Value []*KeyItem +} + +// KeyOperationResult - The key operation result. +type KeyOperationResult struct { + // READ-ONLY; Additional data to authenticate but not encrypt/decrypt when using + // authenticated crypto algorithms. + AdditionalAuthenticatedData []byte + + // READ-ONLY; The tag to authenticate when performing decryption with an authenticated + // algorithm. + AuthenticationTag []byte + + // READ-ONLY; Cryptographically random, non-repeating initialization vector for symmetric + // algorithms. + Iv []byte + + // READ-ONLY; Key identifier + Kid *string + + // READ-ONLY; The result of the operation. + Result []byte +} + +// KeyOperationsParameters - The key operations parameters. +type KeyOperationsParameters struct { + // REQUIRED; algorithm identifier + Algorithm *JSONWebKeyEncryptionAlgorithm + + // REQUIRED; The value to operate on. + Value []byte + + // Additional data to authenticate but not encrypt/decrypt when using + // authenticated crypto algorithms. + AAD []byte + + // Cryptographically random, non-repeating initialization vector for symmetric + // algorithms. + Iv []byte + + // The tag to authenticate when performing decryption with an authenticated + // algorithm. + Tag []byte +} + +// KeyReleaseParameters - The release key parameters. +type KeyReleaseParameters struct { + // REQUIRED; The attestation assertion for the target of the key release. + TargetAttestationToken *string + + // The encryption algorithm to use to protected the exported key material + Enc *KeyEncryptionAlgorithm + + // A client provided nonce for freshness. + Nonce *string +} + +// KeyReleasePolicy - The policy rules under which the key can be exported. +type KeyReleasePolicy struct { + // Content type and version of key release policy + ContentType *string + + // Blob encoding the policy rules under which the key can be released. Blob must + // be base64 URL encoded. + EncodedPolicy []byte + + // Defines the mutability state of the policy. Once marked immutable, this flag + // cannot be reset and the policy cannot be changed under any circumstances. + Immutable *bool +} + +// KeyReleaseResult - The release result, containing the released key. +type KeyReleaseResult struct { + // READ-ONLY; A signed object containing the released key. + Value *string +} + +// KeyRestoreParameters - The key restore parameters. +type KeyRestoreParameters struct { + // REQUIRED; The backup blob associated with a key bundle. + KeyBundleBackup []byte +} + +// KeyRotationPolicy - Management policy for a key. +type KeyRotationPolicy struct { + // The key rotation policy attributes. + 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. + LifetimeActions []*LifetimeActions + + // READ-ONLY; The key policy id. + ID *string +} + +// KeyRotationPolicyAttributes - The key rotation policy attributes. +type KeyRotationPolicyAttributes struct { + // The expiryTime will be applied on the new key version. It should be at least 28 + // days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 + // hours: PT48H, 1 year and 10 days: P1Y10D + ExpiryTime *string + + // READ-ONLY; The key rotation policy created time in UTC. + Created *time.Time + + // READ-ONLY; The key rotation policy's last updated time in UTC. + Updated *time.Time +} + +// KeySignParameters - The key operations parameters. +type KeySignParameters struct { + // REQUIRED; The signing/verification algorithm identifier. For more information on possible + // algorithm types, see JsonWebKeySignatureAlgorithm. + Algorithm *JSONWebKeySignatureAlgorithm + + // REQUIRED; The value to operate on. + Value []byte +} + +// KeyUpdateParameters - The key update parameters. +type KeyUpdateParameters struct { + // The attributes of a key managed by the key vault service. + KeyAttributes *KeyAttributes + + // Json web key operations. For more information on possible key operations, see + // JsonWebKeyOperation. + KeyOps []*JSONWebKeyOperation + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// KeyVerifyParameters - The key verify parameters. +type KeyVerifyParameters struct { + // REQUIRED; The signing/verification algorithm. For more information on possible algorithm + // types, see JsonWebKeySignatureAlgorithm. + Algorithm *JSONWebKeySignatureAlgorithm + + // REQUIRED; The digest used for signing. + Digest []byte + + // REQUIRED; The signature to be verified. + Signature []byte +} + +// KeyVerifyResult - The key verify result. +type KeyVerifyResult struct { + // READ-ONLY; True if the signature is verified, otherwise false. + Value *bool +} + +// LifetimeActions - Action and its trigger that will be performed by Key Vault over the lifetime of +// a key. +type LifetimeActions struct { + // The action that will be executed. + Action *LifetimeActionsType + + // The condition that will execute the action. + Trigger *LifetimeActionsTrigger +} + +// LifetimeActionsTrigger - A condition to be satisfied for an action to be executed. +type LifetimeActionsTrigger struct { + // Time after creation to attempt to rotate. It only applies to rotate. It will be + // in ISO 8601 duration format. Example: 90 days : "P90D" + TimeAfterCreate *string + + // Time before expiry to attempt to rotate or notify. It will be in ISO 8601 + // duration format. Example: 90 days : "P90D" + TimeBeforeExpiry *string +} + +// LifetimeActionsType - The action that will be executed. +type LifetimeActionsType struct { + // The type of the action. The value should be compared case-insensitively. + Type *KeyRotationPolicyAction +} + +// RandomBytes - The get random bytes response object containing the bytes. +type RandomBytes struct { + // REQUIRED; The bytes encoded as a base64url string. + Value []byte +} diff --git a/packages/typespec-go/test/azkeys/zz_models_serde.go b/packages/typespec-go/test/azkeys/zz_models_serde.go new file mode 100644 index 000000000..8638f3ce2 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_models_serde.go @@ -0,0 +1,1227 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type BackupKeyResult. +func (b BackupKeyResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, func() any { + return runtime.EncodeByteArray(b.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupKeyResult. +func (b *BackupKeyResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKeyBundle. +func (d DeletedKeyBundle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populateTimeUnix(objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "key", d.Key) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populate(objectMap, "release_policy", d.ReleasePolicy) + populateTimeUnix(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKeyBundle. +func (d *DeletedKeyBundle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTimeUnix(val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &d.Key) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &d.ReleasePolicy) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeUnix(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKeyItem. +func (d DeletedKeyItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populateTimeUnix(objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "kid", d.Kid) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populateTimeUnix(objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKeyItem. +func (d *DeletedKeyItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTimeUnix(val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &d.Kid) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTimeUnix(val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKeyListResult. +func (d DeletedKeyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKeyListResult. +func (d *DeletedKeyListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetRandomBytesRequest. +func (g GetRandomBytesRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", g.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetRandomBytesRequest. +func (g *GetRandomBytesRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &g.Count) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JSONWebKey. +func (j JSONWebKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "crv", j.Crv) + 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, "key_ops", j.KeyOps) + populate(objectMap, "kid", j.Kid) + populate(objectMap, "kty", j.Kty) + 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) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JSONWebKey. +func (j *JSONWebKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "crv": + err = unpopulate(val, "Crv", &j.Crv) + delete(rawMsg, key) + case "d": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.D, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "dp": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Dp, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "dq": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Dq, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "e": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.E, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "k": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.K, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &j.KeyOps) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &j.Kid) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &j.Kty) + delete(rawMsg, key) + case "n": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.N, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "p": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.P, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "q": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Q, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "qi": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Qi, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "key_hsm": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.T, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "x": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.X, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "y": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Y, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyAttributes. +func (k KeyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeUnix(objectMap, "created", k.Created) + populate(objectMap, "enabled", k.Enabled) + populateTimeUnix(objectMap, "exp", k.Expires) + populate(objectMap, "exportable", k.Exportable) + populate(objectMap, "hsmPlatform", k.HsmPlatform) + populateTimeUnix(objectMap, "nbf", k.NotBefore) + populate(objectMap, "recoverableDays", k.RecoverableDays) + populate(objectMap, "recoveryLevel", k.RecoveryLevel) + populateTimeUnix(objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyAttributes. +func (k *KeyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulateTimeUnix(val, "Created", &k.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &k.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulateTimeUnix(val, "Expires", &k.Expires) + delete(rawMsg, key) + case "exportable": + err = unpopulate(val, "Exportable", &k.Exportable) + delete(rawMsg, key) + case "hsmPlatform": + err = unpopulate(val, "HsmPlatform", &k.HsmPlatform) + delete(rawMsg, key) + case "nbf": + err = unpopulateTimeUnix(val, "NotBefore", &k.NotBefore) + delete(rawMsg, key) + case "recoverableDays": + err = unpopulate(val, "RecoverableDays", &k.RecoverableDays) + delete(rawMsg, key) + case "recoveryLevel": + err = unpopulate(val, "RecoveryLevel", &k.RecoveryLevel) + delete(rawMsg, key) + case "updated": + err = unpopulateTimeUnix(val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyBundle. +func (k KeyBundle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "key", k.Key) + populate(objectMap, "managed", k.Managed) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyBundle. +func (k *KeyBundle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &k.Key) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &k.Managed) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyCreateParameters. +func (k KeyCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "crv", k.Curve) + populate(objectMap, "attributes", k.KeyAttributes) + populate(objectMap, "key_ops", k.KeyOps) + populate(objectMap, "key_size", k.KeySize) + populate(objectMap, "kty", k.Kty) + populate(objectMap, "public_exponent", k.PublicExponent) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyCreateParameters. +func (k *KeyCreateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "crv": + err = unpopulate(val, "Curve", &k.Curve) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "KeyAttributes", &k.KeyAttributes) + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &k.KeyOps) + delete(rawMsg, key) + case "key_size": + err = unpopulate(val, "KeySize", &k.KeySize) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &k.Kty) + delete(rawMsg, key) + case "public_exponent": + err = unpopulate(val, "PublicExponent", &k.PublicExponent) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyImportParameters. +func (k KeyImportParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "Hsm", k.Hsm) + populate(objectMap, "key", k.Key) + populate(objectMap, "attributes", k.KeyAttributes) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyImportParameters. +func (k *KeyImportParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "Hsm": + err = unpopulate(val, "Hsm", &k.Hsm) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &k.Key) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "KeyAttributes", &k.KeyAttributes) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyItem. +func (k KeyItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "kid", k.Kid) + populate(objectMap, "managed", k.Managed) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyItem. +func (k *KeyItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &k.Kid) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &k.Managed) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyListResult. +func (k KeyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", k.NextLink) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyListResult. +func (k *KeyListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &k.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// 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, 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, func() any { + return runtime.EncodeByteArray(k.Result, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyOperationResult. +func (k *KeyOperationResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aad": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "tag": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "iv": + 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": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Result, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyOperationsParameters. +func (k KeyOperationsParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "aad", k.AAD, func() any { + return runtime.EncodeByteArray(k.AAD, runtime.Base64URLFormat) + }) + populate(objectMap, "alg", k.Algorithm) + populateByteArray(objectMap, "iv", k.Iv, func() any { + return runtime.EncodeByteArray(k.Iv, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "tag", k.Tag, func() any { + return runtime.EncodeByteArray(k.Tag, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", k.Value, func() any { + return runtime.EncodeByteArray(k.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyOperationsParameters. +func (k *KeyOperationsParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aad": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AAD, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "alg": + err = unpopulate(val, "Algorithm", &k.Algorithm) + delete(rawMsg, key) + case "iv": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Iv, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "tag": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Tag, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleaseParameters. +func (k KeyReleaseParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enc", k.Enc) + populate(objectMap, "nonce", k.Nonce) + populate(objectMap, "target", k.TargetAttestationToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleaseParameters. +func (k *KeyReleaseParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enc": + err = unpopulate(val, "Enc", &k.Enc) + delete(rawMsg, key) + case "nonce": + err = unpopulate(val, "Nonce", &k.Nonce) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "TargetAttestationToken", &k.TargetAttestationToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleasePolicy. +func (k KeyReleasePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", k.ContentType) + populateByteArray(objectMap, "data", k.EncodedPolicy, func() any { + return runtime.EncodeByteArray(k.EncodedPolicy, runtime.Base64URLFormat) + }) + populate(objectMap, "immutable", k.Immutable) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleasePolicy. +func (k *KeyReleasePolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &k.ContentType) + delete(rawMsg, key) + case "data": + 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) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleaseResult. +func (k KeyReleaseResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleaseResult. +func (k *KeyReleaseResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRestoreParameters. +func (k KeyRestoreParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", k.KeyBundleBackup, func() any { + return runtime.EncodeByteArray(k.KeyBundleBackup, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRestoreParameters. +func (k *KeyRestoreParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.KeyBundleBackup, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRotationPolicy. +func (k KeyRotationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "id", k.ID) + populate(objectMap, "lifetimeActions", k.LifetimeActions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRotationPolicy. +func (k *KeyRotationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &k.ID) + delete(rawMsg, key) + case "lifetimeActions": + err = unpopulate(val, "LifetimeActions", &k.LifetimeActions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRotationPolicyAttributes. +func (k KeyRotationPolicyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTimeUnix(objectMap, "created", k.Created) + populate(objectMap, "expiryTime", k.ExpiryTime) + populateTimeUnix(objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRotationPolicyAttributes. +func (k *KeyRotationPolicyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulateTimeUnix(val, "Created", &k.Created) + delete(rawMsg, key) + case "expiryTime": + err = unpopulate(val, "ExpiryTime", &k.ExpiryTime) + delete(rawMsg, key) + case "updated": + err = unpopulateTimeUnix(val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeySignParameters. +func (k KeySignParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", k.Algorithm) + populateByteArray(objectMap, "value", k.Value, func() any { + return runtime.EncodeByteArray(k.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeySignParameters. +func (k *KeySignParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &k.Algorithm) + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyUpdateParameters. +func (k KeyUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.KeyAttributes) + populate(objectMap, "key_ops", k.KeyOps) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyUpdateParameters. +func (k *KeyUpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "KeyAttributes", &k.KeyAttributes) + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &k.KeyOps) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVerifyParameters. +func (k KeyVerifyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", k.Algorithm) + populateByteArray(objectMap, "digest", k.Digest, func() any { + return runtime.EncodeByteArray(k.Digest, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", k.Signature, func() any { + return runtime.EncodeByteArray(k.Signature, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVerifyParameters. +func (k *KeyVerifyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &k.Algorithm) + delete(rawMsg, key) + case "digest": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Digest, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Signature, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVerifyResult. +func (k KeyVerifyResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVerifyResult. +func (k *KeyVerifyResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeActions. +func (l LifetimeActions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", l.Action) + populate(objectMap, "trigger", l.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeActions. +func (l *LifetimeActions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &l.Action) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &l.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeActionsTrigger. +func (l LifetimeActionsTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "timeAfterCreate", l.TimeAfterCreate) + populate(objectMap, "timeBeforeExpiry", l.TimeBeforeExpiry) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeActionsTrigger. +func (l *LifetimeActionsTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "timeAfterCreate": + err = unpopulate(val, "TimeAfterCreate", &l.TimeAfterCreate) + delete(rawMsg, key) + case "timeBeforeExpiry": + err = unpopulate(val, "TimeBeforeExpiry", &l.TimeBeforeExpiry) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeActionsType. +func (l LifetimeActionsType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeActionsType. +func (l *LifetimeActionsType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// 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, func() any { + return runtime.EncodeByteArray(r.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RandomBytes. +func (r *RandomBytes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &r.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateByteArray[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] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/packages/typespec-go/test/azkeys/zz_options.go b/packages/typespec-go/test/azkeys/zz_options.go new file mode 100644 index 000000000..f6a2b0a10 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_options.go @@ -0,0 +1,133 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +// KeyVaultClientBackupKeyOptions contains the optional parameters for the KeyVaultClient.BackupKey method. +type KeyVaultClientBackupKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientCreateKeyOptions contains the optional parameters for the KeyVaultClient.CreateKey method. +type KeyVaultClientCreateKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientDecryptOptions contains the optional parameters for the KeyVaultClient.Decrypt method. +type KeyVaultClientDecryptOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientDeleteKeyOptions contains the optional parameters for the KeyVaultClient.DeleteKey method. +type KeyVaultClientDeleteKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientEncryptOptions contains the optional parameters for the KeyVaultClient.Encrypt method. +type KeyVaultClientEncryptOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientGetDeletedKeyOptions contains the optional parameters for the KeyVaultClient.GetDeletedKey method. +type KeyVaultClientGetDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientGetDeletedKeysOptions contains the optional parameters for the KeyVaultClient.NewGetDeletedKeysPager method. +type KeyVaultClientGetDeletedKeysOptions struct { + // Maximum number of results to return in a page. If not specified the service + // will return up to 25 results. + Maxresults *int32 +} + +// KeyVaultClientGetKeyOptions contains the optional parameters for the KeyVaultClient.GetKey method. +type KeyVaultClientGetKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientGetKeyRotationPolicyOptions contains the optional parameters for the KeyVaultClient.GetKeyRotationPolicy +// method. +type KeyVaultClientGetKeyRotationPolicyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientGetKeyVersionsOptions contains the optional parameters for the KeyVaultClient.NewGetKeyVersionsPager method. +type KeyVaultClientGetKeyVersionsOptions struct { + // Maximum number of results to return in a page. If not specified the service + // will return up to 25 results. + Maxresults *int32 +} + +// KeyVaultClientGetKeysOptions contains the optional parameters for the KeyVaultClient.NewGetKeysPager method. +type KeyVaultClientGetKeysOptions struct { + // Maximum number of results to return in a page. If not specified the service + // will return up to 25 results. + Maxresults *int32 +} + +// KeyVaultClientGetRandomBytesOptions contains the optional parameters for the KeyVaultClient.GetRandomBytes method. +type KeyVaultClientGetRandomBytesOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientImportKeyOptions contains the optional parameters for the KeyVaultClient.ImportKey method. +type KeyVaultClientImportKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientPurgeDeletedKeyOptions contains the optional parameters for the KeyVaultClient.PurgeDeletedKey method. +type KeyVaultClientPurgeDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientRecoverDeletedKeyOptions contains the optional parameters for the KeyVaultClient.RecoverDeletedKey method. +type KeyVaultClientRecoverDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientReleaseOptions contains the optional parameters for the KeyVaultClient.Release method. +type KeyVaultClientReleaseOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientRestoreKeyOptions contains the optional parameters for the KeyVaultClient.RestoreKey method. +type KeyVaultClientRestoreKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientRotateKeyOptions contains the optional parameters for the KeyVaultClient.RotateKey method. +type KeyVaultClientRotateKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientSignOptions contains the optional parameters for the KeyVaultClient.Sign method. +type KeyVaultClientSignOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientUnwrapKeyOptions contains the optional parameters for the KeyVaultClient.UnwrapKey method. +type KeyVaultClientUnwrapKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientUpdateKeyOptions contains the optional parameters for the KeyVaultClient.UpdateKey method. +type KeyVaultClientUpdateKeyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientUpdateKeyRotationPolicyOptions contains the optional parameters for the KeyVaultClient.UpdateKeyRotationPolicy +// method. +type KeyVaultClientUpdateKeyRotationPolicyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientVerifyOptions contains the optional parameters for the KeyVaultClient.Verify method. +type KeyVaultClientVerifyOptions struct { + // placeholder for future optional parameters +} + +// KeyVaultClientWrapKeyOptions contains the optional parameters for the KeyVaultClient.WrapKey method. +type KeyVaultClientWrapKeyOptions struct { + // placeholder for future optional parameters +} diff --git a/packages/typespec-go/test/azkeys/zz_responses.go b/packages/typespec-go/test/azkeys/zz_responses.go new file mode 100644 index 000000000..c5ee8fdaf --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_responses.go @@ -0,0 +1,148 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +// KeyVaultClientBackupKeyResponse contains the response from method KeyVaultClient.BackupKey. +type KeyVaultClientBackupKeyResponse struct { + // The backup key result, containing the backup blob. + BackupKeyResult +} + +// KeyVaultClientCreateKeyResponse contains the response from method KeyVaultClient.CreateKey. +type KeyVaultClientCreateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientDecryptResponse contains the response from method KeyVaultClient.Decrypt. +type KeyVaultClientDecryptResponse struct { + // The key operation result. + KeyOperationResult +} + +// KeyVaultClientDeleteKeyResponse contains the response from method KeyVaultClient.DeleteKey. +type KeyVaultClientDeleteKeyResponse struct { + // A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info + DeletedKeyBundle +} + +// KeyVaultClientEncryptResponse contains the response from method KeyVaultClient.Encrypt. +type KeyVaultClientEncryptResponse struct { + // The key operation result. + KeyOperationResult +} + +// KeyVaultClientGetDeletedKeyResponse contains the response from method KeyVaultClient.GetDeletedKey. +type KeyVaultClientGetDeletedKeyResponse struct { + // A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info + DeletedKeyBundle +} + +// KeyVaultClientGetDeletedKeysResponse contains the response from method KeyVaultClient.NewGetDeletedKeysPager. +type KeyVaultClientGetDeletedKeysResponse struct { + // A list of keys that have been deleted in this vault. + DeletedKeyListResult +} + +// KeyVaultClientGetKeyResponse contains the response from method KeyVaultClient.GetKey. +type KeyVaultClientGetKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientGetKeyRotationPolicyResponse contains the response from method KeyVaultClient.GetKeyRotationPolicy. +type KeyVaultClientGetKeyRotationPolicyResponse struct { + // Management policy for a key. + KeyRotationPolicy +} + +// KeyVaultClientGetKeyVersionsResponse contains the response from method KeyVaultClient.NewGetKeyVersionsPager. +type KeyVaultClientGetKeyVersionsResponse struct { + // The key list result. + KeyListResult +} + +// KeyVaultClientGetKeysResponse contains the response from method KeyVaultClient.NewGetKeysPager. +type KeyVaultClientGetKeysResponse struct { + // The key list result. + KeyListResult +} + +// KeyVaultClientGetRandomBytesResponse contains the response from method KeyVaultClient.GetRandomBytes. +type KeyVaultClientGetRandomBytesResponse struct { + // The get random bytes response object containing the bytes. + RandomBytes +} + +// KeyVaultClientImportKeyResponse contains the response from method KeyVaultClient.ImportKey. +type KeyVaultClientImportKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientPurgeDeletedKeyResponse contains the response from method KeyVaultClient.PurgeDeletedKey. +type KeyVaultClientPurgeDeletedKeyResponse struct { + // placeholder for future response values +} + +// KeyVaultClientRecoverDeletedKeyResponse contains the response from method KeyVaultClient.RecoverDeletedKey. +type KeyVaultClientRecoverDeletedKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientReleaseResponse contains the response from method KeyVaultClient.Release. +type KeyVaultClientReleaseResponse struct { + // The release result, containing the released key. + KeyReleaseResult +} + +// KeyVaultClientRestoreKeyResponse contains the response from method KeyVaultClient.RestoreKey. +type KeyVaultClientRestoreKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientRotateKeyResponse contains the response from method KeyVaultClient.RotateKey. +type KeyVaultClientRotateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientSignResponse contains the response from method KeyVaultClient.Sign. +type KeyVaultClientSignResponse struct { + // The key operation result. + KeyOperationResult +} + +// KeyVaultClientUnwrapKeyResponse contains the response from method KeyVaultClient.UnwrapKey. +type KeyVaultClientUnwrapKeyResponse struct { + // The key operation result. + KeyOperationResult +} + +// KeyVaultClientUpdateKeyResponse contains the response from method KeyVaultClient.UpdateKey. +type KeyVaultClientUpdateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// KeyVaultClientUpdateKeyRotationPolicyResponse contains the response from method KeyVaultClient.UpdateKeyRotationPolicy. +type KeyVaultClientUpdateKeyRotationPolicyResponse struct { + // Management policy for a key. + KeyRotationPolicy +} + +// KeyVaultClientVerifyResponse contains the response from method KeyVaultClient.Verify. +type KeyVaultClientVerifyResponse struct { + // The key verify result. + KeyVerifyResult +} + +// KeyVaultClientWrapKeyResponse contains the response from method KeyVaultClient.WrapKey. +type KeyVaultClientWrapKeyResponse struct { + // The key operation result. + KeyOperationResult +} diff --git a/packages/typespec-go/test/azkeys/zz_time_unix.go b/packages/typespec-go/test/azkeys/zz_time_unix.go new file mode 100644 index 000000000..c46295ba9 --- /dev/null +++ b/packages/typespec-go/test/azkeys/zz_time_unix.go @@ -0,0 +1,56 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package azkeys + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "time" +) + +type timeUnix time.Time + +func (t timeUnix) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Time(t).Unix()) +} + +func (t *timeUnix) UnmarshalJSON(data []byte) error { + var seconds int64 + if err := json.Unmarshal(data, &seconds); err != nil { + return err + } + *t = timeUnix(time.Unix(seconds, 0)) + return nil +} + +func (t timeUnix) String() string { + return fmt.Sprintf("%d", time.Time(t).Unix()) +} + +func populateTimeUnix(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeUnix)(t) +} + +func unpopulateTimeUnix(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux timeUnix + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/packages/typespec-go/test/tsp/KeyVault.Keys/client.tsp b/packages/typespec-go/test/tsp/KeyVault.Keys/client.tsp new file mode 100644 index 000000000..8dda18302 --- /dev/null +++ b/packages/typespec-go/test/tsp/KeyVault.Keys/client.tsp @@ -0,0 +1,54 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(KeyVault, "Client", "go"); + +using KeyVault; + +@@clientName(KeyCreateParameters, "CreateKeyParameters", "go"); +@@clientName(KeyExportParameters, "ExportKeyParameters", "go"); +@@clientName(KeyImportParameters, "ImportKeyParameters", "go"); +@@clientName(KeyReleaseParameters, "ReleaseParameters", "go"); +@@clientName(KeyRestoreParameters, "RestoreKeyParameters", "go"); +@@clientName(KeySignParameters, "SignParameters", "go"); +@@clientName(KeyUpdateParameters, "UpdateKeyParameters", "go"); +@@clientName(KeyVerifyParameters, "VerifyParameters", "go"); +@@clientName(GetRandomBytesRequest, "GetRandomBytesParameters", "go"); +@@clientName(getDeletedKeys, "ListDeletedKeyProperties", "go"); +@@clientName(getKeys, "ListKeyProperties", "go"); +@@clientName(getKeyVersions, "ListKeyPropertiesVersions", "go"); +@@clientName(DeletedKeyBundle, "DeletedKey", "go"); +@@clientName(KeyProperties, "KeyP", "go"); +@@clientName(KeyItem, "KeyProperties", "go"); +@@clientName(DeletedKeyItem, "DeletedKeyProperties", "go"); +@@clientName(DeletedKeyListResult, "DeletedKeyPropertiesListResult", "go"); +@@clientName(KeyListResult, "KeyPropertiesListResult", "go"); +@@clientName(LifetimeActions, "LifetimeAction", "go"); +@@clientName(LifetimeActionsType, "LifetimeActionType", "go"); +@@clientName(LifetimeActionsTrigger, "LifetimeActionTrigger", "go"); +@@clientName(KeyAttributes.hsmPlatform, "HSMPlatform", "go"); +@@clientName(KeyRestoreParameters.keyBundleBackup, "KeyBackup", "go"); +@@clientName(KeyOperationsParameters, "KeyOperationParameters", "go"); + +@@clientName(KeyImportParameters.hsm, "HSM", "go"); +@@clientName(KeyReleaseParameters.enc, "algorithm", "go"); +@@clientName(KeyOperationsParameters.aad, "AdditionalAuthenticatedData", "go"); +@@clientName(KeyOperationsParameters.tag, "AuthenticationTag", "go"); + +@@clientName(JsonWebKeyType, "KeyType", "go"); +@@clientName(JsonWebKeyOperation, "KeyOperation", "go"); +@@clientName(JsonWebKeyEncryptionAlgorithm, "EncryptionAlgorithm", "go"); +@@clientName(JsonWebKeyCurveName, "CurveName", "go"); +@@clientName(JsonWebKeySignatureAlgorithm, "SignatureAlgorithm", "go"); + +@@clientName(JsonWebKey.kid, "KID", "go"); +@@clientName(KeyItem.kid, "KID", "go"); +@@clientName(KeyOperationResult.kid, "KID", "go"); +@@clientName(KeyOperationsParameters.iv, "IV", "go"); +@@clientName(KeyOperationResult.iv, "IV", "go"); + +@@clientName(JsonWebKey.dp, "DP", "go"); +@@clientName(JsonWebKey.dq, "DQ", "go"); +@@clientName(JsonWebKey.qi, "QI", "go"); diff --git a/packages/typespec-go/test/tsp/KeyVault.Keys/main.tsp b/packages/typespec-go/test/tsp/KeyVault.Keys/main.tsp new file mode 100644 index 000000000..b84a7f99e --- /dev/null +++ b/packages/typespec-go/test/tsp/KeyVault.Keys/main.tsp @@ -0,0 +1,53 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "./routes.tsp"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using TypeSpec.Versioning; +using Azure.Core; + +/** + * The key vault client performs cryptographic key operations and vault operations + * against the Key Vault service. + */ +@useAuth( + OAuth2Auth<[ + { + type: OAuth2FlowType.implicit, + authorizationUrl: "https://login.microsoftonline.com/common/oauth2/authorize", + scopes: ["https://vault.azure.net/.default"], + } + ]> +) +@service({ + title: "KeyVaultClient", +}) +@versioned(Versions) +@server( + "{vaultBaseUrl}", + "The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", + { + vaultBaseUrl: url, + } +) +namespace KeyVault; + +/** + * The available API versions. + */ +enum Versions { + /** + * The 7.5 API version. + */ + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + `v7.5`: "7.5", + + /** + * The 7.6-preview.1 API version. + */ + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + `v7.6_preview.1`: "7.6-preview.1", +} diff --git a/packages/typespec-go/test/tsp/KeyVault.Keys/models.tsp b/packages/typespec-go/test/tsp/KeyVault.Keys/models.tsp new file mode 100644 index 000000000..6c5ad8c94 --- /dev/null +++ b/packages/typespec-go/test/tsp/KeyVault.Keys/models.tsp @@ -0,0 +1,1215 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using Azure.Core; + +namespace KeyVault; + +/** + * JsonWebKey Key Type (kty), as defined in + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + */ +union JsonWebKeyType { + string, + + /** + * Elliptic Curve. + */ + EC: "EC", + + /** + * Elliptic Curve with a private key which is stored in the HSM. + */ + EC_HSM: "EC-HSM", + + /** + * RSA (https://tools.ietf.org/html/rfc3447) + */ + RSA: "RSA", + + /** + * RSA with a private key which is stored in the HSM. + */ + RSA_HSM: "RSA-HSM", + + /** + * Octet sequence (used to represent symmetric keys) + */ + oct: "oct", + + /** + * Octet sequence (used to represent symmetric keys) which is stored the HSM. + */ + oct_HSM: "oct-HSM", +} + +/** + * JSON web key operations. For more information, see JsonWebKeyOperation. + */ +union JsonWebKeyOperation { + string, + + /** Indicates that the key can be used to encrypt. */ + encrypt: "encrypt", + + /** Indicates that the key can be used to decrypt. */ + decrypt: "decrypt", + + /** Indicates that the key can be used to sign. */ + sign: "sign", + + /** Indicates that the key can be used to verify. */ + verify: "verify", + + /** Indicates that the key can be used to wrap another key. */ + wrapKey: "wrapKey", + + /** Indicates that the key can be used to unwrap another key. */ + unwrapKey: "unwrapKey", + + /** Indicates that the key can be imported during creation. */ + `import`: "import", + + /** Indicates that the private component of the key can be exported. */ + export: "export", +} + +/** + * Reflects the deletion recovery level currently in effect for certificates in + * the current vault. If it contains 'Purgeable', the certificate can be + * permanently deleted by a privileged user; otherwise, only the system can purge + * the certificate, at the end of the retention interval. + */ +union DeletionRecoveryLevel { + string, + + /** + * Denotes a vault state in which deletion is an irreversible operation, without + * the possibility for recovery. This level corresponds to no protection being + * available against a Delete operation; the data is irretrievably lost upon + * accepting a Delete operation at the entity level or higher (vault, resource + * group, subscription etc.) + */ + Purgeable: "Purgeable", + + /** + * Denotes a vault state in which deletion is recoverable, and which also permits + * immediate and permanent deletion (i.e. purge). This level guarantees the + * recoverability of the deleted entity during the retention interval (90 days), + * unless a Purge operation is requested, or the subscription is cancelled. System + * wil permanently delete it after 90 days, if not recovered + */ + Recoverable_Purgeable: "Recoverable+Purgeable", + + /** + * Denotes a vault state in which deletion is recoverable without the possibility + * for immediate and permanent deletion (i.e. purge). This level guarantees the + * recoverability of the deleted entity during the retention interval(90 days) and + * while the subscription is still available. System wil permanently delete it + * after 90 days, if not recovered + */ + Recoverable: "Recoverable", + + /** + * Denotes a vault and subscription state in which deletion is recoverable within + * retention interval (90 days), immediate and permanent deletion (i.e. purge) is + * not permitted, and in which the subscription itself cannot be permanently + * canceled. System wil permanently delete it after 90 days, if not recovered + */ + Recoverable_ProtectedSubscription: "Recoverable+ProtectedSubscription", + + /** + * Denotes a vault state in which deletion is recoverable, and which also permits + * immediate and permanent deletion (i.e. purge when 7<= SoftDeleteRetentionInDays + * < 90). This level guarantees the recoverability of the deleted entity during + * the retention interval, unless a Purge operation is requested, or the + * subscription is cancelled. + */ + CustomizedRecoverable_Purgeable: "CustomizedRecoverable+Purgeable", + + /** + * Denotes a vault state in which deletion is recoverable without the possibility + * for immediate and permanent deletion (i.e. purge when 7<= + * SoftDeleteRetentionInDays < 90).This level guarantees the recoverability of the + * deleted entity during the retention interval and while the subscription is + * still available. + */ + CustomizedRecoverable: "CustomizedRecoverable", + + /** + * Denotes a vault and subscription state in which deletion is recoverable, + * immediate and permanent deletion (i.e. purge) is not permitted, and in which + * the subscription itself cannot be permanently canceled when 7<= + * SoftDeleteRetentionInDays < 90. This level guarantees the recoverability of the + * deleted entity during the retention interval, and also reflects the fact that + * the subscription itself cannot be cancelled. + */ + CustomizedRecoverable_ProtectedSubscription: "CustomizedRecoverable+ProtectedSubscription", +} + +/** + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. + */ +union JsonWebKeyCurveName { + string, + + /** The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. */ + P256: "P-256", + + /** The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. */ + P384: "P-384", + + /** The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. */ + P521: "P-521", + + /** The SECG SECP256K1 elliptic curve. */ + P256_K: "P-256K", +} + +/** + * An algorithm used for encryption and decryption. + */ +union JsonWebKeyEncryptionAlgorithm { + string, + + /** + * 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. + */ + RSA_OAEP: "RSA-OAEP", + + /** RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 + * and a mask generation function of MGF1 with SHA-256. + */ + RSA_OAEP256: "RSA-OAEP-256", + + /** RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. */ + RSA1_5: "RSA1_5", + + /** 128-bit AES-GCM. */ + A128_GCM: "A128GCM", + + /** 192-bit AES-GCM. */ + A192_GCM: "A192GCM", + + /** 256-bit AES-GCM. */ + A256_GCM: "A256GCM", + + /** 128-bit AES key wrap. */ + A128_KW: "A128KW", + + /** 192-bit AES key wrap. */ + A192_KW: "A192KW", + + /** 256-bit AES key wrap. */ + A256_KW: "A256KW", + + /** 128-bit AES-CBC. */ + A128_CBC: "A128CBC", + + /** 192-bit AES-CBC. */ + A192_CBC: "A192CBC", + + /** 256-bit AES-CBC. */ + A256_CBC: "A256CBC", + + /** 128-bit AES-CBC with PKCS padding. */ + A128_CBCPAD: "A128CBCPAD", + + /** 192-bit AES-CBC with PKCS padding. */ + A192_CBCPAD: "A192CBCPAD", + + /** 256-bit AES-CBC with PKCS padding. */ + A256_CBCPAD: "A256CBCPAD", + + /** CKM AES key wrap. */ + @added(KeyVault.Versions.`v7.6_preview.1`) + CKM_AES_KEY_WRAP: "CKM_AES_KEY_WRAP", + + /** CKM AES key wrap with padding. */ + @added(KeyVault.Versions.`v7.6_preview.1`) + CKM_AES_KEY_WRAP_PAD: "CKM_AES_KEY_WRAP_PAD", +} + +/** + * The signing/verification algorithm identifier. For more information on possible + * algorithm types, see JsonWebKeySignatureAlgorithm. + */ +union JsonWebKeySignatureAlgorithm { + string, + + /** + * RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in + * https://tools.ietf.org/html/rfc7518 + */ + PS256: "PS256", + + /** + * RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in + * https://tools.ietf.org/html/rfc7518 + */ + PS384: "PS384", + + /** + * RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in + * https://tools.ietf.org/html/rfc7518 + */ + PS512: "PS512", + + /** + * RSASSA-PKCS1-v1_5 using SHA-256, as described in + * https://tools.ietf.org/html/rfc7518 + */ + RS256: "RS256", + + /** + * RSASSA-PKCS1-v1_5 using SHA-384, as described in + * https://tools.ietf.org/html/rfc7518 + */ + RS384: "RS384", + + /** + * RSASSA-PKCS1-v1_5 using SHA-512, as described in + * https://tools.ietf.org/html/rfc7518 + */ + RS512: "RS512", + + /** + * Reserved + */ + RSNULL: "RSNULL", + + /** + * ECDSA using P-256 and SHA-256, as described in + * https://tools.ietf.org/html/rfc7518. + */ + ES256: "ES256", + + /** + * ECDSA using P-384 and SHA-384, as described in + * https://tools.ietf.org/html/rfc7518 + */ + ES384: "ES384", + + /** + * ECDSA using P-521 and SHA-512, as described in + * https://tools.ietf.org/html/rfc7518 + */ + ES512: "ES512", + + /** + * ECDSA using P-256K and SHA-256, as described in + * https://tools.ietf.org/html/rfc7518 + */ + ES256_K: "ES256K", +} + +/** + * The encryption algorithm to use to protected the exported key material + */ +union KeyEncryptionAlgorithm { + string, + + /** The CKM_RSA_AES_KEY_WRAP key wrap mechanism. */ + CKM_RSA_AES_KEY_WRAP: "CKM_RSA_AES_KEY_WRAP", + + /** The RSA_AES_KEY_WRAP_256 key wrap mechanism. */ + RSA_AES_KEY_WRAP_256: "RSA_AES_KEY_WRAP_256", + + /** The RSA_AES_KEY_WRAP_384 key wrap mechanism. */ + RSA_AES_KEY_WRAP_384: "RSA_AES_KEY_WRAP_384", +} + +/** + * The type of the action. The value should be compared case-insensitively. + */ +#suppress "@azure-tools/typespec-azure-core/no-enum" "Intentional enum; orignially modelAsString=false" +enum KeyRotationPolicyAction { + /** + * Rotate the key based on the key policy. + */ + Rotate: "Rotate", + + /** + * Trigger Event Grid events. Defaults to 30 days before expiry. Key Vault only. + */ + Notify: "Notify", +} + +/** + * The key create parameters. + */ +model KeyCreateParameters { + /** + * The type of key to create. For valid values, see JsonWebKeyType. + */ + kty: JsonWebKeyType; + + /** + * The key size in bits. For example: 2048, 3072, or 4096 for RSA. + */ + @encodedName("application/json", "key_size") + keySize?: int32; + + /** + * The public exponent for a RSA key. + */ + @encodedName("application/json", "public_exponent") + publicExponent?: int32; + + /** + * Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + */ + @encodedName("application/json", "key_ops") + keyOps?: JsonWebKeyOperation[]; + + /** + * The attributes of a key managed by the key vault service. + */ + @encodedName("application/json", "attributes") + keyAttributes?: KeyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + tags?: Record; + + /** + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. + */ + @encodedName("application/json", "crv") + curve?: JsonWebKeyCurveName; + + /** + * The policy rules under which the key can be exported. + */ + @encodedName("application/json", "release_policy") + releasePolicy?: KeyReleasePolicy; +} + +/** + * The attributes of a key managed by the key vault service. + */ +model KeyAttributes { + ...Attributes; + + /** + * softDelete data retention days. Value should be >=7 and <=90 when softDelete + * enabled, otherwise 0. + */ + @visibility("read") + recoverableDays?: int32; + + /** + * 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. + */ + @visibility("read") + recoveryLevel?: string; // DeletionRecoveryLevel, but this should be treated as an opaque string. + + /** + * Indicates if the private key can be exported. Release policy must be provided + * when creating the first version of an exportable key. + */ + exportable?: boolean; + + /** + * The underlying HSM Platform. + */ + @visibility("read") + hsmPlatform?: string; +} + +/** + * The object attributes managed by the KeyVault service. + */ +model Attributes { + /** + * Determines whether the object is enabled. + */ + enabled?: boolean; + + /** + * Not before date in UTC. + */ + @encodedName("application/json", "nbf") + @encode("unixTimestamp", int32) + notBefore?: utcDateTime; + + /** + * Expiry date in UTC. + */ + @encodedName("application/json", "exp") + @encode("unixTimestamp", int32) + expires?: utcDateTime; + + /** + * Creation time in UTC. + */ + @visibility("read") + @encode("unixTimestamp", int32) + created?: utcDateTime; + + /** + * Last updated time in UTC. + */ + @visibility("read") + @encode("unixTimestamp", int32) + updated?: utcDateTime; +} + +/** + * The policy rules under which the key can be exported. + */ +model KeyReleasePolicy { + /** + * Content type and version of key release policy + */ + contentType?: string = "application/json; charset=utf-8"; + + /** + * Defines the mutability state of the policy. Once marked immutable, this flag + * cannot be reset and the policy cannot be changed under any circumstances. + */ + immutable?: boolean; + + /** + * Blob encoding the policy rules under which the key can be released. Blob must + * be base64 URL encoded. + */ + @encodedName("application/json", "data") + @encode("base64url") + encodedPolicy?: bytes; +} + +/** + * A KeyBundle consisting of a WebKey plus its attributes. + */ +model KeyBundle { + /** + * The Json web key. + */ + key?: JsonWebKey; + + /** + * The key management attributes. + */ + attributes?: KeyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + tags?: Record; + + /** + * True if the key's lifetime is managed by key vault. If this is a key backing a + * certificate, then managed will be true. + */ + @visibility("read") + managed?: boolean; + + /** + * The policy rules under which the key can be exported. + */ + @encodedName("application/json", "release_policy") + releasePolicy?: KeyReleasePolicy; +} + +/** + * As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 + */ +model JsonWebKey { + /** + * Key identifier. + */ + kid?: string; + + /** + * JsonWebKey Key Type (kty), as defined in + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + */ + kty?: JsonWebKeyType; + + /** + * Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + */ + @encodedName("application/json", "key_ops") + keyOps?: string[]; + + /** + * RSA modulus. + */ + @encode("base64url") + n?: bytes; + + /** + * RSA public exponent. + */ + @encode("base64url") + e?: bytes; + + /** + * RSA private exponent, or the D component of an EC private key. + */ + @encode("base64url") + d?: bytes; + + /** + * RSA private key parameter. + */ + @encode("base64url") + dp?: bytes; + + /** + * RSA private key parameter. + */ + @encode("base64url") + dq?: bytes; + + /** + * RSA private key parameter. + */ + @encode("base64url") + qi?: bytes; + + /** + * RSA secret prime. + */ + @encode("base64url") + p?: bytes; + + /** + * RSA secret prime, with p < q. + */ + @encode("base64url") + q?: bytes; + + /** + * Symmetric key. + */ + @encode("base64url") + k?: bytes; + + /** + * Protected Key, used with 'Bring Your Own Key'. + */ + @encodedName("application/json", "key_hsm") + @encode("base64url") + t?: bytes; + + /** + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. + */ + crv?: JsonWebKeyCurveName; + + /** + * X component of an EC public key. + */ + @encode("base64url") + x?: bytes; + + /** + * Y component of an EC public key. + */ + @encode("base64url") + y?: bytes; +} + +/** + * The key vault error exception. + */ +@error +model KeyVaultError { + /** + * The key vault server error. + */ + @visibility("read") + error?: Error; +} + +/** + * The key vault server error. + */ +model Error { + /** + * The error code. + */ + @visibility("read") + code?: string; + + /** + * The error message. + */ + @visibility("read") + message?: string; + + /** + * The key vault server error. + */ + @visibility("read") + @encodedName("application/json", "innererror") + innerError?: Error; +} + +/** + * The key import parameters. + */ +model KeyImportParameters { + /** + * Whether to import as a hardware key (HSM) or software key. + */ + @encodedName("application/json", "Hsm") + hsm?: boolean; + + /** + * The Json web key + */ + key: JsonWebKey; + + /** + * The key management attributes. + */ + @encodedName("application/json", "attributes") + keyAttributes?: KeyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + tags?: Record; + + /** + * The policy rules under which the key can be exported. + */ + @encodedName("application/json", "release_policy") + releasePolicy?: KeyReleasePolicy; +} + +/** + * A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info + */ +model DeletedKeyBundle { + ...KeyBundle; + + /** + * The url of the recovery object, used to identify and recover the deleted key. + */ + recoveryId?: string; + + /** + * The time when the key is scheduled to be purged, in UTC + */ + @visibility("read") + @encode("unixTimestamp", int32) + scheduledPurgeDate?: utcDateTime; + + /** + * The time when the key was deleted, in UTC + */ + @visibility("read") + @encode("unixTimestamp", int32) + deletedDate?: utcDateTime; +} + +/** + * The key update parameters. + */ +model KeyUpdateParameters { + /** + * Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + */ + @encodedName("application/json", "key_ops") + keyOps?: JsonWebKeyOperation[]; + + /** + * The attributes of a key managed by the key vault service. + */ + @encodedName("application/json", "attributes") + keyAttributes?: KeyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + tags?: Record; + + /** + * The policy rules under which the key can be exported. + */ + @encodedName("application/json", "release_policy") + releasePolicy?: KeyReleasePolicy; +} + +/** + * The key list result. + */ +@pagedResult +model KeyListResult { + /** + * A response message containing a list of keys in the key vault along with a link to the next page of keys. + */ + @items + @visibility("read") + value?: KeyItem[]; + + /** + * The URL to get the next set of keys. + */ + @Azure.Core.nextLink + @visibility("read") + nextLink?: string; +} + +/** + * The key item containing key metadata. + */ +model KeyItem { + /** + * Key identifier. + */ + kid?: string; + + /** + * The key management attributes. + */ + attributes?: KeyAttributes; + + /** + * Application specific metadata in the form of key-value pairs. + */ + tags?: Record; + + /** + * True if the key's lifetime is managed by key vault. If this is a key backing a + * certificate, then managed will be true. + */ + @visibility("read") + managed?: boolean; +} + +/** + * The backup key result, containing the backup blob. + */ +model BackupKeyResult { + /** + * The backup blob containing the backed up key. + */ + @visibility("read") + @encode("base64url") + value?: bytes; +} + +/** + * The key restore parameters. + */ +model KeyRestoreParameters { + /** + * The backup blob associated with a key bundle. + */ + @encodedName("application/json", "value") + @encode("base64url") + keyBundleBackup: bytes; +} + +/** + * The key operations parameters. + */ +model KeyOperationsParameters { + /** + * algorithm identifier + */ + @encodedName("application/json", "alg") + algorithm: JsonWebKeyEncryptionAlgorithm; + + /** + * The value to operate on. + */ + @encode("base64url") + value: bytes; + + /** + * Cryptographically random, non-repeating initialization vector for symmetric + * algorithms. + */ + @encode("base64url") + iv?: bytes; + + /** + * Additional data to authenticate but not encrypt/decrypt when using + * authenticated crypto algorithms. + */ + @encode("base64url") + aad?: bytes; + + /** + * The tag to authenticate when performing decryption with an authenticated + * algorithm. + */ + @encode("base64url") + tag?: bytes; +} + +/** + * The key operation result. + */ +model KeyOperationResult { + /** + * Key identifier + */ + @visibility("read") + kid?: string; + + /** + * The result of the operation. + */ + @visibility("read") + @encodedName("application/json", "value") + @encode("base64url") + result?: bytes; + + /** + * Cryptographically random, non-repeating initialization vector for symmetric + * algorithms. + */ + @visibility("read") + @encode("base64url") + iv?: bytes; + + /** + * The tag to authenticate when performing decryption with an authenticated + * algorithm. + */ + @visibility("read") + @encodedName("application/json", "tag") + @encode("base64url") + authenticationTag?: bytes; + + /** + * Additional data to authenticate but not encrypt/decrypt when using + * authenticated crypto algorithms. + */ + @visibility("read") + @encodedName("application/json", "aad") + @encode("base64url") + additionalAuthenticatedData?: bytes; +} + +/** + * The key operations parameters. + */ +model KeySignParameters { + /** + * The signing/verification algorithm identifier. For more information on possible + * algorithm types, see JsonWebKeySignatureAlgorithm. + */ + @encodedName("application/json", "alg") + algorithm: JsonWebKeySignatureAlgorithm; + + /** + * The value to operate on. + */ + @encode("base64url") + value: bytes; +} + +/** + * The key verify parameters. + */ +model KeyVerifyParameters { + /** + * The signing/verification algorithm. For more information on possible algorithm + * types, see JsonWebKeySignatureAlgorithm. + */ + @encodedName("application/json", "alg") + algorithm: JsonWebKeySignatureAlgorithm; + + /** + * The digest used for signing. + */ + @encode("base64url") + digest: bytes; + + /** + * The signature to be verified. + */ + @encodedName("application/json", "value") + @encode("base64url") + signature: bytes; +} + +/** + * The key verify result. + */ +model KeyVerifyResult { + /** + * True if the signature is verified, otherwise false. + */ + @visibility("read") + value?: boolean; +} + +/** + * The release key parameters. + */ +model KeyReleaseParameters { + /** + * The attestation assertion for the target of the key release. + */ + @minLength(1) + @encodedName("application/json", "target") + targetAttestationToken: string; + + /** + * A client provided nonce for freshness. + */ + nonce?: string; + + /** + * The encryption algorithm to use to protected the exported key material + */ + enc?: KeyEncryptionAlgorithm; +} + +/** + * The release result, containing the released key. + */ +model KeyReleaseResult { + /** + * A signed object containing the released key. + */ + @visibility("read") + value?: string; +} + +/** + * A list of keys that have been deleted in this vault. + */ +@pagedResult +model DeletedKeyListResult { + /** + * A response message containing a list of deleted keys in the key vault along with a link to the next page of + * deleted keys. + */ + @items + @visibility("read") + value?: DeletedKeyItem[]; + + /** + * The URL to get the next set of deleted keys. + */ + @Azure.Core.nextLink + @visibility("read") + nextLink?: string; +} + +/** + * The deleted key item containing the deleted key metadata and information about + * deletion. + */ +model DeletedKeyItem { + ...KeyItem; + + /** + * The url of the recovery object, used to identify and recover the deleted key. + */ + recoveryId?: string; + + /** + * The time when the key is scheduled to be purged, in UTC + */ + @visibility("read") + @encode("unixTimestamp", int32) + scheduledPurgeDate?: utcDateTime; + + /** + * The time when the key was deleted, in UTC + */ + @visibility("read") + @encode("unixTimestamp", int32) + deletedDate?: utcDateTime; +} + +/** + * Management policy for a key. + */ +model KeyRotationPolicy { + /** + * The key policy id. + */ + @visibility("read") + id?: string; + + /** + * 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. + */ + lifetimeActions?: LifetimeActions[]; + + /** + * The key rotation policy attributes. + */ + attributes?: KeyRotationPolicyAttributes; +} + +/** + * Action and its trigger that will be performed by Key Vault over the lifetime of + * a key. + */ +model LifetimeActions { + /** + * The condition that will execute the action. + */ + trigger?: LifetimeActionsTrigger; + + /** + * The action that will be executed. + */ + action?: LifetimeActionsType; +} + +/** + * A condition to be satisfied for an action to be executed. + */ +model LifetimeActionsTrigger { + /** + * Time after creation to attempt to rotate. It only applies to rotate. It will be + * in ISO 8601 duration format. Example: 90 days : "P90D" + */ + timeAfterCreate?: string; + + /** + * Time before expiry to attempt to rotate or notify. It will be in ISO 8601 + * duration format. Example: 90 days : "P90D" + */ + timeBeforeExpiry?: string; +} + +/** + * The action that will be executed. + */ +model LifetimeActionsType { + /** + * The type of the action. The value should be compared case-insensitively. + */ + type?: KeyRotationPolicyAction; +} + +/** + * The key rotation policy attributes. + */ +model KeyRotationPolicyAttributes { + /** + * The expiryTime will be applied on the new key version. It should be at least 28 + * days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 + * hours: PT48H, 1 year and 10 days: P1Y10D + */ + expiryTime?: string; + + /** + * The key rotation policy created time in UTC. + */ + @visibility("read") + @encode("unixTimestamp", int32) + created?: utcDateTime; + + /** + * The key rotation policy's last updated time in UTC. + */ + @visibility("read") + @encode("unixTimestamp", int32) + updated?: utcDateTime; +} + +/** + * The get random bytes request object. + */ +model GetRandomBytesRequest { + /** + * The requested number of random bytes. + */ + @maxValue(128) + @minValue(1) + count: int32; +} + +/** + * The get random bytes response object containing the bytes. + */ +model RandomBytes { + /** + * The bytes encoded as a base64url string. + */ + @encode("base64url") + value: bytes; +} + +/** + * Properties of the key pair backing a certificate. + */ +model KeyProperties { + /** + * Indicates if the private key can be exported. Release policy must be provided + * when creating the first version of an exportable key. + */ + exportable?: boolean; + + /** + * The type of key pair to be used for the certificate. + */ + @minLength(1) + @encodedName("application/json", "kty") + keyType?: JsonWebKeyType; + + /** + * The key size in bits. For example: 2048, 3072, or 4096 for RSA. + */ + @encodedName("application/json", "key_size") + keySize?: int32; + + /** + * Indicates if the same key pair will be used on certificate renewal. + */ + @encodedName("application/json", "reuse_key") + reuseKey?: boolean; + + /** + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. + */ + @encodedName("application/json", "crv") + curve?: JsonWebKeyCurveName; +} + +/** + * The export key parameters. + */ +model KeyExportParameters { + /** + * The export key encryption Json web key. This key MUST be a RSA key that + * supports encryption. + */ + wrappingKey?: JsonWebKey; + + /** + * The export key encryption key identifier. This key MUST be a RSA key that + * supports encryption. + */ + wrappingKid?: string; + + /** + * The encryption algorithm to use to protected the exported key material + */ + @minLength(1) + enc?: KeyEncryptionAlgorithm; +} diff --git a/packages/typespec-go/test/tsp/KeyVault.Keys/routes.tsp b/packages/typespec-go/test/tsp/KeyVault.Keys/routes.tsp new file mode 100644 index 000000000..3f3a96f61 --- /dev/null +++ b/packages/typespec-go/test/tsp/KeyVault.Keys/routes.tsp @@ -0,0 +1,791 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; +import "@typespec/openapi"; +import "@typespec/rest"; +import "./models.tsp"; + +using Azure.Core; +using Azure.Core.Traits; +using Azure.ClientGenerator.Core; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using TypeSpec.Rest; + +namespace KeyVault; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary(""" + Creates a new key, stores it, then returns key parameters and attributes to the + client. + """) +@route("/keys/{key-name}/create") +@post +op createKey is Azure.Core.Foundations.Operation< + { + /** + * 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. + */ + @pattern("^[0-9a-zA-Z-]+$") + @path("key-name") + keyName: string; + + /** + * The parameters to create a key. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyCreateParameters; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * The operation will rotate the key based on the key policy. It requires the + * keys/rotate permission. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary(""" + Creates a new key version, stores it, then returns key parameters, attributes + and policy to the client. + """) +@route("/keys/{key-name}/rotate") +@post +op rotateKey is Azure.Core.Foundations.Operation< + { + /** + * The name of key to be rotated. The system will generate a new version in the + * specified key. + */ + @pattern("^[0-9a-zA-Z-]+$") + @path("key-name") + keyName: string; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary(""" + Imports an externally created key, stores it, and returns key parameters and + attributes to the client. + """) +@route("/keys/{key-name}") +@put +op importKey is Azure.Core.Foundations.Operation< + { + /** + * Name for the imported 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. + */ + @pattern("^[0-9a-zA-Z-]+$") + @path("key-name") + keyName: string; + + /** + * The parameters to import a key. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyImportParameters; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Deletes a key of any type from storage in Azure Key Vault.") +@route("/keys/{key-name}") +@delete +op deleteKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key to delete. + */ + @path("key-name") + keyName: string; + }, + DeletedKeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary(""" + 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. + """) +@route("/keys/{key-name}/{key-version}") +@patch +op updateKey is Azure.Core.Foundations.Operation< + { + /** + * The name of key to update. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key to update. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters of the key to update. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyUpdateParameters; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Gets the public part of a stored key.") +@route("/keys/{key-name}/{key-version}") +@get +op getKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key to get. + */ + @path("key-name") + keyName: string; + + /** + * Adding the version parameter retrieves a specific version of a key. This URI + * fragment is optional. If not specified, the latest version of the key is + * returned. + */ + @path("key-version") + keyVersion: string; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * The full key identifier, attributes, and tags are provided in the response. + * This operation requires the keys/list permission. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary("Retrieves a list of individual key versions with the same key name.") +@route("/keys/{key-name}/versions") +@get +op getKeyVersions is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * Maximum number of results to return in a page. If not specified the service + * will return up to 25 results. + */ + @maxValue(25) + @minValue(1) + @query("maxresults") + maxresults?: int32; + }, + KeyListResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary("List keys in the specified vault.") +@route("/keys") +@get +op getKeys is Azure.Core.Foundations.Operation< + { + /** + * Maximum number of results to return in a page. If not specified the service + * will return up to 25 results. + */ + @maxValue(25) + @minValue(1) + @query("maxresults") + maxresults?: int32; + }, + KeyListResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Requests that a backup of the specified key be downloaded to the client.") +@route("/keys/{key-name}/backup") +@post +op backupKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + }, + BackupKeyResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Restores a backed up key to a vault.") +@route("/keys/restore") +@post +op restoreKey is Azure.Core.Foundations.Operation< + { + /** The parameters to restore the key. */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyRestoreParameters; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("encrypt") +@summary(""" + Encrypts an arbitrary sequence of bytes using an encryption key that is stored + in a key vault. + """) +@route("/keys/{key-name}/{key-version}/encrypt") +@post +op encrypt is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for the encryption operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyOperationsParameters; + }, + KeyOperationResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("decrypt") +@summary("Decrypts a single block of encrypted data.") +@route("/keys/{key-name}/{key-version}/decrypt") +@post +op decrypt is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for the decryption operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyOperationsParameters; + }, + KeyOperationResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("sign") +@summary("Creates a signature from a digest using the specified key.") +@route("/keys/{key-name}/{key-version}/sign") +@post +op sign is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for the signing operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeySignParameters; + }, + KeyOperationResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("verify") +@summary("Verifies a signature using a specified key.") +@route("/keys/{key-name}/{key-version}/verify") +@post +op verify is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for verify operations. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyVerifyParameters; + }, + KeyVerifyResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("wrapKey") +@summary("Wraps a symmetric key using a specified key.") +@route("/keys/{key-name}/{key-version}/wrapkey") +@post +op wrapKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for wrap operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyOperationsParameters; + }, + KeyOperationResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("unwrapKey") +@summary(""" + Unwraps a symmetric key using the specified key that was initially used for + wrapping that key. + """) +@route("/keys/{key-name}/{key-version}/unwrapkey") +@post +op unwrapKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + + /** + * The version of the key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for the key operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyOperationsParameters; + }, + KeyOperationResult, + {}, + KeyVaultError +>; + +/** + * The release key operation is applicable to all key types. The target key must + * be marked exportable. This operation requires the keys/release permission. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/no-openapi" "Operation ID is auto-capitalized, which would be breaking" +@operationId("release") +@summary("Releases a key.") +@route("/keys/{key-name}/{key-version}/release") +@post +op release is Azure.Core.Foundations.Operation< + { + /** + * The name of the key to get. + */ + @path("key-name") + keyName: string; + + /** + * Adding the version parameter retrieves a specific version of a key. + */ + @path("key-version") + keyVersion: string; + + /** + * The parameters for the key release operation. + */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: KeyReleaseParameters; + }, + KeyReleaseResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary("Lists the deleted keys in the specified vault.") +@route("/deletedkeys") +@get +op getDeletedKeys is Azure.Core.Foundations.Operation< + { + /** + * Maximum number of results to return in a page. If not specified the service + * will return up to 25 results. + */ + @maxValue(25) + @minValue(1) + @query("maxresults") + maxresults?: int32; + }, + DeletedKeyListResult, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Gets the public part of a deleted key.") +@route("/deletedkeys/{key-name}") +@get +op getDeletedKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key. + */ + @path("key-name") + keyName: string; + }, + DeletedKeyBundle, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary("Permanently deletes the specified key.") +@route("/deletedkeys/{key-name}") +@delete +op purgeDeletedKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the key + */ + @path("key-name") + keyName: string; + }, + void, + {}, + KeyVaultError +>; + +/** + * 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. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Recovers the deleted key to its latest version.") +@route("/deletedkeys/{key-name}/recover") +@post +op recoverDeletedKey is Azure.Core.Foundations.Operation< + { + /** + * The name of the deleted key. + */ + @path("key-name") + keyName: string; + }, + KeyBundle, + {}, + KeyVaultError +>; + +/** + * The GetKeyRotationPolicy operation returns the specified key policy resources + * in the specified key vault. This operation requires the keys/get permission. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Lists the policy for a key.") +@route("/keys/{key-name}/rotationpolicy") +@get +op getKeyRotationPolicy is Azure.Core.Foundations.Operation< + { + /** + * The name of the key in a given key vault. + */ + @path("key-name") + keyName: string; + }, + KeyRotationPolicy, + {}, + KeyVaultError +>; + +/** + * Set specified members in the key policy. Leave others as undefined. This + * operation requires the keys/update permission. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +#suppress "@azure-tools/typespec-azure-core/use-standard-names" "Operation name is already established" +@summary("Updates the rotation policy for a key.") +@route("/keys/{key-name}/rotationpolicy") +@put +op updateKeyRotationPolicy is Azure.Core.Foundations.Operation< + { + /** + * The name of the key in the given vault. + */ + @path("key-name") + keyName: string; + + /** + * The policy for the key. + */ + @body + keyRotationPolicy: KeyRotationPolicy; + }, + KeyRotationPolicy, + {}, + KeyVaultError +>; + +/** + * Get the requested number of bytes containing random values from a managed HSM. + */ +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Foundations.Operation is necessary for Key Vault" +@summary("Get the requested number of bytes containing random values.") +@route("/rng") +@post +op getRandomBytes is Azure.Core.Foundations.Operation< + { + /** The request object to get random bytes. */ + #suppress "deprecated" "Property flattening is supported for legacy scenarios like Key Vault's" + @body + @flattenProperty + parameters: GetRandomBytesRequest; + }, + RandomBytes, + {}, + KeyVaultError +>;