From ecbc4788cced3d9f26959cc8db3e2d1aa132411e Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Thu, 16 Jan 2025 20:40:27 +0000 Subject: [PATCH] CodeGen from PR 29249 in Azure/azure-rest-api-specs Merge 925d5c86f923de0b25ac7decf27ace22dd8b0a4d into cb78c4578918363f2b8c77af57b4d5c9ee9b1d6f --- .../CHANGELOG.md | 662 ----- .../azure-security-keyvault-secrets/README.md | 280 -- .../TROUBLESHOOTING.md | 2 - .../assets.json | 6 - .../checkstyle-suppressions.xml | 17 - .../migration_guide.md | 241 -- .../perf-tests.yml | 31 - .../azure-security-keyvault-secrets/pom.xml | 83 - .../spotbugs-exclude.xml | 46 - .../keyvault/secrets/SecretAsyncClient.java | 1048 -------- .../keyvault/secrets/SecretClient.java | 1032 -------- .../keyvault/secrets/SecretClientBuilder.java | 517 ---- .../secrets/SecretServiceVersion.java | 69 - .../implementation/DeletedSecretHelper.java | 55 - .../KeyVaultCredentialPolicy.java | 526 ---- .../KeyVaultErrorCodeStrings.java | 10 - .../implementation/SecretClientImpl.java | 2338 ----------------- .../SecretPropertiesHelper.java | 116 - .../implementation/models/Attributes.java | 226 -- .../models/BackupSecretResult.java | 78 - .../models/DeletedSecretBundle.java | 226 -- .../models/DeletedSecretItem.java | 194 -- .../models/DeletedSecretListResult.java | 93 - .../models/DeletionRecoveryLevel.java | 99 - .../secrets/implementation/models/Error.java | 105 - .../implementation/models/KeyVaultError.java | 73 - .../models/KeyVaultErrorException.java | 42 - .../models/SecretAttributes.java | 184 -- .../implementation/models/SecretBundle.java | 259 -- .../implementation/models/SecretItem.java | 201 -- .../models/SecretListResult.java | 92 - .../models/SecretProperties.java | 85 - .../models/SecretRestoreParameters.java | 97 - .../models/SecretSetParameters.java | 172 -- .../models/SecretUpdateParameters.java | 143 - .../models/SecretsModelsUtils.java | 178 -- .../implementation/models/package-info.java | 9 - .../secrets/implementation/package-info.java | 9 - .../secrets/models/DeletedSecret.java | 149 -- .../secrets/models/KeyVaultSecret.java | 150 -- .../models/KeyVaultSecretIdentifier.java | 105 - .../secrets/models/SecretProperties.java | 439 ---- .../keyvault/secrets/models/package-info.java | 9 - .../keyvault/secrets/package-info.java | 177 -- .../src/main/java/module-info.java | 15 - .../proxy-config.json | 3 - .../reflect-config.json | 104 - .../resource-config.json | 13 - .../azure-key-vault-secrets.properties | 2 - .../src/samples/README.md | 87 - .../secrets/BackupAndRestoreOperations.java | 105 - .../BackupAndRestoreOperationsAsync.java | 114 - .../security/keyvault/secrets/HelloWorld.java | 80 - .../keyvault/secrets/HelloWorldAsync.java | 99 - .../keyvault/secrets/ListOperations.java | 69 - .../keyvault/secrets/ListOperationsAsync.java | 92 - .../secrets/ManagingDeletedSecrets.java | 113 - .../secrets/ManagingDeletedSecretsAsync.java | 123 - .../secrets/PersistentTokenCacheDemo.java | 37 - .../keyvault/secrets/ReadmeSamples.java | 149 -- .../SecretAsyncClientJavaDocCodeSnippets.java | 356 --- .../SecretClientJavaDocCodeSnippets.java | 383 --- .../secrets/KeyVaultCredentialPolicyTest.java | 661 ----- ...eyVaultSecretsUserAgentPropertiesTest.java | 21 - .../secrets/SecretAsyncClientTest.java | 574 ---- .../secrets/SecretClientBuilderTest.java | 184 -- .../keyvault/secrets/SecretClientTest.java | 506 ---- .../secrets/SecretClientTestBase.java | 427 --- .../security/keyvault/secrets/TestUtils.java | 54 - .../models/KeyVaultSecretIdentifierTest.java | 55 - .../swagger/autorest.md | 63 - .../tsp-location.yaml | 5 + 72 files changed, 5 insertions(+), 15162 deletions(-) delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/README.md delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/TROUBLESHOOTING.md delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/assets.json delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/migration_guide.md delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/perf-tests.yml delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/pom.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/spotbugs-exclude.xml delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultErrorCodeStrings.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretPropertiesHelper.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifier.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/proxy-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/reflect-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/PersistentTokenCacheDemo.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretAsyncClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/TestUtils.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifierTest.java delete mode 100644 sdk/keyvault/azure-security-keyvault-secrets/swagger/autorest.md create mode 100644 sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml diff --git a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md deleted file mode 100644 index 5e0f255e7ffe6..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md +++ /dev/null @@ -1,662 +0,0 @@ -# Release History - -## 4.10.0-beta.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 4.9.1 (2024-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.53.0` to version `1.54.1`. -- Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. - -## 4.9.0 (2024-10-15) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.52.0` to version `1.53.0`. -- Upgraded `azure-core-http-netty` from `1.15.4` to version `1.15.5`. - -## 4.8.7 (2024-09-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.2.0` to version `1.3.0`. -- Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. -- Upgraded `azure-core` from `1.51.0` to version `1.52.0`. - -## 4.8.6 (2024-08-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.50.0` to version `1.51.0`. -- Upgraded `azure-core-http-netty` from `1.15.2` to version `1.15.3`. - -## 4.8.5 (2024-07-29) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.15.1` to version `1.15.2`. -- Upgraded `azure-json` from `1.1.0` to version `1.2.0`. -- Upgraded `azure-core` from `1.49.1` to version `1.50.0`. - -## 4.8.4 (2024-06-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.0` to version `1.49.1`. -- Upgraded `azure-core-http-netty` from `1.15.0` to version `1.15.1`. - -## 4.8.3 (2024-05-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. -- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. - -## 4.8.2 (2024-04-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.47.0` to version `1.48.0`. -- Upgraded `azure-core-http-netty` from `1.14.1` to version `1.14.2`. - -## 4.8.1 (2024-03-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.46.0` to version `1.47.0`. -- Upgraded `azure-core-http-netty` from `1.14.0` to version `1.14.1`. - -## 4.8.0 (2024-02-22) -Changes when compared to the last stable release (`4.7.3`) include: - -### Features Added -- Added support for service version `7.5`. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.45.1` to version `1.46.0`. -- Upgraded `azure-core-http-netty` from `1.13.11` to version `1.14.0`. - -## 4.7.3 (2023-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.10` to version `1.13.11`. -- Upgraded `azure-core` from `1.45.0` to version `1.45.1`. - -## 4.7.2 (2023-11-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.8.0-beta.1 (2023-11-09) - -### Features Added -- Added support for service version `7.5-preview.1`. - -#### Dependency Updates -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. - -## 4.7.1 (2023-10-20) - -### Bugs Fixed -- Fixed an issue preventing the client from setting the `contentType` of the secret when the set secret operation is performed. ([#37019](https://github.com/Azure/azure-sdk-for-java/issues/37019)) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.43.0` to version `1.44.1`. -- Upgraded `azure-core-http-netty` from `1.13.7` to version `1.13.9`. - -## 4.7.0 (2023-09-25) - -### Features Added -- Added new methods `fromJson` and `toJson` to models: - - `DeletedSecret` - - `KeyVaultSecret` - - `SecretProperties` - -### Other Changes -- Migrate test recordings to assets repo. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.42.0` to version `1.43.0`. -- Upgraded `azure-core-http-netty` from `1.13.6` to version `1.13.7`. - -## 4.6.5 (2023-08-21) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.41.0` to version `1.42.0`. -- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`. - -## 4.6.4 (2023-07-25) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.40.0` to version `1.41.0`. -- Upgraded `azure-core-http-netty` from `1.13.4` to version `1.13.5`. - -## 4.6.3 (2023-06-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.39.0` to version `1.40.0`. -- Upgraded `azure-core-http-netty` from `1.13.3` to version `1.13.4`. - -## 4.6.2 (2023-05-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.2` to version `1.13.3`. -- Upgraded `azure-core` from `1.38.0` to version `1.39.0`. - -## 4.6.1 (2023-04-20) - -### Other Changes - -- Test proxy server migration. -- Made all logger instances static. - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.1` to version `1.13.2`. -- Upgraded `azure-core` from `1.37.0` to version `1.38.0`. - -## 4.6.0 (2023-03-18) - -### Features Added -- Added support for service version `7.4`. - -### Other Changes -- Upgraded `azure-core-http-netty` from `1.13.0` to version `1.13.1`. -- Upgraded `azure-core` from `1.36.0` to version `1.37.0`. - -## 4.5.4 (2023-02-16) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.12.8` to version `1.13.0`. -- Upgraded `azure-core` from `1.35.0` to version `1.36.0`. - -## 4.5.3 (2023-01-09) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.34.0` to version `1.35.0`. -- Upgraded `azure-core-http-netty` from `1.12.7` to version `1.12.8`. - -## 4.5.2 (2022-11-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.33.0` to version `1.34.0`. -- Upgraded `azure-core-http-netty` from `1.12.6` to version `1.12.7`. - -## 4.5.1 (2022-10-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.32.0` to version `1.33.0`. -- Upgraded `azure-core-http-netty` from `1.12.5` to version `1.12.6`. - -## 4.5.0 (2022-09-20) - -### Breaking Changes -- Made it so that we verify that the challenge resource matches the vault domain by default. This should affect few customers who can use the `disableChallengeResourceVerification()` method in client builders to disable this functionality. See https://aka.ms/azsdk/blog/vault-uri for more information. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.31.0` to version `1.32.0`. -- Upgraded `azure-core-http-netty` from `1.12.4` to version `1.12.5`. - -## 4.4.6 (2022-08-17) - -### Bugs Fixed -- Fixed an issue where requests sent by sync clients that should include a body could have an empty body instead. ([#30512](https://github.com/Azure/azure-sdk-for-java/pull/30512)) - -## 4.4.5 (2022-08-15) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.31.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.4`. - -## 4.4.4 (2022-07-06) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.30.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.3`. - -## 4.4.3 (2022-06-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.29.1`. -- Upgraded `azure-core-http-netty` dependency to `1.12.2`. - -## 4.4.2 (2022-05-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.28.0`. -- Upgraded `azure-core-http-netty` dependency to `1.12.0`. - -## 4.4.1 (2022-04-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.27.0`. -- Upgraded `azure-core-http-netty` dependency to `1.11.9`. - -## 4.4.0 (2022-03-31) - -### Features Added -- Added support for service version `7.3`. -- Implemented new traits (micro-interfaces) in `SecretClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. - -## 4.3.8 (2022-03-17) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.26.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.8` - -## 4.4.0-beta.5 (2022-02-11) - -### Features added -- Implemented new traits (micro-interfaces) in `SecretClientBuilder`. This makes the experience of using client builders more consistent across libraries in the Azure SDK for Java. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.3.7 (2022-02-11) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.25.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.7` - -## 4.4.0-beta.4 (2022-01-13) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.3.6 (2022-01-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.24.1` -- Upgraded `azure-core-http-netty` dependency to `1.11.6` - -## 4.4.0-beta.3 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.3.5 (2021-11-12) - -### Features Added - -- Added support for multi-tenant authentication in clients. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.22.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.2` - -## 4.4.0-beta.2 (2021-10-07) - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.21.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.1` - -## 4.3.4 (2021-10-06) - -### Bugs Fixed -- Fixed an issue that made clients send unnecessary unauthorized requests to obtain a bearer challenge from the service even when already possessing a valid bearer token. - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.21.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.1` - -## 4.4.0-beta.1 (2021-09-10) - -### Features Added -- Added support for service version `7.3-preview`. - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.3.3 (2021-09-10) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.20.0` -- Upgraded `azure-core-http-netty` dependency to `1.11.0` - -## 4.3.2 (2021-08-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.19.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.2` - -## 4.3.1 (2021-07-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` dependency to `1.18.0` -- Upgraded `azure-core-http-netty` dependency to `1.10.1` - -## 4.3.0 (2021-06-17) - -### Features Added -- Changed default service version to `7.2`. -- Added `KeyVaultSecretIdentifier` to parse secret URLs. - -### Changes since 4.3.0-beta.6 - -#### Bug Fixes -- Ensured that `RetryPolicy` and `HttpLogOptions` use a default implementation when creating Key Vault clients if not set or set to `null`. - -#### Breaking Changes -- Removed service method overloads that take a `pollingInterval`, since `PollerFlux` and `SyncPoller` objects allow for setting this value directly on them. - -#### Non-Breaking Changes -- Renamed `secretId` to `sourceId` in `KeyVaultSecretIdentifier`. -- `KeyVaultSecretIdentifier` can now be used to parse any Key Vault identifier. -- Added the `@ServiceMethod` annotation to all public methods that call the Key Vault service in `SecretClient` and `SecretAsyncClient`. - -## 4.3.0-beta.6 (2021-05-15) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.16.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.2` -- Upgraded `azure-identity` dependency to `1.3.0` - -## 4.3.0-beta.5 (2021-04-09) - -### New features -- Added support for service version `7.2`. -- Added support to specify whether or not a pipeline policy should be added per call or per retry. - -### Breaking Changes -- Changed `KeyVaultSecretIdentifier` so it is instantiated via its constructor as opposed to via a `parse()` factory method. - -## 4.3.0-beta.4 (2021-03-12) - -### Changed -- Changed logging level in `onRequest` and `onSuccess` calls for service operations from `INFO` to `VERBOSE`. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.14.0` -- Upgraded `azure-core-http-netty` dependency to `1.9.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.6.0` -- Upgraded `azure-identity` dependency to `1.2.4` - -## 4.3.0-beta.3 (2021-02-11) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.13.0` -- Upgraded `azure-core-http-netty` dependency to `1.8.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.2.3` - -## 4.2.5 (2021-02-11) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.13.0` -- Upgraded `azure-core-http-netty` dependency to `1.8.0` -- Upgraded `azure-core-http-okhttp` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.2.3` - -## 4.2.4 (2021-01-15) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.12.0` -- Upgraded `azure-core-http-netty` dependency to `1.7.1` -- Upgraded `azure-core-http-okhttp` dependency to `1.4.1` -- Upgraded `azure-identity` dependency to `1.2.2` - -## 4.2.3 (2020-11-12) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.10.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.3` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.3` -- Upgraded `azure-core-test` dependency to `1.5.1` -- Upgraded `azure-identity` dependency to `1.2.0` - -## 4.3.0-beta.2 (2020-10-09) - -### New Features -- Added `KeyVaultSecretIdentifier`. Use its [`parse`](https://github.com/Azure/azure-sdk-for-java/blob/ff52067a3772a430e5913b898f2806078aec8ef2/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifier.java#L79) method to parse the different elements of a given secret identifier. -- Added API overloads that allow for passing specific polling intervals for long-running operations: - - `SecretAsyncClient` - - `beginDeleteSecret(String, Duration)` - - `beginRecoverDeletedSecret(String, Duration)` - - `SecretClient` - - `beginDeleteSecret(String, Duration)` - - `beginRecoverDeletedSecret(String, Duration)` -- Added support for `com.azure.core.util.ClientOptions` in client builders. - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.9.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.2` -- Upgraded `azure-core-test` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.1.3` - -## 4.2.2 (2020-10-08) - -### Dependency Updates -- Upgraded `azure-core` dependency to `1.9.0` -- Upgraded `azure-core-http-netty` dependency to `1.6.2` -- Upgraded `azure-core-http-okhttp` dependency to `1.3.2` -- Upgraded `azure-core-test` dependency to `1.5.0` -- Upgraded `azure-identity` dependency to `1.1.3` - -## 4.3.0-beta.1 (2020-09-11) -- Updated versions for azure-core and azure-identity. - -## 4.2.1 (2020-09-10) -- Updated versions for azure-core and azure-identity. - -## 4.2.0 (2020-08-12) -- Added support for service version `7.1`. -- Added `retryPolicy` setter in `SecretClientBuilder`. -- Added `recoverableDays` property to `SecretProperties`. - -## 4.2.0-beta.4 (2020-07-08) -- Updated versions for azure-core, azure-identity. - -## 4.1.5 (2020-07-08) -- Updated versions for azure-core and azure-identity. - -## 4.2.0-beta.3 (2020-06-10) -- Updated version for azure-core, azure-identity and external dependencies. -- Fixed `ByteBuf` resource leak in `KeyVaultCredentialPolicy`. - -## 4.1.4 (2020-06-10) -- Updated version for azure-core, azure-identity and external dependencies. - -## 4.1.3 (2020-05-06) -- Update azure-core dependency to version 1.5.0. -- Fixed `ByteBuff` resource leak in `KeyVaultCredentialPolicy`. - -## 4.2.0-beta.2 (2020-04-09) -- Update azure-core dependency to version 1.4.0. -- Added `retryPolicy` setter in `SecretClientBuilder` - -## 4.1.2 (2020-04-07) -- Update azure-core dependency to version 1.4.0. - -## 4.1.1 (2020-03-25) -- Update azure-core dependency to version 1.3.0. - -## 4.2.0-beta.1 (2020-03-10) -### Added -- Added `recoverableDays` property to `SecretProperties`. -- Added support for `7.1-Preview` service version - -## 4.1.0 (2020-01-07) -- Update azure-core dependency to version 1.2.0 -- Drop commons-codec dependency - -## 4.0.1 (2019-12-04) - -## 4.0.0 (2019-10-31) -### Breaking changes - -- Secret has been renamed to KeyVaultSecret to avoid ambiguity with other libraries and to yield better search results. -- endpoint method on SecretClientBuilder has been renamed to vaultUrl. -- On SecretProperties, expires, created, and updated have been renamed to expiresOn, createdOn, and updatedOn respectively. -- On DeletedSecret, deletedDate has been renamed to deletedOn. -- listSecrets and listSecretVersions methods have been renamed to listPropertiesOfSecrets and listPropertiesOfSecretVersions in `SecretClient` and `SecretAsyncClient` respectively. -- restoreSecret method has been renamed to restoreSecretBackup in `SecretClient` and `SecretAsyncClient` to better associate it with SecretClient.backupSecret. -- deleteSecret method has been renamed to beginDeleteSecret and now returns a SyncPoller in `SecretClient` and PollerFlux in `SecretAsyncClient` to track this long-running operation. -- recoverDeletedSecret method has been renamed to beginRecoverDeletedSecret and now returns a SyncPoller in `SecretClient` and PollerFlux in `SecretAsyncClient` to track this long-running operation. - -### Major changes -- SecretClient.vaultUrl has been added with the original value pass to SecretClient. - -## 4.0.0-preview.3 (2019-09-10) -For details on the Azure SDK for Java (August 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview3-java). - -## 4.0.0-preview.4 (2019-09-08) -For details on the Azure SDK for Java (September 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview4-java). - -- Updated to be fully compliant with the Java 9 Platform Module System. - -### Breaking changes -- `SecretBase` has been renamed to `SecretProperties`. -- `Secret` and `DeletedSecret` no longer extend `SecretProperties`, but instead contain a `SecretProperties` property named `Properties`. -- `updateSecret` method has been renamed to `updateSecretProperties` in `SecretClient` and `SecretAsyncClient`. -- Getters and setters were updated to use Java Bean notation. -- Changed VoidResponse to Response on sync API, and Mono to Mono> on async API. - -## 4.0.0-preview.2 (2019-08-06) -For details on the Azure SDK for Java (August 2019 Preview) release refer to the [release announcement](https://azure.github.io/azure-sdk/releases/2019-08-06/java.html). - -- Added support for HTTP challenge based authentication, allowing clients to interact with vaults in sovereign clouds. -- Combined SecretClientBuilder, SecretAsyncClientBuilder into SecretClientBuilder. Methods to create both sync and async clients type were added. -- Removed static builder method from clients. Builders are now instantiable. - -## 4.0.0-preview.1 (2019-06-28) -Version 4.0.0-preview.1 is a preview of our efforts in creating a client library that is developer-friendly, idiomatic to the Java ecosystem, and as consistent across different languages and platforms as possible. The principles that guide our efforts can be found in the [Azure SDK Design Guidelines for Java](https://aka.ms/azsdk/guide/java). - -For details on the Azure SDK for Java (July 2019 Preview) release, you can refer to the [release announcement](https://aka.ms/azure-sdk-preview1-java). - -This library is not a direct replacement for secrets management operations from microsoft-azure-keyvault. Applications using that library would require code changes to use `azure-keyvault-secrets`. -This package's -[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-keyvault-secrets_4.0.0-preview.1/keyvault/client/secrets/README.md) -and -[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-keyvault-secrets_4.0.0-preview.1/keyvault/client/secrets/src/samples/java) -demonstrate the new API. - -### Major changes from `azure-keyvault` -- Packages scoped by functionality - - `azure-keyvault-secrets` contains a `SecretClient` and `SecretAsyncClient` for secret operations, - `azure-keyvault-keys` contains a `KeyClient` and `KeyAsyncClient` for key operations -- Client instances are scoped to vaults (an instance interacts with one vault -only) -- Reactive streams support using [Project Reactor](https://projectreactor.io/). -- Authentication using `azure-identity` credentials - - see this package's - [documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-keyvault-secrets_4.0.0-preview.1/keyvault/client/secrets/README.md) - , and the - [Azure Identity documentation](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity/README.md) - for more information - -### `azure-keyvault` features not implemented in this library -- Certificate management APIs -- National cloud support. This release supports public global cloud vaults, - e.g. https://{vault-name}.vault.azure.net diff --git a/sdk/keyvault/azure-security-keyvault-secrets/README.md b/sdk/keyvault/azure-security-keyvault-secrets/README.md deleted file mode 100644 index 454266cd92683..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/README.md +++ /dev/null @@ -1,280 +0,0 @@ -# Azure Key Vault Secret client library for Java -Azure Key Vault is a cloud service that provides secure storage for secrets, such as passwords and database connection strings. - -The Azure Key Vault Secrets client library allows you to securely store and tightly control the access to tokens, passwords, API keys, and other secrets. This library offers operations to create, retrieve, update, delete, purge, backup, restore, and list the secrets and its versions. - -Use the Azure Key Vault Secrets client library to create and manage secrets. - -[Source code][source_code] | [API reference documentation][api_documentation] | [Product documentation][azkeyvault_docs] | [Samples][secrets_samples] - -## Getting started -### Include the package -#### Include the BOM file -Please include the `azure-sdk-bom` to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. -To learn more about the BOM, see the [AZURE SDK BOM README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/boms/azure-sdk-bom/README.md). - -```xml - - - - com.azure - azure-sdk-bom - {bom_version_to_target} - pom - import - - - -``` - -and then include the direct dependency in the dependencies section without the version tag as shown below. - -```xml - - - com.azure - azure-security-keyvault-secrets - - -``` - -#### Include direct dependency -If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows. - -[//]: # ({x-version-update-start;com.azure:azure-security-keyvault-secrets;current}) -```xml - - com.azure - azure-security-keyvault-secrets - 4.9.0 - -``` -[//]: # ({x-version-update-end}) - -### Prerequisites - -- A [Java Development Kit (JDK)][jdk_link], version 8 or later. - - Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). -- An [Azure Subscription][azure_subscription]. -- An existing [Azure Key Vault][azure_keyvault]. If you need to create a key vault, you can do so in the Azure Portal by following the steps in [this document][azure_keyvault_portal]. Alternatively, you can use the Azure CLI by following the steps in [this document][azure_keyvault_cli]. - -### Authenticate the client -In order to interact with the Azure Key Vault service, you will need to create an instance of the [`SecretClient`](#create-secret-client) class, a **vault url** and a credential object. The examples shown in this document use a credential object named [`DefaultAzureCredential`][default_azure_credential], which is appropriate for most scenarios, including local development and production environments. Additionally, we recommend using a [managed identity][managed_identity] for authentication in production environments. - -You can find more information on different ways of authenticating and their corresponding credential types in the [Azure Identity documentation][azure_identity]. - -#### Create secret client -Once you perform [the authentication set up that suits you best][default_azure_credential] and replaced **your-key-vault-url** with the URL for your key vault, you can create the `SecretClient`: - -```java readme-sample-createSecretClient -SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); -``` - -> NOTE: For using an asynchronous client use `SecretAsyncClient` instead of `SecretClient` and call `buildAsyncClient()`. - -## Key concepts -### Secret -A secret is the fundamental resource within Azure Key Vault. From a developer's perspective, Key Vault APIs accept and return secret values as strings. In addition to the secret data, the following attributes may be specified: -* enabled: Specifies whether the secret data can be retrieved. -* notBefore: Identifies the time after which the secret will be active. -* expires: Identifies the expiration time on or after which the secret data should not be retrieved. -* created: Indicates when this version of the secret was created. -* updated: Indicates when this version of the secret was updated. - -### Secret client: -The secret client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing secrets and its versions. Asynchronous (`SecretAsyncClient`) and synchronous (`SecretClient`) clients exist in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a secret, you can interact with the primary resource types in Key Vault. - -## Examples -### Sync API -The following sections provide several code snippets covering some of the most common Azure Key Vault Secret service tasks, including: -- [Create a secret](#create-a-secret) -- [Retrieve a secret](#retrieve-a-secret) -- [Update an existing secret](#update-an-existing-secret) -- [Delete a secret](#delete-a-secret) -- [List secrets](#list-secrets) - -### Create a secret -Create a secret to be stored in the Azure Key Vault. -- `setSecret` creates a new secret in the Azure Key Vault. If a secret with the given name already exists then a new version of the secret is created. - -```java readme-sample-createSecret -KeyVaultSecret secret = secretClient.setSecret("", ""); -System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); -``` - -### Retrieve a secret -Retrieve a previously stored secret by calling `getSecret`. - -```java readme-sample-retrieveSecret -KeyVaultSecret secret = secretClient.getSecret(""); -System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); -``` - -### Update an existing secret -Update an existing secret by calling `updateSecretProperties`. - -```java readme-sample-updateSecret -// Get the secret to update. -KeyVaultSecret secret = secretClient.getSecret(""); -// Update the expiry time of the secret. -secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); -SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secret.getProperties()); -System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn()); -``` - -### Delete a secret -Delete an existing secret by calling `beginDeleteSecret`. - -```java readme-sample-deleteSecret -SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); - -// Deleted secret is accessible as soon as polling begins. -PollResponse deletedSecretPollResponse = deletedSecretPoller.poll(); - -// Deletion date only works for a SoftDelete-enabled Key Vault. -System.out.printf("Deletion date: %s%n", deletedSecretPollResponse.getValue().getDeletedOn()); - -// Secret is being deleted on server. -deletedSecretPoller.waitForCompletion(); -``` - -### List secrets -List the secrets in the Azure Key Vault by calling `listPropertiesOfSecrets`. - -```java readme-sample-listSecrets -// List operations don't return the secrets with value information. So, for each returned secret we call getSecret to -// get the secret with its value information. -for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretWithValue.getName(), - secretWithValue.getValue()); -} -``` - -### Async API -The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Secret Service tasks, including: -- [Create a secret asynchronously](#create-a-secret-asynchronously) -- [Retrieve a secret asynchronously](#retrieve-a-secret-asynchronously) -- [Update an existing secret asynchronously](#update-an-existing-secret-asynchronously) -- [Delete a secret asynchronously](#delete-a-secret-asynchronously) -- [List secrets asynchronously](#list-secrets-asynchronously) - -> Note : You should add `System.in.read()` or `Thread.sleep()` after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits. - -### Create a secret asynchronously -Create a secret to be stored in the Azure Key Vault. -- `setSecret` creates a new secret in the Azure Key Vault. If a secret with the given name already exists then a new version of the secret is created. - -```java readme-sample-createSecretAsync -secretAsyncClient.setSecret("", "") - .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", - secret.getName(), secret.getValue())); -``` - -### Retrieve a secret asynchronously -Retrieve a previously stored secret by calling `getSecret`. - -```java readme-sample-retrieveSecretAsync -secretAsyncClient.getSecret("") - .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", - secret.getName(), secret.getValue())); -``` - -### Update an existing secret asynchronously -Update an existing secret by calling `updateSecretProperties`. - -```java readme-sample-updateSecretAsync -secretAsyncClient.getSecret("") - .flatMap(secret -> { - // Update the expiry time of the secret. - secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - return secretAsyncClient.updateSecretProperties(secret.getProperties()); - }).subscribe(updatedSecretProperties -> - System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); -``` - -### Delete a secret asynchronously -Delete an existing secret by calling `beginDeleteSecret`. - -```java readme-sample-deleteSecretAsync -secretAsyncClient.beginDeleteSecret("") - .subscribe(pollResponse -> { - System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); - System.out.printf("Deleted secret name: %s%n", pollResponse.getValue().getName()); - System.out.printf("Deleted secret value: %s%n", pollResponse.getValue().getValue()); - }); -``` - -### List secrets asynchronously -List the secrets in the Azure Key Vault by calling `listPropertiesOfSecrets`. - -```java readme-sample-listSecretsAsync -// The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` -// to get its value as well. -secretAsyncClient.listPropertiesOfSecrets() - .flatMap(secretProperties -> - secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) - .subscribe(secretResponse -> - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), - secretResponse.getValue())); -``` - -## Troubleshooting -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/TROUBLESHOOTING.md) for details on how to diagnose various failure scenarios. - -### General -Azure Key Vault Secret clients raise exceptions. For example, if you try to retrieve a secret after it is deleted a `404` error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. - -```java readme-sample-troubleshooting -try { - secretClient.getSecret(""); -} catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); -} -``` - -### Default HTTP Client -All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the [HTTP clients wiki][http_clients_wiki]. - -### Default SSL library -All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an Uber JAR containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the [performance tuning][performance_tuning] section of the wiki. - -## Next steps -Several Key Vault Java SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure Key Vault. - -## Next steps samples -Samples are explained in detail [here][samples_readme]. - -### Additional documentation -For more extensive documentation on Azure Key Vault, see the [API reference documentation][azkeyvault_rest]. - -## Contributing -This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. - -This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_code_of_conduct]. For more information see the Code of Conduct FAQ or contact with any additional questions or comments. - - -[source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src -[api_documentation]: https://azure.github.io/azure-sdk-for-java -[azkeyvault_docs]: https://learn.microsoft.com/azure/key-vault/ -[azure_identity]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable -[azure_subscription]: https://azure.microsoft.com/ -[azure_keyvault]: https://learn.microsoft.com/azure/key-vault/general/overview -[azure_keyvault_cli]: https://learn.microsoft.com/azure/key-vault/general/quick-create-cli -[azure_keyvault_portal]: https://learn.microsoft.com/azure/key-vault/general/quick-create-portal -[default_azure_credential]: https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#defaultazurecredential -[managed_identity]: https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview -[azkeyvault_rest]: https://learn.microsoft.com/rest/api/keyvault/ -[secrets_samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets -[samples_readme]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md -[performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -[http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients -[microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-secrets%2FREADME.png) diff --git a/sdk/keyvault/azure-security-keyvault-secrets/TROUBLESHOOTING.md b/sdk/keyvault/azure-security-keyvault-secrets/TROUBLESHOOTING.md deleted file mode 100644 index e58f6a0d56117..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/TROUBLESHOOTING.md +++ /dev/null @@ -1,2 +0,0 @@ -# Troubleshooting Azure Key Vault Secrets SDK Issues -See our general [Azure Key Vault SDK Troubleshooting Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/TROUBLESHOOTING.md) to troubleshoot issues common to the Azure Key Vault SDKs for Java. diff --git a/sdk/keyvault/azure-security-keyvault-secrets/assets.json b/sdk/keyvault/azure-security-keyvault-secrets/assets.json deleted file mode 100644 index 2363851274cfb..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/keyvault/azure-security-keyvault-secrets", - "Tag": "java/keyvault/azure-security-keyvault-secrets_5c7c80d234" -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml deleted file mode 100644 index 76f2e5b6e1e59..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/sdk/keyvault/azure-security-keyvault-secrets/migration_guide.md b/sdk/keyvault/azure-security-keyvault-secrets/migration_guide.md deleted file mode 100644 index e083b6fd3de0e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/migration_guide.md +++ /dev/null @@ -1,241 +0,0 @@ -# Guide for migrating to azure-security-keyvault-secrets from azure-keyvault -This guide is intended to assist in the migration to `azure-security-keyvault-secrets` from [deprecated] `azure-keyvault`. It will focus on side-by-side comparisons for similar operations between the two packages. - -Familiarity with the `azure-keyvault` package is assumed. For those new to the Key Vault Secret client library for Java, please refer to the [README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) rather than this guide. - -## Table of contents -- [Migration benefits](#migration-benefits) -- [Cross Service SDK improvements](#cross-service-sdk-improvements) -- [Important changes](#important-changes) - - [Separate packages and clients](#separate-packages-and-clients) - - [Package names and namespaces](#package-names-and-namespaces) - - [Client instantiation](#client-instantiation) - - [Authentication](#authentication) - - [Common scenarios](#common-scenarios) - - [Async operations](#async-operations) - - [Create a secret](#create-a-secret) - - [Retrieve a secret](#retrieve-a-secret) - - [List properties of secrets](#list-properties-of-secrets) - - [Delete a secret](#delete-a-secret) -- [Additional samples](#additional-samples) -- [Support](#support) - -## Migration benefits -A natural question to ask when considering whether or not to adopt a new version or library is what the benefits of doing so would be. As Azure has matured and been embraced by a more diverse group of developers, we have been focused on learning the patterns and practices to best support developer productivity and to understand the gaps that the Java client libraries have. - -There were several areas of consistent feedback expressed across the Azure client library ecosystem. One of the most important is that the client libraries for different Azure services have not had a consistent approach to organization, naming, and API structure. Additionally, many developers have felt that the learning curve was difficult, and the APIs did not offer a good, approachable, and consistent onboarding story for those learning Azure or exploring a specific Azure service. - -To try and improve the development experience across Azure services, a set of uniform [design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) was created for all languages to drive a consistent experience with established API patterns for all services. A set of [Java-specific guidelines](https://azure.github.io/azure-sdk/java_introduction.html) was also introduced to ensure that Java clients have a natural and idiomatic feel with respect to the Java ecosystem. Further details are available in the guidelines for those interested. - -### Cross Service SDK improvements -The modern Key Vault Secret client library also provides the ability to share in some of the cross-service improvements made to the Azure development experience, such as: - -- Using the new Azure Identity library to share a single authentication approach between clients. -- A unified logging and diagnostics pipeline offering a common view of the activities across each of the client libraries. - -## Important changes -### Separate packages and clients -In the interest of simplifying the API for working with Key Vault certificates, keys and secrets, the `azure-keyvault` was split into separate packages: - -- [`azure-security-keyvault-certificates`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) contains `CertificateClient` for working with Key Vault certificates. -- [`azure-security-keyvault-keys`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) contains `KeyClient` for working with Key Vault keys and `CryptographyClient` for performing cryptographic operations. -- `azure-security-keyvault-secrets` contains `SecretClient` for working with Key Vault secrets. - -### Package names and namespaces -Package names and the namespace root for the modern Azure client libraries for Java have changed. Each will follow the pattern `com.azure..` where the legacy clients followed the pattern `com.microsoft.azure.`. This provides a quick and accessible means to help understand, at a glance, whether you are using the modern or legacy clients. - -In the case of the Key Vault, the modern client libraries have packages and namespaces that begin with `com.azure.security.keyvault` and were released beginning with version `4.0.0`. The legacy client libraries have packages and namespaces that begin with `com.microsoft.azure.keyvault` and a version of `1.x.x` or below. - -### Client instantiation -Previously in `azure-keyvault` you could create a `KeyVaultClient`, via a public constructor that took an authentication delegate and could be used for multiple Key Vault endpoints. - -```java -import com.microsoft.azure.keyvault.KeyVaultClient; -import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; - -KeyVaultCredentials keyVaultCredentials = new MyKeyVaultCredentials("", ""); -KeyVaultClient keyVaultClient = new KeyVaultClient(keyVaultCredentials); -``` - -Now, across all modern Azure client libraries, client instances are created via builders, which consistently take an endpoint or connection string along with token credentials. This means that you can use a single client builder to instantiate multiple clients that share some configuration. - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.SecretClientBuilder; - -TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); -SecretClientBuilder secretClientBuilder = new SecretClientBuilder() - .vaultUrl("") - .credential(tokenCredential); - -// Create a client. -SecretClient someSecretClient = secretClientBuilder.buildClient(); - -// Create a client with the same configuration, plus some more. -SecretClient anotherSecretClient = secretClientBuilder - .addPolicy(new AddDatePolicy()) - .buildClient(); -``` - -### Authentication -Previously in `azure-keyvault` you could create a `KeyVaultClient` by passing either a `KeyVaultCredential` or `RestClient` from `client-runtime`: - -```java -import com.microsoft.azure.keyvault.KeyVaultClient; -import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials; - -KeyVaultCredentials keyVaultCredentials = new MyKeyVaultCredentials("", ""); -KeyVaultClient keyVaultClient = new KeyVaultClient(keyVaultCredentials); -``` - -Now in `azure-security-keyvault-secrets` you can create a `SecretClient` using any credential from [`azure-identity`](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md). Below is an example using [`DefaultAzureCredential`](https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#defaultazurecredential): - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.SecretClientBuilder; - -TokenCredential tokenCredentials = new DefaultAzureCredentialBuilder().build(); - -SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(tokenCredential) - .buildClient(); -``` - -### Async operations -The modern `azure-security-keyvault-secrets` library includes a complete set of async APIs that return [Project Reactor-based types](https://projectreactor.io/), as opposed to `azure-keyvault` async APIs that return either [Observable](https://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html) or [ServiceFuture](https://azure.github.io/ref-docs/java/com/microsoft/rest/ServiceFuture.html). - -Another difference is that async operations are available on their own separate async clients, which include the word `Async` in their name, like `SecretAsyncClient`. - -All modern Azure async clients can be created virtually the same way as sync clients, with the slight difference of calling `buildAsyncClient` on the client builder instead of `buildClient`: - -```java -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.SecretClientBuilder; - -TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); -SecretClientBuilder secretClientBuilder = new SecretClientBuilder() - .vaultUrl("") - .credential(tokenCredential); - -// To create an async client. -SecretAsyncClient secretAsyncClient = secretClientBuilder.buildAsyncClient(); - -// To create a sync client. -SecretClient secretClient = secretClientBuilder.buildClient(); -``` - -### Common scenarios -#### Create a secret -In `azure-keyvault` you could set a secret by using `KeyVaultClient`'s `setSecret` method, which required a vault endpoint, secret name, and secret value. This method returned a `SecretBundle` containing the secret. - -```java -String keyVaultUrl = "https://.vault.azure.net/"; - -SecretBundle secret = keyVaultClient.setSecret(keyVaultUrl, "", "secret-value"); -``` - -Now in `azure-security-keyvault-secrets` there are couple ways to create secrets: you can provide either a secret name and value or a `KeyVaultSecret` object to the `setSecret` method. These methods all return the created secret as a `KeyVaultSecret`. - -```java -// Create a secret by providing name and value. -KeyVaultSecret secret = secretClient.setSecret("", ""); - -// Create a secret by providing a KeyVaultSecret object. -KeyVaultSecret anotherSecret = secretClient.setSecret(new KeyVaultSecret("", "")); -``` - -#### Retrieve a secret -In `azure-keyvault` you could retrieve a secret (in a `SecretBundle`) by using `getSecret` in one of the following ways: - -- Using the desired key vault endpoint and secret name to get the latest version of a secret. -- Using the desired key vault endpoint, secret name and secret version to get a specific secret version. -- Using the secret identifier to get a specific secret version. - -Additionally, you could list the properties of the versions of a secret with the `getSecretVersions` method, which returned a `PagedList` of `SecretItem`. - -```java -String keyVaultUrl = "https://.vault.azure.net/"; - -// Get a secret's latest version. -SecretBundle secret = keyVaultClient.getSecret(keyVaultUrl, ""); - -// Get a secret's specific version. -SecretBundle secretVersion = keyVaultClient.getSecret(keyVaultUrl, "", ""); - -// Get a secret's specific version using its id. -String secretIdentifier = "https://.vault.azure.net/secrets//"; -SecretBundle secretWithId = keyVaultClient.getSecret(secretIdentifier); - -// Get a key's versions. -PagedList secretVersions = keyVaultClient.getSecretVersions(keyVaultUrl, ""); -``` - -Now in `azure-security-keyvault-secrets` you can retrieve a secret (as a `KeyVaultSecret`) by using `getSecret` in one of the following ways: - -- Using the secret name to get the latest version of the secret. -- Using the secret name and secret version to get a specific version of the secret. - -Additionally, you con list the properties of the versions of a secret with the `getSecretVersions` method, which returned a `PagedIterable` of `SecretProperties`. - -```java -// Get a secret's latest version. -KeyVaultSecret secret = secretClient.getSecret(""); - -// Get a secret's specific version. -KeyVaultSecret secretVersion = secretClient.getSecret("", ""); - -// Get a secret's versions' properties. -PagedIterable secretVersionsProperties = secretClient.listPropertiesOfSecretVersions(""); -``` - -#### List properties of secrets -In `azure-keyvault` you could list the properties of secrets in a specified vault with the `getSecrets` methods. This returned a `PagedList` containing `SecretItem` instances. - -```java -PagedList secretsProperties = keyVaultClient.getSecrets(keyVaultUrl); -``` - -Now in `azure-security-keyvault-secrets` you can list the properties of secrets in a vault with the `listPropertiesOfSecrets` method. This returns an iterator-like object containing `SecretProperties` instances. - -```java -PagedIterable secretsProperties = secretClient.listPropertiesOfSecrets(); -``` - -#### Delete a secret -In `azure-keyvault` you could delete all versions of a secret with the `deleteSecret` method. This returned information about the deleted secret (as a `DeletedSecretBundle`), but you could not poll the deletion operation to know when it completed. This would be valuable information if you intended to permanently delete the deleted secret with `purgeDeletedSecret`. - -```java -DeletedSecretBundle deletedSecret = keyVaultClient.deleteSecret(keyVaultUrl, ""); - -// This purge would fail if deletion hadn't finished -keyVaultClient.purgeDeletedSecret(keyVaultUrl, ""); -``` - -Now in `azure-security-keyvault-secrets` you can delete a secret with `beginDeleteSecret`, which returns a long operation poller object that can be used to wait/check on the operation. Calling `poll` on the poller will return information about the deleted secret (as a `DeletedSecret`) without waiting for the operation to complete, but calling `waitForCompletion` will wait for the deletion to complete. Again, `purgeDeletedSecret` will permanently delete your deleted secret and make it unrecoverable. - -```java -SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); -PollResponse pollResponse = deletedSecretPoller.poll(); -DeletedSecret deletedSecret = pollResponse.getValue(); - -// Wait for completion before attempting to purge the secret. -deletedSecretPoller.waitForCompletion(); -secretClient.purgeDeletedSecret(""); -``` - -## Additional samples -More examples can be found [here](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples). - -## Support - -If you have migrated your code base and experiencing errors, see our [troubleshooting guide][troubleshooting_guide]. For additional support, please search our [existing issues][existing_issues] or [open a new issue][open_new_issue]. You may also find existing answers on community sites like [Stack Overflow]. - -[deprecated]: https://aka.ms/azsdk/deprecated -[existing_issues]: https://github.com/Azure/azure-sdk-for-java/issues -[open_new_issue]: https://github.com/Azure/azure-sdk-for-java/issues/new/choose -[stack_overflow]: https://stackoverflow.com/questions/tagged/azure-keyvault+java -[troubleshooting_guide]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/TROUBLESHOOTING.md diff --git a/sdk/keyvault/azure-security-keyvault-secrets/perf-tests.yml b/sdk/keyvault/azure-security-keyvault-secrets/perf-tests.yml deleted file mode 100644 index d63c3f4267863..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/perf-tests.yml +++ /dev/null @@ -1,31 +0,0 @@ -Service: keyvault-secrets - -Project: sdk/keyvault/azure-security-keyvault-perf - -PrimaryPackage: 'com.azure:azure-security-keyvault-secrets' - -PackageVersions: -- 'com.azure:azure-security-keyvault-certificates': 4.6.6 # {x-version-update;com.azure:azure-security-keyvault-certificates;dependency} - 'com.azure:azure-security-keyvault-keys': 4.8.7 # {x-version-update;com.azure:azure-security-keyvault-keys;dependency} - 'com.azure:azure-security-keyvault-secrets': 4.8.6 # {x-version-update;com.azure:azure-security-keyvault-secrets;dependency} - 'com.azure:azure-core': 1.51.0 # {x-version-update;com.azure:azure-core;dependency} - 'com.azure:azure-core-http-netty': 1.15.3 # {x-version-update;com.azure:azure-core-http-netty;dependency} - 'com.azure:azure-identity': 1.13.2 # {x-version-update;com.azure:azure-identity;dependency} -- 'com.azure:azure-security-keyvault-certificates': source - 'com.azure:azure-security-keyvault-keys': source - 'com.azure:azure-security-keyvault-secrets': source - 'com.azure:azure-core': source - 'com.azure:azure-core-http-netty': source - 'com.azure:azure-identity': source - -Tests: -- Test: get-secret - Class: getsecret - Arguments: - - --parallel 64 - -- Test: list-secrets - Class: listsecrets - Arguments: - - --count 5 --parallel 64 - - --count 500 --parallel 32 diff --git a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml deleted file mode 100644 index 7d12c9d2baeca..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - 4.0.0 - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - com.azure - azure-security-keyvault-secrets - 4.10.0-beta.1 - - Microsoft Azure client library for KeyVault Secrets - This module contains client library for Microsoft Azure KeyVault Secrets. - https://github.com/Azure/azure-sdk-for-java - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - scm:git:https://github.com/Azure/azure-sdk-for-java - scm:git:git@github.com:Azure/azure-sdk-for-java.git - HEAD - - - - - - --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED - --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - - --add-opens com.azure.security.keyvault.secrets/com.azure.security.keyvault.secrets=ALL-UNNAMED - --add-opens com.azure.security.keyvault.secrets/com.azure.security.keyvault.secrets.implementation=ALL-UNNAMED - --add-opens com.azure.security.keyvault.secrets/com.azure.security.keyvault.secrets.models=ALL-UNNAMED - - - checkstyle-suppressions.xml - false - spotbugs-exclude.xml - - - - - com.azure - azure-core - 1.54.1 - - - - com.azure - azure-json - 1.3.0 - - - - com.azure - azure-core-http-netty - 1.15.7 - - - - - com.azure - azure-core-test - 1.27.0-beta.4 - test - - - - com.azure - azure-identity - 1.15.0 - test - - - diff --git a/sdk/keyvault/azure-security-keyvault-secrets/spotbugs-exclude.xml b/sdk/keyvault/azure-security-keyvault-secrets/spotbugs-exclude.xml deleted file mode 100644 index cb6006dcb501b..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/spotbugs-exclude.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java deleted file mode 100644 index 7c036867fce02..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java +++ /dev/null @@ -1,1048 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.PollingContext; -import com.azure.security.keyvault.secrets.implementation.SecretClientImpl; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretItem; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.implementation.models.SecretItem; -import com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createDeletedSecret; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createKeyVaultSecret; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretAttributes; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretProperties; - -/** - * The SecretAsyncClient provides asynchronous methods to manage {@link KeyVaultSecret secrets} in the Azure Key Vault. - * The client supports creating, retrieving, updating, deleting, purging, backing up, restoring, and listing the - * {@link KeyVaultSecret secrets}. The client also supports listing {@link DeletedSecret deleted secrets} for a - * soft-delete enabled key vault. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Asynchronous Secret Client

- * - * - *
- * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *
- * - *

Create a Secret

- * The {@link SecretAsyncClient} can be used to create a secret in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to create and store a secret in the key vault, using the - * {@link SecretAsyncClient#setSecret(String, String)} API.

- * - * - *
- * secretAsyncClient.setSecret("secretName", "secretValue")
- *     .subscribe(secretResponse ->
- *         System.out.printf("Secret is created with name %s and value %s%n",
- *             secretResponse.getName(), secretResponse.getValue()));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link SecretClient}.

- * - *
- * - *
- * - *

Get a Secret

- * The {@link SecretAsyncClient} can be used to retrieve a secret from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously retrieve a previously stored secret from the - * key vault, using the {@link SecretAsyncClient#getSecret(String)} API.

- * - * - *
- * secretAsyncClient.getSecret("secretName")
- *     .subscribe(secretWithVersion ->
- *         System.out.printf("Secret is returned with name %s and value %s %n",
- *             secretWithVersion.getName(), secretWithVersion.getValue()));
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link SecretClient}.

- * - *
- * - *
- * - *

Delete a Secret

- * The {@link SecretAsyncClient} can be used to delete a secret from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to delete a secret from the key vault, using the - * {@link SecretAsyncClient#beginDeleteSecret(String)} API.

- * - * - *
- * secretAsyncClient.beginDeleteSecret("secretName")
- *     .subscribe(pollResponse -> {
- *         System.out.println("Delete Status: " + pollResponse.getStatus().toString());
- *         System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName());
- *         System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue());
- *     });
- * 
- * - * - *

Note: For the synchronous sample, refer to {@link SecretClient}.

- * - * @see SecretClientBuilder - * @see PollerFlux - * @see PagedFlux - */ -@ServiceClient( - builder = SecretClientBuilder.class, - isAsync = true, - serviceInterfaces = SecretClientImpl.SecretClientService.class) -public final class SecretAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SecretAsyncClient.class); - - private final SecretClientImpl implClient; - private final String vaultUrl; - - /** - * Creates a SecretAsyncClient to service requests - * - * @param implClient the implementation client. - * @param vaultUrl the vault url. - */ - SecretAsyncClient(SecretClientImpl implClient, String vaultUrl) { - this.implClient = implClient; - this.vaultUrl = vaultUrl; - } - - /** - * Gets the vault endpoint url to which service requests are sent to. - * @return the vault endpoint url. - */ - public String getVaultUrl() { - return vaultUrl; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return implClient.getHttpPipeline(); - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

The {@link SecretProperties#getExpiresOn() expires}, {@link SecretProperties#getContentType() contentType}, - * and {@link SecretProperties#getNotBefore() notBefore} values in {@code secret} are optional. - * If not specified, {@link SecretProperties#isEnabled() enabled} is set to true by key vault.

- * - *

Code sample

- *

Creates a new secret which activates in one day and expires in one year. Subscribes to the call asynchronously - * and prints out the newly created secret details when a response is received.

- * - * - *
-     * SecretProperties properties = new SecretProperties()
-     *     .setExpiresOn(OffsetDateTime.now().plusDays(60));
-     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
-     *     .setProperties(properties);
-     *
-     * secretAsyncClient.setSecret(newSecret)
-     *     .subscribe(secretResponse ->
-     *         System.out.printf("Secret is created with name %s and value %s %n",
-     *             secretResponse.getName(), secretResponse.getValue()));
-     * 
- * - * - * @param secret The Secret object containing information about the secret and its properties. The properties - * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be null. - * @return A {@link Mono} containing the {@link KeyVaultSecret created secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceModifiedException if {@code secret} is malformed. - * @throws HttpResponseException if {@link KeyVaultSecret#getName() name} or {@link KeyVaultSecret#getValue() value} - * is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecret(KeyVaultSecret secret) { - return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

Code sample

- *

Creates a new secret in the key vault. Subscribes to the call asynchronously and prints out - * the newly created secret details when a response is received.

- * - *
-     * secretAsyncClient.setSecret("secretName", "secretValue")
-     *     .subscribe(secretResponse ->
-     *         System.out.printf("Secret is created with name %s and value %s%n",
-     *             secretResponse.getName(), secretResponse.getValue()));
-     * 
- * - * - * @param name The name of the secret. It is required and cannot be null. - * @param value The value of the secret. It is required and cannot be null. - * @return A {@link Mono} containing the {@link KeyVaultSecret created secret}. - * @throws ResourceModifiedException if invalid {@code name} or {@code value} are specified. - * @throws HttpResponseException if {@code name} or {@code value} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecret(String name, String value) { - return setSecretWithResponse(new KeyVaultSecret(name, value)).flatMap(FluxUtil::toMono); - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

The {@link SecretProperties#getExpiresOn() expires}, {@link SecretProperties#getContentType() contentType}, - * and {@link SecretProperties#getNotBefore() notBefore} values in {@code secret} are optional. - * If not specified, {@link SecretProperties#isEnabled() enabled} is set to true by key vault.

- * - *

Code sample

- *

Creates a new secret which activates in one day and expires in one year. Subscribes to the call asynchronously - * and prints out the newly created secret details when a response is received.

- * - * - *
-     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue").
-     *     setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
-     * secretAsyncClient.setSecretWithResponse(newSecret)
-     *     .subscribe(secretResponse ->
-     *         System.out.printf("Secret is created with name %s and value %s %n",
-     *             secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
-     * 
- * - * - * @param secret The Secret object containing information about the secret and its properties. The properties - * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be null. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSecret created secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceModifiedException if {@code secret} is malformed. - * @throws HttpResponseException if {@link KeyVaultSecret#getName() name} or {@link KeyVaultSecret#getValue() value} - * is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponse(KeyVaultSecret secret) { - try { - SecretProperties secretProperties = secret.getProperties(); - if (secretProperties == null) { - return implClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), null, null, null) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapSetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } else { - return implClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), - secretProperties.getTags(), secretProperties.getContentType(), - createSecretAttributes(secretProperties)) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapSetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // For backwards compatibility with the exception type mapping of the handwritten KeyVault Secrets REST proxy. - // Only specific error codes are mapped to certain HttpResponseException subclasses, the default before was - // HttpResponseException and the new default is KeyVaultErrorException which is a subclass of HttpResponseException - // and is a non-breaking change. Specific error codes used different subclasses of HttpResponseException and that - // is a breaking change, so this mapping preserves the old behavior. - static HttpResponseException mapSetSecretException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - /** - * Gets the latest version of the specified secret from the key vault. This operation requires the - * {@code secrets/get} permission. - * - *

Code sample

- *

Gets latest version of the secret in the key vault. Subscribes to the call asynchronously and prints out the - * returned secret details when a response is received.

- * - *
-     * secretAsyncClient.getSecret("secretName")
-     *     .subscribe(secretWithVersion ->
-     *         System.out.printf("Secret is returned with name %s and value %s %n",
-     *             secretWithVersion.getName(), secretWithVersion.getValue()));
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link Mono} containing the requested {@link KeyVaultSecret secret}. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. - * @throws HttpResponseException If the server reports an error when executing the request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecret(String name) { - return getSecretWithResponse(name, null).flatMap(FluxUtil::toMono); - } - - /** - * Gets the specified secret with specified version from the key vault. This operation requires the - * {@code secrets/get} permission. - * - *

Code sample

- *

Gets a specific version of the secret in the key vault. Subscribes to the call - * asynchronously and prints out the returned secret details when a response is received.

- * - * - *
-     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * secretAsyncClient.getSecret("secretName", secretVersion)
-     *     // Passing a Context is optional and useful if you want a set of data to flow through the request.
-     *     // Otherwise, the line below can be removed.
-     *     .contextWrite(Context.of(key1, value1, key2, value2))
-     *     .subscribe(secretWithVersion ->
-     *         System.out.printf("Secret is returned with name %s and value %s %n",
-     *             secretWithVersion.getName(), secretWithVersion.getValue()));
-     * 
- * - * - * @param name The name of the secret, cannot be null. - * @param version The version of the secret to retrieve. If this is an empty string or null, this - * call is equivalent to calling {@link #getSecret(String)}, with the latest version being retrieved. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * requested {@link KeyVaultSecret secret}. - * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in - * the vault. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - * @throws HttpResponseException If the server reports an error when executing the request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecret(String name, String version) { - return getSecretWithResponse(name, version).flatMap(FluxUtil::toMono); - } - - /** - * Gets the specified secret with specified version from the key vault. This operation requires the - * {@code secrets/get} permission. - * - *

Code sample

- *

Gets a specific version of the secret in the key vault. Subscribes to the call asynchronously and prints out - * the returned secret details when a response is received.

- * - *
-     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * secretAsyncClient.getSecretWithResponse("secretName", secretVersion)
-     *     // Passing a Context is optional and useful if you want a set of data to flow through the request.
-     *     // Otherwise, the line below can be removed.
-     *     .contextWrite(Context.of(key1, value1, key2, value2))
-     *     .subscribe(secretWithVersion ->
-     *         System.out.printf("Secret is returned with name %s and value %s %n",
-     *             secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue()));
-     * 
- * - * - * @param name The name of the secret, cannot be null. - * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent - * to calling {@link #getSecret(String)}, with the latest version being retrieved. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * requested {@link KeyVaultSecret secret}. - * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in - * the vault. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - * @throws HttpResponseException If the server reports an error when executing the request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponse(String name, String version) { - if (CoreUtils.isNullOrEmpty(name)) { - return monoError(LOGGER, new IllegalArgumentException("'name' cannot be null or empty.")); - } - - try { - return implClient.getSecretWithResponseAsync(vaultUrl, name, version) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapGetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapGetSecretException(HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } - } - - /** - * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. - * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are - * not changed. This operation requires the {@code secrets/set} permission. - * - *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} cannot be null.

- * - *

Code sample

- *

Gets latest version of the secret, changes its {@link SecretProperties#setNotBefore(OffsetDateTime) notBefore} - * time, and then updates it in the Azure Key Vault. Subscribes to the call asynchronously and prints out the - * returned secret details when a response is received.

- * - * - *
-     * secretAsyncClient.getSecret("secretName")
-     *     .subscribe(secretResponseValue -> {
-     *         SecretProperties secretProperties = secretResponseValue.getProperties();
-     *         //Update the not before time of the secret.
-     *         secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50));
-     *         secretAsyncClient.updateSecretProperties(secretProperties)
-     *             .subscribe(secretResponse ->
-     *                 System.out.printf("Secret's updated not before time %s %n",
-     *                     secretResponse.getNotBefore().toString()));
-     *     });
-     * 
- * - * - * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. - * @return A {@link Mono} containing the {@link SecretProperties updated secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. - * @throws HttpResponseException if {@link SecretProperties#getName() name} or - * {@link SecretProperties#getVersion() version} is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSecretProperties(SecretProperties secretProperties) { - return updateSecretPropertiesWithResponse(secretProperties).flatMap(FluxUtil::toMono); - } - - /** - * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. - * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are - * not changed. This operation requires the {@code secrets/set} permission. - * - *

Code sample

- *

Gets latest version of the secret, changes its {@link SecretProperties#setNotBefore(OffsetDateTime) notBefore} - * time, and then updates it in the Azure Key Vault. Subscribes to the call asynchronously and prints out the - * returned secret details when a response is received.

- * - * - *
-     * secretAsyncClient.getSecret("secretName")
-     *     .subscribe(secretResponseValue -> {
-     *         SecretProperties secretProperties = secretResponseValue.getProperties();
-     *         //Update the not before time of the secret.
-     *         secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50));
-     *         secretAsyncClient.updateSecretPropertiesWithResponse(secretProperties)
-     *             .subscribe(secretResponse ->
-     *                 System.out.printf("Secret's updated not before time %s %n",
-     *                     secretResponse.getValue().getNotBefore().toString()));
-     *     });
-     * 
- * - * - *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} cannot be null.

- * - * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link SecretProperties updated secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. - * @throws HttpResponseException if {@link SecretProperties#getName() name} or - * {@link SecretProperties#getVersion() version} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSecretPropertiesWithResponse(SecretProperties secretProperties) { - try { - return implClient - .updateSecretWithResponseAsync(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), - secretProperties.getContentType(), createSecretAttributes(secretProperties), - secretProperties.getTags()) - .map(response -> new SimpleResponse<>(response, createSecretProperties(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the - * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. - * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. - * This operation requires the {@code secrets/delete} permission. - * - *

Code sample

- *

Deletes the secret in the Azure Key Vault. Subscribes to the call asynchronously and prints out the deleted - * secret details when a response is received.

- * - *
-     * secretAsyncClient.beginDeleteSecret("secretName")
-     *     .subscribe(pollResponse -> {
-     *         System.out.println("Delete Status: " + pollResponse.getStatus().toString());
-     *         System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName());
-     *         System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue());
-     *     });
-     * 
- * - * - * @param name The name of the secret to be deleted. - * @return A {@link PollerFlux} to poll on and retrieve {@link DeletedSecret deleted secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginDeleteSecret(String name) { - return new PollerFlux<>(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), - (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); - } - - private Function, Mono> deleteActivationOperation(String name) { - return pollingContext -> implClient.deleteSecretAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapDeleteSecretException) - .map(SecretsModelsUtils::createDeletedSecret); - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapDeleteSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - private Function, Mono>> - deletePollOperation(String name) { - return pollingContext -> implClient.getDeletedSecretAsync(vaultUrl, name) - .map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedSecret(bundle))) - .onErrorResume(HttpResponseException.class, exception -> { - if (exception.getResponse().getStatusCode() == 404) { - return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, - pollingContext.getLatestResponse().getValue())); - } else { - // This means either vault has soft-delete disabled or permission is not granted for the get deleted - // key operation. In both cases deletion operation was successful when activation operation - // succeeded before reaching here. - return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue())); - } - }) - // This means either vault has soft-delete disabled or permission is not granted for the get deleted key - // operation. In both cases deletion operation was successful when activation operation succeeded before - // reaching here. - .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue())); - } - - /** - * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the - * {@code secrets/list} permission. - * - *

Code sample

- *

Gets the deleted secret from the key vault enabled for soft-delete. Subscribes to the call - * asynchronously and prints out the deleted secret details when a response is received.

- * - * - *
-     * secretAsyncClient.getDeletedSecret("secretName")
-     *     .subscribe(deletedSecretResponse ->
-     *         System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId()));
-     * 
- * - * - * @param name The name of the deleted secret. - * @return A {@link Mono} containing the {@link DeletedSecret deleted secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedSecret(String name) { - return getDeletedSecretWithResponse(name).flatMap(FluxUtil::toMono); - } - - /** - * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the - * {@code secrets/list} permission. - * - *

Code sample

- *

Gets the deleted secret from the key vault enabled for soft-delete. Subscribes to the call - * asynchronously and prints out the deleted secret details when a response is received.

- * - * - *
-     * secretAsyncClient.getDeletedSecretWithResponse("secretName")
-     *     .subscribe(deletedSecretResponse ->
-     *         System.out.printf("Deleted Secret's Recovery Id %s %n",
-     *             deletedSecretResponse.getValue().getRecoveryId()));
-     * 
- * - * - * @param name The name of the deleted secret. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link DeletedSecret deleted secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretWithResponse(String name) { - try { - return implClient.getDeletedSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapGetDeletedSecretException) - .map(response -> new SimpleResponse<>(response, createDeletedSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapGetDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - /** - * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed - * on a soft-delete enabled. This operation requires the {@code secrets/purge} permission. - * - *

Code sample

- *

Purges the deleted secret from the key vault enabled for soft-delete. Subscribes to the call - * asynchronously and prints out the status code from the server response when a response is received.

- * - * - *
-     * secretAsyncClient.purgeDeletedSecret("deletedSecretName")
-     *     .doOnSuccess(purgeResponse ->
-     *         System.out.println("Successfully Purged deleted Secret"))
-     *     .subscribe();
-     * 
- * - * - * @param name The name of the secret. - * @return An empty {@link Mono}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedSecret(String name) { - return purgeDeletedSecretWithResponse(name).flatMap(FluxUtil::toMono); - } - - /** - * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be enabled on - * a soft-delete enabled vault. This operation requires the {@code secrets/purge} permission. - * - *

Code sample

- *

Purges the deleted secret from the key vault enabled for soft-delete. Subscribes to the call - * asynchronously and prints out the status code from the server response when a response is received.

- * - * - *
-     * secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName")
-     *     .subscribe(purgeResponse ->
-     *         System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode()));
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link Mono} containing a Response containing status code and HTTP headers. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedSecretWithResponse(String name) { - try { - return implClient.purgeDeletedSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapPurgeDeletedSecretException); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapPurgeDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - /** - * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a soft-delete - * enabled vault. This operation requires the {@code secrets/recover} permission. - * - *

Code sample

- *

Recovers the deleted secret from the key vault enabled for soft-delete. Subscribes to the call - * asynchronously and prints out the recovered secret details when a response is received.

- * - * - *
-     * secretAsyncClient.beginRecoverDeletedSecret("deletedSecretName")
-     *     .subscribe(pollResponse -> {
-     *         System.out.println("Recovery Status: " + pollResponse.getStatus().toString());
-     *         System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName());
-     *         System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue());
-     *     });
-     * 
- * - * - * @param name The name of the deleted secret to be recovered. - * @return A {@link PollerFlux} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public PollerFlux beginRecoverDeletedSecret(String name) { - return new PollerFlux<>(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), - (context, firstResponse) -> Mono.empty(), context -> Mono.empty()); - } - - private Function, Mono> recoverActivationOperation(String name) { - return pollingContext -> implClient.recoverDeletedSecretAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapRecoverDeletedSecretException) - .map(SecretsModelsUtils::createKeyVaultSecret); - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapRecoverDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - private Function, Mono>> - recoverPollOperation(String name) { - return pollingContext -> implClient.getSecretWithResponseAsync(vaultUrl, name, null) - .map(response -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultSecret(response.getValue()))) - .onErrorResume(HttpResponseException.class, exception -> { - if (exception.getResponse().getStatusCode() == 404) { - return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, - pollingContext.getLatestResponse().getValue())); - } else { - // This means permission is not granted for the get deleted key operation. In both cases the - // deletion operation was successful when activation operation succeeded before reaching here. - return Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue())); - } - }) - // This means permission is not granted for the get deleted key operation. In both cases the deletion - // operation was successful when activation operation succeeded before reaching here. - .onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue())); - } - - /** - * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. This - * operation requires the {@code secrets/backup} permission. - * - *

Code sample

- *

Backs up the secret from the key vault. Subscribes to the call asynchronously and prints out - * the length of the secret's backup byte array returned in the response.

- * - * - *
-     * secretAsyncClient.backupSecret("secretName")
-     *     .subscribe(secretBackupResponse ->
-     *         System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.length));
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link Mono} containing the backed up secret blob. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupSecret(String name) { - return backupSecretWithResponse(name).flatMap(FluxUtil::toMono); - } - - /** - * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. This - * operation requires the {@code secrets/backup} permission. - * - *

Code sample

- *

Backs up the secret from the key vault. Subscribes to the call asynchronously and prints out - * the length of the secret's backup byte array returned in the response.

- * - * - *
-     * secretAsyncClient.backupSecretWithResponse("secretName")
-     *     .subscribe(secretBackupResponse ->
-     *         System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.getValue().length));
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * backed up secret blob. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupSecretWithResponse(String name) { - try { - return implClient.backupSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapBackupSecretException) - .map(response -> new SimpleResponse<>(response, response.getValue().getValue())); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapBackupSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - /** - * Restores a backed up secret, and all its versions, to a vault. This operation requires the - * {@code secrets/restore} permission. - * - *

Code sample

- *

Restores the secret in the key vault from its backup. Subscribes to the call asynchronously - * and prints out the restored secret details when a response is received.

- * - * - *
-     * // Pass the secret backup byte array to the restore operation.
-     * byte[] secretBackupByteArray = {};
-     * secretAsyncClient.restoreSecretBackup(secretBackupByteArray)
-     *     .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
-     *         secretResponse.getName(), secretResponse.getValue()));
-     * 
- * - * - * @param backup The backup blob associated with the secret. - * @return A {@link Mono} containing the {@link KeyVaultSecret restored secret}. - * @throws ResourceModifiedException when {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreSecretBackup(byte[] backup) { - return restoreSecretBackupWithResponse(backup).flatMap(FluxUtil::toMono); - } - - /** - * Restores a backed up secret, and all its versions, to a vault. This operation requires the - * {@code secrets/restore} permission. - * - *

Code sample

- *

Restores the secret in the key vault from its backup. Subscribes to the call asynchronously - * and prints out the restored secret details when a response is received.

- * - * - *
-     * // Pass the secret backup byte array to the restore operation.
-     * byte[] secretBackupByteArray = {};
-     * secretAsyncClient.restoreSecretBackupWithResponse(secretBackupByteArray)
-     *     .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n",
-     *         secretResponse.getValue().getName(), secretResponse.getValue().getValue()));
-     * 
- * - * - * @param backup The backup blob associated with the secret. - * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSecret restored secret}. - * @throws ResourceModifiedException when {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreSecretBackupWithResponse(byte[] backup) { - try { - return implClient.restoreSecretWithResponseAsync(vaultUrl, backup) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapRestoreSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapRestoreSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - - /** - * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and - * attributes populated. The secret values and their versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Code sample

- *

The sample below fetches the all the secret properties in the vault. For each secret retrieved, makes a call - * to {@link #getSecret(String, String) getSecret(String, String)} to get its value, and then prints it out.

- * - * - *
-     * secretAsyncClient.listPropertiesOfSecrets()
-     *     .flatMap(secretProperties -> {
-     *         String name = secretProperties.getName();
-     *         String version = secretProperties.getVersion();
-     *
-     *         System.out.printf("Getting secret name: '%s', version: %s%n", name, version);
-     *         return secretAsyncClient.getSecret(name, version);
-     *     })
-     *     .subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s",
-     *         secretResponse.getName(), secretResponse.getValue()));
-     * 
- * - * - * @return A {@link PagedFlux} containing {@link SecretProperties properties} of all the secrets in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listPropertiesOfSecrets() { - return new PagedFlux<>( - maxResults -> implClient.getSecretsSinglePageAsync(vaultUrl, maxResults) - .map(SecretAsyncClient::mapSecretItemPage), - (continuationToken, maxResults) -> implClient.getSecretsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapSecretItemPage)); - } - - /** - * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation - * requires the {@code secrets/list} permission. - * - *

Code sample

- *

Lists the deleted secrets in the key vault. Subscribes to the call asynchronously and prints out the - * recovery id of each deleted secret when a response is received.

- * - * - *
-     * secretAsyncClient.listDeletedSecrets()
-     *     .subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n",
-     *         deletedSecretResponse.getRecoveryId()));
-     * 
- * - * - * @return A {@link Flux} containing all of the {@link DeletedSecret deleted secrets} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listDeletedSecrets() { - return new PagedFlux<>( - maxResults -> implClient.getDeletedSecretsSinglePageAsync(vaultUrl, maxResults) - .map(SecretAsyncClient::mapDeletedSecretItemPage), - (continuationToken, maxResults) -> implClient - .getDeletedSecretsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapDeletedSecretItemPage)); - } - - static PagedResponse mapDeletedSecretItemPage(PagedResponse page) { - List converted = new ArrayList<>(page.getValue().size()); - for (DeletedSecretItem deletedSecretItem : page.getValue()) { - converted.add(createDeletedSecret(deletedSecretItem)); - } - - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), converted, - page.getContinuationToken(), null); - } - - /** - * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier - * and attributes populated. The secret values and secret versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Code sample

- *

The sample below fetches the all the versions of the given secret. For each version retrieved, makes a call - * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it - * out.

- * - * - *
-     * secretAsyncClient.listPropertiesOfSecretVersions("secretName")
-     *     .flatMap(secretProperties -> {
-     *         System.out.println("Get secret value for version: " + secretProperties.getVersion());
-     *         return secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion());
-     *     })
-     *     .subscribe(secret -> System.out.printf("Received secret with name %s and type %s%n",
-     *         secret.getName(), secret.getValue()));
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link PagedFlux} containing {@link SecretProperties properties} of all the versions of the specified - * secret in the vault. Flux is empty if secret with {@code name} does not exist in key vault - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listPropertiesOfSecretVersions(String name) { - return new PagedFlux<>( - maxResults -> implClient.getSecretVersionsSinglePageAsync(vaultUrl, name, maxResults) - .map(SecretAsyncClient::mapSecretItemPage), - (continuationToken, maxResults) -> implClient - .getSecretVersionsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapSecretItemPage)); - } - - static PagedResponse mapSecretItemPage(PagedResponse page) { - List converted = new ArrayList<>(page.getValue().size()); - for (SecretItem secretItem : page.getValue()) { - converted.add(createSecretProperties(secretItem)); - } - - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), converted, - page.getContinuationToken(), null); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java deleted file mode 100644 index 8a66d7d4bccc0..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java +++ /dev/null @@ -1,1032 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.PollingContext; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.secrets.implementation.SecretClientImpl; -import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.implementation.models.SecretBundle; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.Duration; -import java.util.function.Function; -import java.util.function.Supplier; - -import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapDeletedSecretItemPage; -import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapSecretItemPage; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createDeletedSecret; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createKeyVaultSecret; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretAttributes; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretProperties; - -/** - * The SecretClient provides synchronous methods to manage {@link KeyVaultSecret secrets} in the Azure Key Vault. The - * client supports creating, retrieving, updating, deleting, purging, backing up, restoring, and listing the - * {@link KeyVaultSecret secrets}. The client also supports listing {@link DeletedSecret deleted secrets} for a - * soft-delete enabled key vault. - * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link SecretClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Synchronous Secret client

- * - *
- * SecretClient secretClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildClient();
- * 
- * - * - *
- * - *
- * - *

Create a Secret

- * The {@link SecretClient} can be used to create a secret in the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously create and store a secret in the key vault, - * using the {@link SecretClient#setSecret(String, String)} API.

- * - * - *
- * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
- * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
- * 
- * - * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

- * - *
- * - *
- * - *

Get a Secret

- * The {@link SecretClient} can be used to retrieve a secret from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to synchronously retrieve a previously stored secret from the Azure - * KeyVault, using the {@link SecretClient#getSecret(String)} API.

- * - * - *
- * KeyVaultSecret secret = secretClient.getSecret("secretName");
- * System.out.printf("Secret is returned with name %s and value %s%n",
- *     secret.getName(), secret.getValue());
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link SecretAsyncClient}.

- * - *
- * - *
- * - *

Delete a Secret

- * The {@link SecretClient} can be used to delete a secret from the key vault. - * - *

Code Sample:

- *

The following code sample demonstrates how to delete a secret from the key vault, using - * the {@link SecretClient#beginDeleteSecret(String)} API.

- * - * - *
- * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
- *
- * // Deleted Secret is accessible as soon as polling begins.
- * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
- *
- * // Deletion date only works for a SoftDelete-enabled Key Vault.
- * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
- *     .getDeletedOn().toString());
- * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
- *     .getRecoveryId());
- *
- * // Secret is being deleted on server.
- * deleteSecretPoller.waitForCompletion();
- * 
- * - * - *

Note: For the asynchronous sample, refer to {@link SecretAsyncClient}.

- * - * @see SecretClientBuilder - * @see SyncPoller - * @see PagedIterable - */ -@ServiceClient(builder = SecretClientBuilder.class, serviceInterfaces = SecretClientImpl.SecretClientService.class) -public final class SecretClient { - private static final ClientLogger LOGGER = new ClientLogger(SecretClient.class); - private final SecretClientImpl implClient; - private final String vaultUrl; - - /** - * Gets the vault endpoint url to which service requests are sent to. - * @return the vault endpoint url. - */ - public String getVaultUrl() { - return vaultUrl; - } - - /** - * Creates a SecretClient to service requests - * - * @param implClient the implementation client. - * @param vaultUrl the vault url. - */ - SecretClient(SecretClientImpl implClient, String vaultUrl) { - this.implClient = implClient; - this.vaultUrl = vaultUrl; - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

The {@link SecretProperties#getExpiresOn() expires}, {@link SecretProperties#getContentType() contentType}, - * and {@link SecretProperties#getNotBefore() notBefore} values in {@code secret} are optional. - * If not specified, {@link SecretProperties#isEnabled() enabled} is set to true by key vault.

- * - *

Code sample

- *

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the - * response.

- * - *
-     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
-     *     .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
-     * KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret);
-     * System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(),
-     *     returnedSecret.getValue());
-     * 
- * - * - * @param secret The Secret object containing information about the secret and its properties. The properties - * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be null. - * @return The {@link KeyVaultSecret created secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceModifiedException if {@code secret} is malformed. - * @throws HttpResponseException if {@link KeyVaultSecret#getName() name} or {@link KeyVaultSecret#getValue() value} - * is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSecret setSecret(KeyVaultSecret secret) { - return setSecretWithResponse(secret, Context.NONE).getValue(); - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

Code sample

- *

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the - * response.

- * - *
-     * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
-     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
-     * 
- * - * - * @param name The name of the secret. It is required and cannot be null. - * @param value The value of the secret. It is required and cannot be null. - * @return The {@link KeyVaultSecret created secret}. - * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. - * @throws HttpResponseException if {@code name} or {@code value} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSecret setSecret(String name, String value) { - return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); - } - - /** - * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is - * created. This operation requires the {@code secrets/set} permission. - * - *

Code sample

- *

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the - * response.

- * - *
-     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
-     *     .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
-     * KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue();
-     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
-     * 
- * - * - * @param secret The Secret object containing information about the secret and its properties. The properties - * secret.name and secret.value must be non null. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSecret created secret}. - * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. - * @throws HttpResponseException if {@code name} or {@code value} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response setSecretWithResponse(KeyVaultSecret secret, Context context) { - return callWithMappedException(() -> { - SecretProperties secretProperties = secret.getProperties(); - if (secretProperties == null) { - Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), - secret.getValue(), null, null, null, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - } else { - Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), - secret.getValue(), secretProperties.getTags(), secretProperties.getContentType(), - createSecretAttributes(secretProperties), context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - } - }, SecretAsyncClient::mapSetSecretException); - } - - /** - * Gets the latest version of the specified secret from the key vault. - * This operation requires the {@code secrets/get} permission. - * - *

Code sample

- *

Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.

- * - *
-     * KeyVaultSecret secret = secretClient.getSecret("secretName");
-     * System.out.printf("Secret is returned with name %s and value %s%n",
-     *     secret.getName(), secret.getValue());
-     * 
- * - * - * @param name The name of the secret. - * @return The requested {@link KeyVaultSecret}. - * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - * @throws HttpResponseException If the server reports an error when executing the request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSecret getSecret(String name) { - return getSecretWithResponse(name, null, Context.NONE).getValue(); - } - - /** - * Gets the specified secret with specified version from the key vault. This operation requires the - * {@code secrets/get} permission. - * - *

Code sample

- *

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

- * - *
-     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion);
-     * System.out.printf("Secret is returned with name %s and value %s%n",
-     *     secretWithVersion.getName(), secretWithVersion.getValue());
-     * 
- * - * - * @param name The name of the secret, cannot be null. - * @param version The version of the secret to retrieve. If this is an empty string or null, this call is - * equivalent to calling {@link #getSecret(String)}, with the latest version being retrieved. - * @return The requested {@link KeyVaultSecret secret}. - * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in - * the vault. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - * @throws HttpResponseException If the server reports an error when executing the request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSecret getSecret(String name, String version) { - return getSecretWithResponse(name, version, Context.NONE).getValue(); - } - - /** - * Gets the specified secret with specified version from the key vault. This operation requires the - * {@code secrets/get} permission. - * - *

Code sample

- *

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

- * - *
-     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
-     * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion,
-     *     new Context(key2, value2)).getValue();
-     * System.out.printf("Secret is returned with name %s and value %s%n",
-     *     secretWithVersion.getName(), secretWithVersion.getValue());
-     * 
- * - * - * @param name The name of the secret, cannot be null - * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent - * to calling {@link #getSecret(String)}, with the latest version being retrieved. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the requested {@link KeyVaultSecret}. - * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in - * the vault. - * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSecretWithResponse(String name, String version, Context context) { - if (CoreUtils.isNullOrEmpty(name)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); - } - - return callWithMappedException(() -> { - Response response = implClient.getSecretWithResponse(vaultUrl, name, version, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - }, SecretAsyncClient::mapGetSecretException); - } - - /** - * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. - * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are - * not changed. This operation requires the {@code secrets/set} permission. - * - *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} cannot be null.

- * - *

Code sample

- *

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key - * vault.

- * - *
-     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
-     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
-     * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties);
-     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName());
-     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
-     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
-     * 
- * - * - * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. - * @return The {@link SecretProperties updated secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. - * @throws HttpResponseException if {@link SecretProperties#getName() name} or - * {@link SecretProperties#getVersion() version} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretProperties updateSecretProperties(SecretProperties secretProperties) { - return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); - } - - /** - * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. - * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are - * not changed. This operation requires the {@code secrets/set} permission. - * - *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} cannot be null.

- * - *

Code sample

- *

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. - *

- * - *
-     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
-     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
-     * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties,
-     *     new Context(key2, value2)).getValue();
-     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName());
-     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
-     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
-     * 
- * - * - * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * {@link SecretProperties updated secret}. - * @throws NullPointerException if {@code secret} is {@code null}. - * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and - * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. - * @throws HttpResponseException if {@link SecretProperties#getName() name} or - * {@link SecretProperties#getVersion() version} is an empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSecretPropertiesWithResponse(SecretProperties secretProperties, - Context context) { - Response response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), - secretProperties.getVersion(), secretProperties.getContentType(), createSecretAttributes(secretProperties), - secretProperties.getTags(), context); - return new SimpleResponse<>(response, createSecretProperties(response.getValue())); - } - - /** - * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the - * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. - * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. - * This operation requires the {@code secrets/delete} permission. - * - *

Code sample

- *

Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret - * returned in the response.

- * - *
-     * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
-     *
-     * // Deleted Secret is accessible as soon as polling begins.
-     * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
-     *
-     * // Deletion date only works for a SoftDelete-enabled Key Vault.
-     * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
-     *     .getDeletedOn().toString());
-     * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
-     *     .getRecoveryId());
-     *
-     * // Secret is being deleted on server.
-     * deleteSecretPoller.waitForCompletion();
-     * 
- * - * - * @param name The name of the secret to be deleted. - * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginDeleteSecret(String name) { - return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), - deletePollOperation(name), (context, response) -> null, context -> null); - } - - private Function, PollResponse> - deleteActivationOperation(String name) { - return pollingContext -> callWithMappedException( - () -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), - SecretAsyncClient::mapDeleteSecretException); - } - - private Function, PollResponse> deletePollOperation(String name) { - return pollingContext -> { - try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); - } catch (HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, - pollingContext.getLatestResponse().getValue()); - } else { - // This means either vault has soft-delete disabled or permission is not granted for the get deleted - // key operation. In both cases deletion operation was successful when activation operation - // succeeded before reaching here. - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - } catch (Exception ex) { - // This means either vault has soft-delete disabled or permission is not granted for the get deleted - // key operation. In both cases deletion operation was successful when activation operation - // succeeded before reaching here. - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - }; - } - - /** - * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the - * {@code secrets/list} permission. - * - *

Code sample

- *

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the - * deleted secret returned in the response.

- * - *
-     * DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName");
-     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
-     * 
- * - * - * @param name The name of the deleted secret. - * @return The {@link DeletedSecret deleted secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedSecret getDeletedSecret(String name) { - return getDeletedSecretWithResponse(name, Context.NONE).getValue(); - } - - /** - * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the - * {@code secrets/list} permission. - * - *

Code sample

- *

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the - * deleted secret returned in the response.

- * - *
-     * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName",
-     *     new Context(key2, value2)).getValue();
-     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
-     * 
- * - * - * @param name The name of the deleted secret. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the {@link DeletedSecret deleted - * secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> { - Response response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); - return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); - }, SecretAsyncClient::mapGetDeletedSecretException); - } - - /** - * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed - * on a soft-delete enabled vault. This operation requires the {@code secrets/purge} permission. - * - *

Code sample

- *

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from - * the server response.

- * - * - *
-     * secretClient.purgeDeletedSecret("secretName");
-     * 
- * - * - * @param name The name of the secret. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedSecret(String name) { - purgeDeletedSecretWithResponse(name, Context.NONE); - } - - /** - * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed - * on a soft-delete enabled vault. This operation requires the {@code secrets/purge} permission. - * - *

Code sample

- *

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from - * the server response.

- * - *
-     * Response<Void> purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName",
-     *     new Context(key1, value1));
-     * System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode());
-     * 
- * - * - * @param name The name of the secret. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A response containing status code and HTTP headers. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), - SecretAsyncClient::mapPurgeDeletedSecretException); - } - - /** - * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a soft-delete - * enabled vault. This operation requires the {@code secrets/recover} permission. - * - *

Code sample

- *

Recovers the deleted secret from the key vault enabled for soft-delete. Prints out the details of the - * recovered secret returned in the response.

- * - *
-     * SyncPoller<KeyVaultSecret, Void> recoverSecretPoller =
-     *     secretClient.beginRecoverDeletedSecret("deletedSecretName");
-     *
-     * // Deleted Secret can be accessed as soon as polling is in progress.
-     * PollResponse<KeyVaultSecret> recoveredSecretPollResponse = recoverSecretPoller.poll();
-     * System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName());
-     * System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId());
-     *
-     * // Key is being recovered on server.
-     * recoverSecretPoller.waitForCompletion();
-     * 
- * - * - * @param name The name of the deleted secret to be recovered. - * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller beginRecoverDeletedSecret(String name) { - return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), - recoverPollOperation(name), (context, response) -> null, context -> null); - } - - private Function, PollResponse> - recoverActivationOperation(String name) { - return pollingContext -> callWithMappedException( - () -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), - SecretAsyncClient::mapRecoverDeletedSecretException); - } - - private Function, PollResponse> recoverPollOperation(String name) { - return pollingContext -> { - try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); - } catch (HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, - pollingContext.getLatestResponse().getValue()); - } else { - // This means permission is not granted for the get deleted key operation. In both cases the - // deletion operation was successful when activation operation succeeded before reaching here. - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - } catch (Exception ex) { - // This means permission is not granted for the get deleted key operation. In both cases the - // deletion operation was successful when activation operation succeeded before reaching here. - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - pollingContext.getLatestResponse().getValue()); - } - }; - } - - /** - * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. - * This operation requires the {@code secrets/backup} permission. - * - *

Code sample

- *

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in - * the response

- * - *
-     * byte[] secretBackup = secretClient.backupSecret("secretName");
-     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
-     * 
- * - * - * @param name The name of the secret. - * @return A {@link Response} whose {@link Response#getValue() value} contains the backed up secret blob. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public byte[] backupSecret(String name) { - return backupSecretWithResponse(name, Context.NONE).getValue(); - } - - /** - * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. - * This operation requires the {@code secrets/backup} permission. - * - *

Code sample

- *

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in - * the response

- * - * - *
-     * byte[] secretBackup = secretClient.backupSecretWithResponse("secretName",
-     *     new Context(key1, value1)).getValue();
-     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
-     * 
- * - * - * @param name The name of the secret. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the backed up secret blob. - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> { - Response response = implClient.backupSecretWithResponse(vaultUrl, name, context); - return new SimpleResponse<>(response, response.getValue().getValue()); - }, SecretAsyncClient::mapBackupSecretException); - } - - /** - * Restores a backed up secret, and all its versions, to a vault. - * This operation requires the {@code secrets/restore} permission. - * - *

Code sample

- *

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret - * returned in the response.

- * - * - *
-     * // Pass the secret backup byte array of the secret to be restored.
-     * byte[] secretBackupByteArray = {};
-     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray);
-     * System.out
-     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
-     * 
- * - * - * @param backup The backup blob associated with the secret. - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSecret restored secret}. - * @throws ResourceModifiedException when {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVaultSecret restoreSecretBackup(byte[] backup) { - return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); - } - - /** - * Restores a backed up secret, and all its versions, to a vault. - * This operation requires the {@code secrets/restore} permission. - * - *

Code sample

- *

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret - * returned in the response.

- * - * - *
-     * // Pass the secret backup byte array of the secret to be restored.
-     * byte[] secretBackupByteArray = {};
-     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray,
-     *     new Context(key2, value2)).getValue();
-     * System.out
-     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
-     * 
- * - * - * @param backup The backup blob associated with the secret. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A {@link Response} whose {@link Response#getValue() value} contains the - * {@link KeyVaultSecret restored secret}. - * @throws ResourceModifiedException when {@code backup} blob is malformed. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreSecretBackupWithResponse(byte[] backup, Context context) { - return callWithMappedException(() -> { - Response response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - }, SecretAsyncClient::mapRestoreSecretException); - } - - /** - * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and - * attributes populated. The secret values and their versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Iterate through secrets and fetch their latest value

- *

The snippet below loops over each {@link SecretProperties secret} and calls - * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the - * value of its latest version.

- * - * - *
-     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) {
-     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
-     *     System.out.printf("Received secret with name %s and value %s",
-     *         secretWithValue.getName(), secretWithValue.getValue());
-     * }
-     * 
- * - * - *

Iterate over secrets by page

- *

The snippet below loops over each {@link SecretProperties secret} by page and calls - * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the - * value of its latest version.

- * - * - *
-     * secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> {
-     *     System.out.printf("Response headers are %s. Url %s  and status code %d %n", resp.getHeaders(),
-     *         resp.getRequest().getUrl(), resp.getStatusCode());
-     *     resp.getItems().forEach(value -> {
-     *         KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
-     *         System.out.printf("Received secret with name %s and value %s",
-     *             secretWithValue.getName(), secretWithValue.getValue());
-     *     });
-     * });
-     * 
- * - * - * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The - * {@link SecretProperties} contains all the information about the secret, except its value. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfSecrets() { - return listPropertiesOfSecrets(Context.NONE); - } - - /** - * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and - * attributes populated. The secret values and their versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Iterate over secrets and fetch their latest value

- *

The snippet below loops over each {@link SecretProperties secret} and calls - * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the - * value of its latest version.

- * - *
-     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) {
-     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
-     *     System.out.printf("Received secret with name %s and value %s",
-     *         secretWithValue.getName(), secretWithValue.getValue());
-     * }
-     * 
- * - * - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. - * {@link SecretProperties} contains all the information about the secret, except its value. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfSecrets(Context context) { - return new PagedIterable<>( - maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapSecretItemPage( - implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); - } - - /** - * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation - * requires the {@code secrets/list} permission. - * - *

Iterate over secrets

- *

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

- * - *
-     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) {
-     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
-     * }
-     * 
- * - * - *

Iterate over secrets by page

- *

Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its - * recovery id.

- * - *
-     * secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> {
-     *     System.out.printf("Got response headers . Url: %s, Status code: %d %n",
-     *         resp.getRequest().getUrl(), resp.getStatusCode());
-     *     resp.getItems().forEach(value -> {
-     *         System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId());
-     *     });
-     * });
-     * 
- * - * - * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDeletedSecrets() { - return listDeletedSecrets(Context.NONE); - } - - /** - * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation - * requires the {@code secrets/list} permission. - * - *

Code sample

- *

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

- * - *
-     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) {
-     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
-     * }
-     * 
- * - * - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDeletedSecrets(Context context) { - return new PagedIterable<>( - maxResults -> mapDeletedSecretItemPage( - implClient.getDeletedSecretsSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapDeletedSecretItemPage( - implClient.getDeletedSecretsNextSinglePage(continuationToken, vaultUrl, context))); - } - - /** - * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier - * and attributes populated. The secret values and secret versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Code sample

- *

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call - * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it - * out.

- * - *
-     * for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) {
-     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
-     *     System.out.printf("Received secret's version with name %s and value %s",
-     *         secretWithValue.getName(), secretWithValue.getValue());
-     * }
-     * 
- * - * - * @param name The name of the secret. - * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the - * vault. List is empty if secret with {@code name} does not exist in key vault - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfSecretVersions(String name) { - return listPropertiesOfSecretVersions(name, Context.NONE); - } - - /** - * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier - * and attributes populated. The secret values and secret versions are not listed in the response. - * This operation requires the {@code secrets/list} permission. - * - *

Code sample

- *

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call - * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it - * out.

- * - *
-     * for (SecretProperties secret : secretClient
-     *     .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) {
-     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
-     *     System.out.printf("Received secret's version with name %s and value %s",
-     *         secretWithValue.getName(), secretWithValue.getValue());
-     * }
-     * 
- * - * - *

Iterate over secret versions by page

- *

The sample below iterates over each {@link SecretProperties secret} by each page and calls - * {@link SecretClient#getSecret(String, String)}. This will return the {@link KeyVaultSecret secret} with the - * corresponding version's value.

- * - * - *
-     * secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2))
-     *     .iterableByPage().forEach(resp -> {
-     *         System.out.printf("Got response headers . Url: %s, Status code: %d %n",
-     *             resp.getRequest().getUrl(), resp.getStatusCode());
-     *         resp.getItems().forEach(value -> {
-     *             KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
-     *             System.out.printf("Received secret's version with name %s and value %s",
-     *                 secretWithValue.getName(), secretWithValue.getValue());
-     *         });
-     *     });
-     * 
- * - * - * @param name The name of the secret. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the - * vault. List is empty if secret with {@code name} does not exist in key vault - * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. - * @throws HttpResponseException when a secret with {@code name} is empty string. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listPropertiesOfSecretVersions(String name, Context context) { - return new PagedIterable<>( - maxResults -> mapSecretItemPage( - implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), - (continuationToken, maxResults) -> mapSecretItemPage( - implClient.getSecretVersionsNextSinglePage(continuationToken, vaultUrl, context))); - } - - private static T callWithMappedException(Supplier call, - Function exceptionMapper) { - try { - return call.get(); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java deleted file mode 100644 index 5c163cb2819bf..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeader; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.TracingOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.tracing.Tracer; -import com.azure.core.util.tracing.TracerProvider; -import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.secrets.implementation.KeyVaultErrorCodeStrings; -import com.azure.security.keyvault.secrets.implementation.SecretClientImpl; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecretIdentifier; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of the {@link - * SecretAsyncClient secret async client} and {@link SecretClient secret client}, - * by calling {@link SecretClientBuilder#buildAsyncClient() buildAsyncClient} and {@link - * SecretClientBuilder#buildClient() buildClient} respectively. - * It constructs an instance of the desired client. - * - *

The {@link SecretClient}/{@link SecretAsyncClient} both provide synchronous/asynchronous methods to manage - * {@link KeyVaultSecret secrets} in the Azure Key Vault. The client supports creating, retrieving, updating, - * deleting, purging, backing up, restoring, and listing the {@link KeyVaultSecret secrets}. The client also support - * listing {@link com.azure.security.keyvault.secrets.models.DeletedSecret deleted secrets} for a soft-delete enabled - * Azure Key Vault.

- * - *

The minimal configuration options required by {@link SecretClientBuilder secretClientBuilder} to build - * {@link SecretAsyncClient} are {@link String vaultUrl} and {@link TokenCredential credential}.

- * - * - *
- * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildAsyncClient();
- * 
- * - * - *

Samples to construct the sync client

- * - *
- * SecretClient secretClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildClient();
- * 
- * - * - *

The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom - * {@link HttpClient http client} can be optionally configured in the {@link SecretClientBuilder}.

- * - * - *
- * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
- *     .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- *     .vaultUrl("<your-key-vault-url>")
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .httpClient(HttpClient.createDefault())
- *     .buildAsyncClient();
- * 
- * - * - * @see SecretClient - * @see SecretAsyncClient - */ -@ServiceClientBuilder(serviceClients = SecretClient.class) -public final class SecretClientBuilder implements TokenCredentialTrait, - HttpTrait, ConfigurationTrait { - private static final ClientLogger LOGGER = new ClientLogger(SecretClientBuilder.class); - // This is properties file's name. - private static final String AZURE_KEY_VAULT_SECRETS = "azure-key-vault-secrets.properties"; - private static final String SDK_NAME = "name"; - private static final String SDK_VERSION = "version"; - - // Please see here - // for more information on Azure resource provider namespaces. - private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault"; - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - private final List perCallPolicies; - private final List perRetryPolicies; - private final Map properties; - private TokenCredential credential; - private HttpPipeline pipeline; - private String vaultUrl; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private SecretServiceVersion version; - private ClientOptions clientOptions; - private boolean disableChallengeResourceVerification = false; - - /** - * The constructor with defaults. - */ - public SecretClientBuilder() { - httpLogOptions = new HttpLogOptions(); - perCallPolicies = new ArrayList<>(); - perRetryPolicies = new ArrayList<>(); - properties = CoreUtils.getProperties(AZURE_KEY_VAULT_SECRETS); - } - - /** - * Creates a {@link SecretClient} based on options set in the builder. - * Every time {@code buildClient()} is called, a new instance of {@link SecretClient} is created. - * - *

If {@link SecretClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link SecretClientBuilder#vaultUrl(String) serviceEndpoint} are used to create the - * {@link SecretClientBuilder client}. All other builder settings are ignored. If {@code pipeline} is not set, - * then {@link SecretClientBuilder#credential(TokenCredential) key vault credential}, and - * {@link SecretClientBuilder#vaultUrl(String)} key vault url are required to build the {@link SecretClient - * client}.

- * - * @return A {@link SecretClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link SecretClientBuilder#credential(TokenCredential)} or - * {@link SecretClientBuilder#vaultUrl(String)} have not been set. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SecretClient buildClient() { - return new SecretClient(buildInnerClient(), vaultUrl); - } - - /** - * Creates a {@link SecretAsyncClient} based on options set in the builder. - * Every time {@code buildAsyncClient()} is called, a new instance of {@link SecretAsyncClient} is created. - * - *

If {@link SecretClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link SecretClientBuilder#vaultUrl(String) serviceEndpoint} are used to create the - * {@link SecretClientBuilder client}. All other builder settings are ignored. If {@code pipeline} is not set, - * then {@link SecretClientBuilder#credential(TokenCredential) key vault credential}, and - * {@link SecretClientBuilder#vaultUrl(String)} key vault url are required to build the {@link - * SecretAsyncClient client}.

- * - * @return A {@link SecretAsyncClient} with the options set from the builder. - * - * @throws IllegalStateException If {@link SecretClientBuilder#credential(TokenCredential)} or - * {@link SecretClientBuilder#vaultUrl(String)} have not been set. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SecretAsyncClient buildAsyncClient() { - return new SecretAsyncClient(buildInnerClient(), vaultUrl); - } - - private SecretClientImpl buildInnerClient() { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - String buildEndpoint = getBuildEndpoint(buildConfiguration); - - if (buildEndpoint == null) { - throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); - } - - SecretServiceVersion serviceVersion = version != null ? version : SecretServiceVersion.getLatest(); - - if (pipeline != null) { - return new SecretClientImpl(pipeline, serviceVersion.getVersion()); - } - - if (credential == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.CREDENTIALS_REQUIRED)); - } - - // Closest to API goes first, closest to wire goes last. - final List policies = new ArrayList<>(); - - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - - httpLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - ClientOptions localClientOptions = clientOptions != null ? clientOptions : DEFAULT_CLIENT_OPTIONS; - - policies.add(new UserAgentPolicy(CoreUtils.getApplicationId(localClientOptions, httpLogOptions), clientName, - clientVersion, buildConfiguration)); - - List httpHeaderList = new ArrayList<>(); - localClientOptions.getHeaders() - .forEach(header -> httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); - policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); - - // Add per call additional policies. - policies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - - // Add retry policy. - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - policies.add(new KeyVaultCredentialPolicy(credential, disableChallengeResourceVerification)); - - // Add per retry additional policies. - policies.addAll(perRetryPolicies); - - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - - TracingOptions tracingOptions = localClientOptions.getTracingOptions(); - Tracer tracer = TracerProvider.getDefaultProvider() - .createTracer(clientName, clientVersion, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .clientOptions(localClientOptions) - .tracer(tracer) - .build(); - - return new SecretClientImpl(pipeline, serviceVersion.getVersion()); - } - - /** - * Sets the vault endpoint URL to send HTTP requests to. You should validate that this URL references a valid Key - * Vault resource. Refer to the following documentation for details. - * - * @param vaultUrl The vault url is used as destination on Azure to send requests to. If you have a secret - * identifier, create a new {@link KeyVaultSecretIdentifier} to parse it and obtain the {@code vaultUrl} and - * other information. - * - * @return The updated {@link SecretClientBuilder} object. - * - * @throws IllegalArgumentException If {@code vaultUrl} is null or it cannot be parsed into a valid URL. - * @throws NullPointerException If {@code vaultUrl} is {@code null}. - */ - public SecretClientBuilder vaultUrl(String vaultUrl) { - if (vaultUrl == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'vaultUrl' cannot be null.")); - } - - try { - URL url = new URL(vaultUrl); - this.vaultUrl = url.toString(); - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault url is malformed.", e)); - } - - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * - * @return The updated {@link SecretClientBuilder} object. - * - * @throws NullPointerException If {@code credential} is {@code null}. - */ - @Override - public SecretClientBuilder credential(TokenCredential credential) { - if (credential == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); - } - - this.credential = credential; - - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated {@link SecretClientBuilder} object. - * - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public SecretClientBuilder addPolicy(HttpPipelinePolicy policy) { - if (policy == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); - } - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * The {@link #vaultUrl(String) vaultUrl} is not ignored when - * {@code pipeline} is set. - * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - * - * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store used to - * - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - - return this; - } - - /** - * Sets the {@link SecretServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version the client library will have the result of potentially moving to a newer service version. - * - * @param version {@link SecretServiceVersion} of the service API used when making requests. - * - * @return The updated {@link SecretClientBuilder} object. - */ - public SecretClientBuilder serviceVersion(SecretServiceVersion version) { - this.version = version; - - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * The default retry policy will be used in the pipeline, if not provided. - * - * @param retryPolicy user's retry policy applied to each request. - * - * @return The updated {@link SecretClientBuilder} object. - */ - public SecretClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @see HttpClientOptions - * @return The updated {@link SecretClientBuilder} object. - */ - @Override - public SecretClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - - return this; - } - - /** - * Disables verifying if the authentication challenge resource matches the Key Vault domain. This verification is - * performed by default. - * - * @return The updated {@link SecretClientBuilder} object. - */ - public SecretClientBuilder disableChallengeResourceVerification() { - this.disableChallengeResourceVerification = true; - - return this; - } - - private String getBuildEndpoint(Configuration configuration) { - if (vaultUrl != null) { - return vaultUrl; - } - - String configEndpoint = configuration.get("AZURE_KEYVAULT_ENDPOINT"); - if (CoreUtils.isNullOrEmpty(configEndpoint)) { - return null; - } - - try { - URL url = new URL(configEndpoint); - return url.toString(); - } catch (MalformedURLException ex) { - return null; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java deleted file mode 100644 index 8ddee9cb149b5..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretServiceVersion.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.util.ServiceVersion; - -/** - * The versions of Azure Key Vault Secret supported by this client library. - */ -public enum SecretServiceVersion implements ServiceVersion { - /** - * Service version {@code 7.0}. - */ - V7_0("7.0"), - - /** - * Service version {@code 7.1}. - */ - V7_1("7.1"), - - /** - * Service version {@code 7.2}. - */ - V7_2("7.2"), - - /** - * Service version {@code 7.3}. - */ - V7_3("7.3"), - - /** - * Service version {@code 7.4}. - */ - V7_4("7.4"), - - /** - * Service version {@code 7.5}. - */ - V7_5("7.5"), - - /** - * Service version {@code 7.6-preview.1}. - */ - V7_6_PREVIEW_1("7.6-preview.1"); - - private final String version; - - SecretServiceVersion(String version) { - this.version = version; - } - - /** - * {@inheritDoc} - */ - @Override - public String getVersion() { - return this.version; - } - - /** - * Gets the latest service version supported by this client library - * - * @return the latest {@link SecretServiceVersion} - */ - public static SecretServiceVersion getLatest() { - return V7_6_PREVIEW_1; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java deleted file mode 100644 index 85ddb89acc215..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.secrets.implementation; - -import com.azure.security.keyvault.secrets.models.DeletedSecret; - -import java.time.OffsetDateTime; - -public final class DeletedSecretHelper { - private static DeletedSecretAccessor accessor; - - public interface DeletedSecretAccessor { - void setRecoveryId(DeletedSecret deletedSecret, String recoveryId); - - void setScheduledPurgeDate(DeletedSecret deletedSecret, OffsetDateTime scheduledPurgeDate); - - void setDeletedOn(DeletedSecret deletedSecret, OffsetDateTime deletedOn); - } - - public static void setRecoveryId(DeletedSecret deletedSecret, String recoveryId) { - if (accessor == null) { - new DeletedSecret(); - } - - assert accessor != null; - accessor.setRecoveryId(deletedSecret, recoveryId); - } - - public static void setScheduledPurgeDate(DeletedSecret deletedSecret, OffsetDateTime scheduledPurgeDate) { - if (accessor == null) { - new DeletedSecret(); - } - - assert accessor != null; - - accessor.setScheduledPurgeDate(deletedSecret, scheduledPurgeDate); - } - - public static void setDeletedOn(DeletedSecret deletedSecret, OffsetDateTime deletedOn) { - if (accessor == null) { - new DeletedSecret(); - } - - assert accessor != null; - - accessor.setDeletedOn(deletedSecret, deletedOn); - } - - public static void setAccessor(DeletedSecretAccessor newAccessor) { - accessor = newAccessor; - } - - private DeletedSecretHelper() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java deleted file mode 100644 index 267635f434d4c..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.secrets.implementation; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelineNextSyncPolicy; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; -import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; - -/** - * A policy that authenticates requests with the Azure Key Vault service. The content added by this policy is - * leveraged in {@link TokenCredential} to get and set the correct "Authorization" header value. - * - * @see TokenCredential - */ -public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); - private static final String BEARER_TOKEN_PREFIX = "Bearer "; - private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; - private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; - private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; - private final boolean disableChallengeResourceVerification; - - /** - * Creates a {@link KeyVaultCredentialPolicy}. - * - * @param credential The token credential to authenticate the request. - */ - public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChallengeResourceVerification) { - super(credential); - - this.disableChallengeResourceVerification = disableChallengeResourceVerification; - } - - /** - * Extracts attributes off the bearer challenge in the authentication header. - * - * @param authenticateHeader The authentication header containing the challenge. - * @param authChallengePrefix The authentication challenge name. - * - * @return A challenge attributes map. - */ - private static Map extractChallengeAttributes(String authenticateHeader, - String authChallengePrefix) { - if (!isBearerChallenge(authenticateHeader, authChallengePrefix)) { - return Collections.emptyMap(); - } - - String[] attributes = authenticateHeader.replace("\"", "").substring(authChallengePrefix.length()).split(","); - Map attributeMap = new HashMap<>(); - - for (String pair : attributes) { - // Using trim is ugly, but we need it here because currently the 'claims' attribute comes after two spaces. - String[] keyValue = pair.trim().split("=", 2); - - attributeMap.put(keyValue[0], keyValue[1]); - } - - return attributeMap; - } - - /** - * Verifies whether a challenge is bearer or not. - * - * @param authenticateHeader The authentication header containing all the challenges. - * @param authChallengePrefix The authentication challenge name. - * - * @return A boolean indicating if the challenge is a bearer challenge or not. - */ - private static boolean isBearerChallenge(String authenticateHeader, String authChallengePrefix) { - return (!CoreUtils.isNullOrEmpty(authenticateHeader) - && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); - } - - @Override - public Mono authorizeRequest(HttpPipelineCallContext context) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes - // which also protect the body of the request. As a result, before we know the auth scheme we need to - // avoid sending an unprotected body to Key Vault. We don't currently support this enhanced auth scheme - // in the SDK, but we still don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBody() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBody()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, - request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((Flux) null); - } - } - - return Mono.empty(); - }); - } - - @SuppressWarnings("unchecked") - @Override - public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context, HttpResponse response) { - return Mono.defer(() -> { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((Flux) contentOptional.get()); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return Mono.just(false); - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String - .format("The challenge resource '%s' does not match the requested domain. If you wish to " - + "disable this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); - }); - } - - @Override - public void authorizeRequestSync(HttpPipelineCallContext context) { - HttpRequest request = context.getHttpRequest(); - - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } - - if (this.challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return; - } - - // The body is removed from the initial request because Key Vault supports other authentication schemes which - // also protect the body of the request. As a result, before we know the auth scheme we need to avoid sending an - // unprotected body to Key Vault. We don't currently support this enhanced auth scheme in the SDK, but we still - // don't want to send any unprotected data to vaults which require it. - - // Do not overwrite previous contents if retrying after initial request failed (e.g. timeout). - if (!context.getData(KEY_VAULT_STASHED_CONTENT_KEY).isPresent()) { - if (request.getBodyAsBinaryData() != null) { - context.setData(KEY_VAULT_STASHED_CONTENT_KEY, request.getBodyAsBinaryData()); - context.setData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY, request.getHeaders().getValue(CONTENT_LENGTH)); - request.setHeader(CONTENT_LENGTH, "0"); - request.setBody((BinaryData) null); - } - } - } - - @Override - public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, HttpResponse response) { - HttpRequest request = context.getHttpRequest(); - Optional contentOptional = context.getData(KEY_VAULT_STASHED_CONTENT_KEY); - Optional contentLengthOptional = context.getData(KEY_VAULT_STASHED_CONTENT_LENGTH_KEY); - - if (request.getBody() == null && contentOptional.isPresent() && contentLengthOptional.isPresent()) { - request.setBody((BinaryData) (contentOptional.get())); - request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); - } - - String authority = getRequestAuthority(request); - Map challengeAttributes - = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - String scope = challengeAttributes.get("resource"); - - if (scope != null) { - scope = scope + "/.default"; - } else { - scope = challengeAttributes.get("scope"); - } - - if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); - - if (this.challenge == null) { - return false; - } - } else { - if (!disableChallengeResourceVerification) { - if (!isChallengeResourceValid(request, scope)) { - throw LOGGER.logExceptionAsError(new RuntimeException(String.format( - "The challenge resource '%s' does not match the requested domain. If you wish to disable " - + "this check for your client, pass 'true' to the SecretClientBuilder" - + ".disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information.", - scope))); - } - } - - String authorization = challengeAttributes.get("authorization"); - - if (authorization == null) { - authorization = challengeAttributes.get("authorization_uri"); - } - - final URI authorizationUri; - - try { - authorizationUri = new URI(authorization); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError(new RuntimeException( - String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); - } - - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); - - CHALLENGE_CACHE.put(authority, this.challenge); - } - - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); - - return true; - } - - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return authorizeRequest(context).then(Mono.defer(next::process)).flatMap(httpResponse -> { - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallenge(context, httpResponse, nextPolicy); - } - - return Mono.just(httpResponse); - }); - } - - @Override - public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { - if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { - throw LOGGER.logExceptionAsError( - new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme.")); - } - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - - authorizeRequestSync(context); - - HttpResponse httpResponse = next.processSync(); - String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (httpResponse.getStatusCode() == 401 && authHeader != null) { - return handleChallengeSync(context, httpResponse, nextPolicy); - } - - return httpResponse; - } - - private Mono handleChallenge(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextPolicy next) { - return authorizeRequestOnChallenge(context, httpResponse).flatMap(authorized -> { - if (authorized) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextPolicy nextPolicy = next.clone(); - - return next.process().flatMap(newResponse -> { - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallenge(context, newResponse, nextPolicy); - } else { - return Mono.just(newResponse); - } - }); - } - - return Mono.just(httpResponse); - }); - } - - private HttpResponse handleChallengeSync(HttpPipelineCallContext context, HttpResponse httpResponse, - HttpPipelineNextSyncPolicy next) { - if (authorizeRequestOnChallengeSync(context, httpResponse)) { - // The body needs to be closed or read to the end to release the connection. - httpResponse.close(); - - HttpPipelineNextSyncPolicy nextPolicy = next.clone(); - HttpResponse newResponse = next.processSync(); - String authHeader = newResponse.getHeaderValue(WWW_AUTHENTICATE); - - if (newResponse.getStatusCode() == 401 - && authHeader != null - && isClaimsPresent(newResponse) - && !isClaimsPresent(httpResponse)) { - - return handleChallengeSync(context, newResponse, nextPolicy); - } - - return newResponse; - } - - return httpResponse; - } - - private boolean isClaimsPresent(HttpResponse httpResponse) { - Map challengeAttributes - = extractChallengeAttributes(httpResponse.getHeaderValue(WWW_AUTHENTICATE), BEARER_TOKEN_PREFIX); - - String error = challengeAttributes.get("error"); - - if (error != null) { - String base64Claims = challengeAttributes.get("claims"); - - return "insufficient_claims".equalsIgnoreCase(error) && base64Claims != null; - } - - return false; - } - - private static class ChallengeParameters { - private final URI authorizationUri; - private final String tenantId; - private final String[] scopes; - - ChallengeParameters(URI authorizationUri, String[] scopes) { - this.authorizationUri = authorizationUri; - tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; - } - - /** - * Get the {@code authorization} or {@code authorization_uri} parameter from the challenge response. - */ - public URI getAuthorizationUri() { - return authorizationUri; - } - - /** - * Get the {@code resource} or {@code scope} parameter from the challenge response. This should end with - * "/.default". - */ - public String[] getScopes() { - return scopes; - } - - /** - * Get the tenant ID from {@code authorizationUri}. - */ - public String getTenantId() { - return tenantId; - } - } - - public static void clearCache() { - CHALLENGE_CACHE.clear(); - } - - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; - } - - return authority; - } - - private static boolean isChallengeResourceValid(HttpRequest request, String scope) { - final URI scopeUri; - - try { - scopeUri = new URI(scope); - } catch (URISyntaxException e) { - throw LOGGER.logExceptionAsError( - new RuntimeException(String.format("The challenge resource '%s' is not a valid URI.", scope), e)); - } - - // Returns false if the host specified in the scope does not match the requested domain. - return request.getUrl() - .getHost() - .toLowerCase(Locale.ROOT) - .endsWith("." + scopeUri.getHost().toLowerCase(Locale.ROOT)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultErrorCodeStrings.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultErrorCodeStrings.java deleted file mode 100644 index b37d6bb2d410e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultErrorCodeStrings.java +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.implementation; - -public final class KeyVaultErrorCodeStrings { - public static final String CREDENTIALS_REQUIRED = "Azure Key Vault credentials are required."; - public static final String VAULT_END_POINT_REQUIRED = "Azure Key Vault endpoint url is required."; - public static final String PARAMETER_REQUIRED = "%s cannot be null."; -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java deleted file mode 100644 index aaeaf37c2278c..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java +++ /dev/null @@ -1,2338 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretItem; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretListResult; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.implementation.models.SecretAttributes; -import com.azure.security.keyvault.secrets.implementation.models.SecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.SecretItem; -import com.azure.security.keyvault.secrets.implementation.models.SecretListResult; -import com.azure.security.keyvault.secrets.implementation.models.SecretRestoreParameters; -import com.azure.security.keyvault.secrets.implementation.models.SecretSetParameters; -import com.azure.security.keyvault.secrets.implementation.models.SecretUpdateParameters; -import java.util.Map; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the SecretClient type. - */ -public final class SecretClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final SecretClientService service; - - /** - * Api Version. - */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** - * The HTTP pipeline to send requests through. - */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * The serializer to serialize an object into a string. - */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * Initializes an instance of SecretClient client. - * - * @param apiVersion Api Version. - */ - public SecretClientImpl(String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of SecretClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. - */ - public SecretClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of SecretClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. - */ - public SecretClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; - this.service = RestProxy.create(SecretClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for SecretClient to be used by the proxy service to perform REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "SecretClient") - public interface SecretClientService { - @Put("/secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> setSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretSetParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Put("/secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response setSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretSetParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Delete("/secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/secrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Patch("/secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Patch("/secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Get("/secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/secrets/{secret-name}/{secret-version}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/secrets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/secrets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/secrets/{secret-name}/versions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/secrets/{secret-name}/versions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedsecrets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedsecrets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedsecrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/deletedsecrets/{secret-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/deletedsecrets/{secret-name}") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> purgeDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/deletedsecrets/{secret-name}") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response purgeDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/deletedsecrets/{secret-name}/recover") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> recoverDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/deletedsecrets/{secret-name}/recover") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response recoverDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/secrets/{secret-name}/backup") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> backupSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/secrets/{secret-name}/backup") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response backupSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Post("/secrets/restore") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Post("/secrets/restore") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretVersionsNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretVersionsNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecretsNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretsNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponseAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes) { - return FluxUtil.withContext(context -> setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, - secretContentType, secretAttributes, context)); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponseAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { - final String accept = "application/json"; - SecretSetParameters parameters = new SecretSetParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecret(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecretAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes) { - return setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecretAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { - return setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response setSecretWithResponse(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { - final String accept = "application/json"; - SecretSetParameters parameters = new SecretSetParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value, Map tags, - String secretContentType, SecretAttributes secretAttributes) { - return setSecretWithResponse(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes, - Context.NONE).getValue(); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> deleteSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.deleteSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSecretAsync(String vaultBaseUrl, String secretName) { - return deleteSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return deleteSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.deleteSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedSecretBundle deleteSecret(String vaultBaseUrl, String secretName) { - return deleteSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, String secretContentType, SecretAttributes secretAttributes, Map tags) { - return FluxUtil.withContext(context -> updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, - secretContentType, secretAttributes, tags, context)); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, String secretContentType, SecretAttributes secretAttributes, Map tags, - Context context) { - final String accept = "application/json"; - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - parameters.setTags(tags); - return service.updateSecret(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags) { - return updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, secretContentType, - secretAttributes, tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags, Context context) { - return updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, secretContentType, - secretAttributes, tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSecretWithResponse(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags, Context context) { - final String accept = "application/json"; - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - parameters.setTags(tags); - return service.updateSecretSync(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), parameters, - accept, context); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags) { - return updateSecretWithResponse(vaultBaseUrl, secretName, secretVersion, secretContentType, secretAttributes, - tags, Context.NONE).getValue(); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion) { - return FluxUtil - .withContext(context -> getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, context)); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, Context context) { - final String accept = "application/json"; - return service.getSecret(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { - return getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - Context context) { - return getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSecretWithResponse(String vaultBaseUrl, String secretName, String secretVersion, - Context context) { - final String accept = "application/json"; - return service.getSecretSync(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) { - return getSecretWithResponse(vaultBaseUrl, secretName, secretVersion, Context.NONE).getValue(); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsSinglePageAsync(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretsAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getSecretsSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getSecretsNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretsAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getSecretsSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getSecretsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsSinglePage(String vaultBaseUrl, Integer maxresults, Context context) { - final String accept = "application/json"; - Response res - = service.getSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecrets(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getSecretsSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getSecretsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecrets(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getSecretsSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getSecretsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsSinglePageAsync(String vaultBaseUrl, String secretName, - Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getSecretVersions(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsSinglePageAsync(String vaultBaseUrl, String secretName, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getSecretVersions(vaultBaseUrl, secretName, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretVersionsAsync(String vaultBaseUrl, String secretName, Integer maxresults) { - return new PagedFlux<>(() -> getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults), - nextLink -> getSecretVersionsNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretVersionsAsync(String vaultBaseUrl, String secretName, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults, context), - nextLink -> getSecretVersionsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsSinglePage(String vaultBaseUrl, String secretName, - Integer maxresults) { - final String accept = "application/json"; - Response res = service.getSecretVersionsSync(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsSinglePage(String vaultBaseUrl, String secretName, - Integer maxresults, Context context) { - final String accept = "application/json"; - Response res = service.getSecretVersionsSync(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecretVersions(String vaultBaseUrl, String secretName, Integer maxresults) { - return new PagedIterable<>( - () -> getSecretVersionsSinglePage(vaultBaseUrl, secretName, maxresults, Context.NONE), - nextLink -> getSecretVersionsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecretVersions(String vaultBaseUrl, String secretName, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getSecretVersionsSinglePage(vaultBaseUrl, secretName, maxresults, context), - nextLink -> getSecretVersionsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsSinglePageAsync(String vaultBaseUrl, - Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.getDeletedSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsSinglePageAsync(String vaultBaseUrl, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getDeletedSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedSecretsAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getDeletedSecretsSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getDeletedSecretsNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedSecretsAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getDeletedSecretsSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedSecretsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsSinglePage(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedSecrets(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getDeletedSecretsSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getDeletedSecretsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedSecrets(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getDeletedSecretsSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedSecretsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretWithResponseAsync(String vaultBaseUrl, - String secretName) { - return FluxUtil.withContext(context -> getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.getDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.getDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedSecretBundle getDeletedSecret(String vaultBaseUrl, String secretName) { - return getDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.purgeDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedSecretWithResponse(String vaultBaseUrl, String secretName, Context context) { - final String accept = "application/json"; - return service.purgeDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedSecret(String vaultBaseUrl, String secretName) { - purgeDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil - .withContext(context -> recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.recoverDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response recoverDeletedSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.recoverDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle recoverDeletedSecret(String vaultBaseUrl, String secretName) { - return recoverDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> backupSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.backupSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupSecretAsync(String vaultBaseUrl, String secretName) { - return backupSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return backupSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { - final String accept = "application/json"; - return service.backupSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public BackupSecretResult backupSecret(String vaultBaseUrl, String secretName) { - return backupSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreSecretWithResponseAsync(String vaultBaseUrl, byte[] secretBundleBackup) { - return FluxUtil - .withContext(context -> restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup, context)); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreSecretWithResponseAsync(String vaultBaseUrl, byte[] secretBundleBackup, - Context context) { - final String accept = "application/json"; - SecretRestoreParameters parameters = new SecretRestoreParameters(); - parameters.setSecretBundleBackup(secretBundleBackup); - return service.restoreSecret(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup) { - return restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup, Context context) { - return restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreSecretWithResponse(String vaultBaseUrl, byte[] secretBundleBackup, - Context context) { - final String accept = "application/json"; - SecretRestoreParameters parameters = new SecretRestoreParameters(); - parameters.setSecretBundleBackup(secretBundleBackup); - return service.restoreSecretSync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle restoreSecret(String vaultBaseUrl, byte[] secretBundleBackup) { - return restoreSecretWithResponse(vaultBaseUrl, secretBundleBackup, Context.NONE).getValue(); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSecretsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getSecretsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res = service.getSecretsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { - final String accept = "application/json"; - Response res = service.getSecretsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSecretVersionsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getSecretVersionsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getSecretVersionsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - Response res = service.getSecretVersionsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getDeletedSecretsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, - String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getDeletedSecretsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretPropertiesHelper.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretPropertiesHelper.java deleted file mode 100644 index ef89b1fa8f9fd..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretPropertiesHelper.java +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.secrets.implementation; - -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -public class SecretPropertiesHelper { - private static SecretPropertiesAccessor accessor; - - public interface SecretPropertiesAccessor { - void setId(SecretProperties properties, String id); - - void setVersion(SecretProperties properties, String version); - - void setCreatedOn(SecretProperties properties, OffsetDateTime createdOn); - - void setUpdatedOn(SecretProperties properties, OffsetDateTime updatedOn); - - void setName(SecretProperties properties, String name); - - void setRecoveryLevel(SecretProperties properties, String recoveryLevel); - - void setKeyId(SecretProperties properties, String keyId); - - void setManaged(SecretProperties properties, Boolean managed); - - void setRecoverableDays(SecretProperties properties, Integer recoverableDays); - } - - public static void setId(SecretProperties properties, String id) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setId(properties, id); - } - - public static void setVersion(SecretProperties properties, String version) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setVersion(properties, version); - } - - public static void setCreatedOn(SecretProperties properties, OffsetDateTime createdOn) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setCreatedOn(properties, createdOn); - } - - public static void setUpdatedOn(SecretProperties properties, OffsetDateTime updatedOn) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setUpdatedOn(properties, updatedOn); - } - - public static void setName(SecretProperties properties, String name) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setName(properties, name); - } - - public static void setRecoveryLevel(SecretProperties properties, String recoveryLevel) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setRecoveryLevel(properties, recoveryLevel); - } - - public static void setKeyId(SecretProperties properties, String keyId) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setKeyId(properties, keyId); - } - - public static void setManaged(SecretProperties properties, Boolean managed) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setManaged(properties, managed); - } - - public static void setRecoverableDays(SecretProperties properties, Integer recoverableDays) { - if (accessor == null) { - new SecretProperties(); - } - - assert accessor != null; - accessor.setRecoverableDays(properties, recoverableDays); - } - - public static void setAccessor(SecretPropertiesAccessor newAccessor) { - accessor = newAccessor; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java deleted file mode 100644 index a409d75c7a234..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the KeyVault service. - */ -@Fluent -public class Attributes implements JsonSerializable { - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of Attributes class. - */ - public Attributes() { - } - - /** - * Get the enabled property: Determines whether the object is enabled. - * - * @return the enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled property: Determines whether the object is enabled. - * - * @param enabled the enabled value to set. - * @return the Attributes object itself. - */ - public Attributes setEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore property: Not before date in UTC. - * - * @return the notBefore value. - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); - } - - /** - * Set the notBefore property: Not before date in UTC. - * - * @param notBefore the notBefore value to set. - * @return the Attributes object itself. - */ - public Attributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = notBefore.toEpochSecond(); - } - return this; - } - - /** - * Get the expires property: Expiry date in UTC. - * - * @return the expires value. - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); - } - - /** - * Set the expires property: Expiry date in UTC. - * - * @param expires the expires value to set. - * @return the Attributes object itself. - */ - public Attributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = expires.toEpochSecond(); - } - return this; - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Set the created property: Creation time in UTC. - * - * @param created the created value to set. - * @return the Attributes object itself. - */ - Attributes setCreated(OffsetDateTime created) { - if (created == null) { - this.created = null; - } else { - this.created = created.toEpochSecond(); - } - return this; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Set the updated property: Last updated time in UTC. - * - * @param updated the updated value to set. - * @return the Attributes object itself. - */ - Attributes setUpdated(OffsetDateTime updated) { - if (updated == null) { - this.updated = null; - } else { - this.updated = updated.toEpochSecond(); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", this.enabled); - jsonWriter.writeNumberField("nbf", this.notBefore); - jsonWriter.writeNumberField("exp", this.expires); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Attributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Attributes if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the Attributes. - */ - public static Attributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Attributes deserializedAttributes = new Attributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedAttributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - deserializedAttributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - deserializedAttributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - deserializedAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java deleted file mode 100644 index b3d30d2bf45f5..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.Base64Url; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The backup secret result, containing the backup blob. - */ -@Immutable -public final class BackupSecretResult implements JsonSerializable { - /* - * The backup blob containing the backed up secret. - */ - private Base64Url value; - - /** - * Creates an instance of BackupSecretResult class. - */ - public BackupSecretResult() { - } - - /** - * Get the value property: The backup blob containing the backed up secret. - * - * @return the value value. - */ - public byte[] getValue() { - if (this.value == null) { - return null; - } - return this.value.decodedBytes(); - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of BackupSecretResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of BackupSecretResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the BackupSecretResult. - */ - public static BackupSecretResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - BackupSecretResult deserializedBackupSecretResult = new BackupSecretResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedBackupSecretResult.value - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedBackupSecretResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java deleted file mode 100644 index 76027d396870a..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Map; - -/** - * A Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when it will be - * purged. - */ -@Fluent -public final class DeletedSecretBundle extends SecretBundle { - /* - * The url of the recovery object, used to identify and recover the deleted secret. - */ - private String recoveryId; - - /* - * The time when the secret is scheduled to be purged, in UTC - */ - private Long scheduledPurgeDate; - - /* - * The time when the secret was deleted, in UTC - */ - private Long deletedDate; - - /* - * True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed - * will be true. - */ - private Boolean managed; - - /* - * If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV - * certificate. - */ - private String kid; - - /** - * Creates an instance of DeletedSecretBundle class. - */ - public DeletedSecretBundle() { - } - - /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @return the recoveryId value. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedSecretBundle object itself. - */ - public DeletedSecretBundle setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; - } - - /** - * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. - */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); - } - - /** - * Get the deletedDate property: The time when the secret was deleted, in UTC. - * - * @return the deletedDate value. - */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); - } - - /** - * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - @Override - public Boolean isManaged() { - return this.managed; - } - - /** - * Get the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding - * key backing the KV certificate. - * - * @return the kid value. - */ - @Override - public String getKid() { - return this.kid; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setValue(String value) { - super.setValue(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setId(String id) { - super.setId(id); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setContentType(String contentType) { - super.setContentType(contentType); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setAttributes(SecretAttributes attributes) { - super.setAttributes(attributes); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setTags(Map tags) { - super.setTags(tags); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", getValue()); - jsonWriter.writeStringField("id", getId()); - jsonWriter.writeStringField("contentType", getContentType()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("recoveryId", this.recoveryId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedSecretBundle from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedSecretBundle if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedSecretBundle. - */ - public static DeletedSecretBundle fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedSecretBundle deserializedDeletedSecretBundle = new DeletedSecretBundle(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedDeletedSecretBundle.setValue(reader.getString()); - } else if ("id".equals(fieldName)) { - deserializedDeletedSecretBundle.setId(reader.getString()); - } else if ("contentType".equals(fieldName)) { - deserializedDeletedSecretBundle.setContentType(reader.getString()); - } else if ("attributes".equals(fieldName)) { - deserializedDeletedSecretBundle.setAttributes(SecretAttributes.fromJson(reader)); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedSecretBundle.setTags(tags); - } else if ("kid".equals(fieldName)) { - deserializedDeletedSecretBundle.kid = reader.getString(); - } else if ("managed".equals(fieldName)) { - deserializedDeletedSecretBundle.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoveryId".equals(fieldName)) { - deserializedDeletedSecretBundle.recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - deserializedDeletedSecretBundle.scheduledPurgeDate = reader.getNullable(JsonReader::getLong); - } else if ("deletedDate".equals(fieldName)) { - deserializedDeletedSecretBundle.deletedDate = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedSecretBundle; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java deleted file mode 100644 index 7796427df1e5e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Map; - -/** - * The deleted secret item containing metadata about the deleted secret. - */ -@Fluent -public final class DeletedSecretItem extends SecretItem { - /* - * The url of the recovery object, used to identify and recover the deleted secret. - */ - private String recoveryId; - - /* - * The time when the secret is scheduled to be purged, in UTC - */ - private Long scheduledPurgeDate; - - /* - * The time when the secret was deleted, in UTC - */ - private Long deletedDate; - - /* - * True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will - * be true. - */ - private Boolean managed; - - /** - * Creates an instance of DeletedSecretItem class. - */ - public DeletedSecretItem() { - } - - /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @return the recoveryId value. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedSecretItem object itself. - */ - public DeletedSecretItem setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; - } - - /** - * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. - */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); - } - - /** - * Get the deletedDate property: The time when the secret was deleted, in UTC. - * - * @return the deletedDate value. - */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); - } - - /** - * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - @Override - public Boolean isManaged() { - return this.managed; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretItem setId(String id) { - super.setId(id); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretItem setAttributes(SecretAttributes attributes) { - super.setAttributes(attributes); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretItem setTags(Map tags) { - super.setTags(tags); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedSecretItem setContentType(String contentType) { - super.setContentType(contentType); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", getId()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("contentType", getContentType()); - jsonWriter.writeStringField("recoveryId", this.recoveryId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedSecretItem from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedSecretItem if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedSecretItem. - */ - public static DeletedSecretItem fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedSecretItem deserializedDeletedSecretItem = new DeletedSecretItem(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedDeletedSecretItem.setId(reader.getString()); - } else if ("attributes".equals(fieldName)) { - deserializedDeletedSecretItem.setAttributes(SecretAttributes.fromJson(reader)); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedSecretItem.setTags(tags); - } else if ("contentType".equals(fieldName)) { - deserializedDeletedSecretItem.setContentType(reader.getString()); - } else if ("managed".equals(fieldName)) { - deserializedDeletedSecretItem.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoveryId".equals(fieldName)) { - deserializedDeletedSecretItem.recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - deserializedDeletedSecretItem.scheduledPurgeDate = reader.getNullable(JsonReader::getLong); - } else if ("deletedDate".equals(fieldName)) { - deserializedDeletedSecretItem.deletedDate = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedSecretItem; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java deleted file mode 100644 index 62d91307493de..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The deleted secret list result. - */ -@Immutable -public final class DeletedSecretListResult implements JsonSerializable { - /* - * A response message containing a list of the deleted secrets in the vault along with a link to the next page of - * deleted secrets - */ - private List value; - - /* - * The URL to get the next set of deleted secrets. - */ - private String nextLink; - - /** - * Creates an instance of DeletedSecretListResult class. - */ - public DeletedSecretListResult() { - } - - /** - * Get the value property: A response message containing a list of the deleted secrets in the vault along with a - * link to the next page of deleted secrets. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of deleted secrets. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedSecretListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedSecretListResult if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the DeletedSecretListResult. - */ - public static DeletedSecretListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedSecretListResult deserializedDeletedSecretListResult = new DeletedSecretListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> DeletedSecretItem.fromJson(reader1)); - deserializedDeletedSecretListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDeletedSecretListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedSecretListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java deleted file mode 100644 index 33351dbfc1baa..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains - * 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the - * secret, at the end of the retention interval. - */ -public final class DeletionRecoveryLevel extends ExpandableStringEnum { - /** - * 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.). - */ - public static final DeletionRecoveryLevel PURGEABLE = fromString("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. - */ - public static final DeletionRecoveryLevel RECOVERABLE_PURGEABLE = fromString("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. - */ - public static final DeletionRecoveryLevel RECOVERABLE = fromString("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. - */ - public static final DeletionRecoveryLevel RECOVERABLE_PROTECTED_SUBSCRIPTION - = fromString("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. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE_PURGEABLE - = fromString("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. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE = fromString("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. - */ - public static final DeletionRecoveryLevel CUSTOMIZED_RECOVERABLE_PROTECTED_SUBSCRIPTION - = fromString("CustomizedRecoverable+ProtectedSubscription"); - - /** - * Creates a new instance of DeletionRecoveryLevel value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public DeletionRecoveryLevel() { - } - - /** - * Creates or finds a DeletionRecoveryLevel from its string representation. - * - * @param name a name to look for. - * @return the corresponding DeletionRecoveryLevel. - */ - public static DeletionRecoveryLevel fromString(String name) { - return fromString(name, DeletionRecoveryLevel.class); - } - - /** - * Gets known DeletionRecoveryLevel values. - * - * @return known DeletionRecoveryLevel values. - */ - public static Collection values() { - return values(DeletionRecoveryLevel.class); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java deleted file mode 100644 index ea1218e5c05f4..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key vault server error. - */ -@Immutable -public final class Error implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The key vault server error. - */ - private Error innerError; - - /** - * Creates an instance of Error class. - */ - public Error() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - public Error getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Error from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Error if the JsonReader was pointing to an instance of it, or null if it was pointing to - * JSON null. - * @throws IOException If an error occurs while reading the Error. - */ - public static Error fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Error deserializedError = new Error(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedError.innerError = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java deleted file mode 100644 index 67f004980d7f9..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private Error error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public Error getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 50b18ba8ce65c..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - * @param value the deserialized response value. - */ - public KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java deleted file mode 100644 index 33a3b08b61223..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The secret management attributes. - */ -@Fluent -public final class SecretAttributes extends Attributes { - /* - * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. - */ - private Integer recoverableDays; - - /* - * Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains - * 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the - * secret, at the end of the retention interval. - */ - private DeletionRecoveryLevel recoveryLevel; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /* - * Creation time in UTC. - */ - private Long created; - - /** - * Creates an instance of SecretAttributes class. - */ - public SecretAttributes() { - } - - /** - * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when - * softDelete enabled, otherwise 0. - * - * @return the recoverableDays value. - */ - public Integer getRecoverableDays() { - return this.recoverableDays; - } - - /** - * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for secrets in the - * current vault. If it contains 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, - * only the system can purge the secret, at the end of the retention interval. - * - * @return the recoveryLevel value. - */ - public DeletionRecoveryLevel getRecoveryLevel() { - return this.recoveryLevel; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - @Override - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - @Override - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * {@inheritDoc} - */ - @Override - public SecretAttributes setEnabled(Boolean enabled) { - super.setEnabled(enabled); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SecretAttributes setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SecretAttributes setExpires(OffsetDateTime expires) { - super.setExpires(expires); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", isEnabled()); - if (getNotBefore() != null) { - jsonWriter.writeNumberField("nbf", getNotBefore().toEpochSecond()); - } - if (getExpires() != null) { - jsonWriter.writeNumberField("exp", getExpires().toEpochSecond()); - } - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretAttributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretAttributes if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SecretAttributes. - */ - public static SecretAttributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretAttributes deserializedSecretAttributes = new SecretAttributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedSecretAttributes.setEnabled(reader.getNullable(JsonReader::getBoolean)); - } else if ("nbf".equals(fieldName)) { - Long notBeforeHolder = reader.getNullable(JsonReader::getLong); - if (notBeforeHolder != null) { - deserializedSecretAttributes.setNotBefore( - OffsetDateTime.ofInstant(Instant.ofEpochSecond(notBeforeHolder), ZoneOffset.UTC)); - } - } else if ("exp".equals(fieldName)) { - Long expiresHolder = reader.getNullable(JsonReader::getLong); - if (expiresHolder != null) { - deserializedSecretAttributes - .setExpires(OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiresHolder), ZoneOffset.UTC)); - } - } else if ("created".equals(fieldName)) { - deserializedSecretAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedSecretAttributes.updated = reader.getNullable(JsonReader::getLong); - } else if ("recoverableDays".equals(fieldName)) { - deserializedSecretAttributes.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("recoveryLevel".equals(fieldName)) { - deserializedSecretAttributes.recoveryLevel = DeletionRecoveryLevel.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java deleted file mode 100644 index 86f56a6754f4e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * A secret consisting of a value, id and its attributes. - */ -@Fluent -public class SecretBundle implements JsonSerializable { - /* - * The secret value. - */ - private String value; - - /* - * The secret id. - */ - private String id; - - /* - * The content type of the secret. - */ - private String contentType; - - /* - * The secret management attributes. - */ - private SecretAttributes attributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV - * certificate. - */ - private String kid; - - /* - * True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed - * will be true. - */ - private Boolean managed; - - /** - * Creates an instance of SecretBundle class. - */ - public SecretBundle() { - } - - /** - * Get the value property: The secret value. - * - * @return the value value. - */ - public String getValue() { - return this.value; - } - - /** - * Set the value property: The secret value. - * - * @param value the value value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setValue(String value) { - this.value = value; - return this; - } - - /** - * Get the id property: The secret id. - * - * @return the id value. - */ - public String getId() { - return this.id; - } - - /** - * Set the id property: The secret id. - * - * @param id the id value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setId(String id) { - this.id = id; - return this; - } - - /** - * Get the contentType property: The content type of the secret. - * - * @return the contentType value. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType property: The content type of the secret. - * - * @param contentType the contentType value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the attributes property: The secret management attributes. - * - * @return the attributes value. - */ - public SecretAttributes getAttributes() { - return this.attributes; - } - - /** - * Set the attributes property: The secret management attributes. - * - * @param attributes the attributes value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setAttributes(SecretAttributes attributes) { - this.attributes = attributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding - * key backing the KV certificate. - * - * @return the kid value. - */ - public String getKid() { - return this.kid; - } - - /** - * Set the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding - * key backing the KV certificate. - * - * @param kid the kid value to set. - * @return the SecretBundle object itself. - */ - SecretBundle setKid(String kid) { - this.kid = kid; - return this; - } - - /** - * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Set the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the SecretBundle object itself. - */ - SecretBundle setManaged(Boolean managed) { - this.managed = managed; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", this.value); - jsonWriter.writeStringField("id", this.id); - jsonWriter.writeStringField("contentType", this.contentType); - jsonWriter.writeJsonField("attributes", this.attributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretBundle from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretBundle if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SecretBundle. - */ - public static SecretBundle fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretBundle deserializedSecretBundle = new SecretBundle(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedSecretBundle.value = reader.getString(); - } else if ("id".equals(fieldName)) { - deserializedSecretBundle.id = reader.getString(); - } else if ("contentType".equals(fieldName)) { - deserializedSecretBundle.contentType = reader.getString(); - } else if ("attributes".equals(fieldName)) { - deserializedSecretBundle.attributes = SecretAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSecretBundle.tags = tags; - } else if ("kid".equals(fieldName)) { - deserializedSecretBundle.kid = reader.getString(); - } else if ("managed".equals(fieldName)) { - deserializedSecretBundle.managed = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretBundle; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java deleted file mode 100644 index a999777b0f372..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * The secret item containing secret metadata. - */ -@Fluent -public class SecretItem implements JsonSerializable { - /* - * Secret identifier. - */ - private String id; - - /* - * The secret management attributes. - */ - private SecretAttributes attributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * Type of the secret value such as a password. - */ - private String contentType; - - /* - * True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will - * be true. - */ - private Boolean managed; - - /** - * Creates an instance of SecretItem class. - */ - public SecretItem() { - } - - /** - * Get the id property: Secret identifier. - * - * @return the id value. - */ - public String getId() { - return this.id; - } - - /** - * Set the id property: Secret identifier. - * - * @param id the id value to set. - * @return the SecretItem object itself. - */ - public SecretItem setId(String id) { - this.id = id; - return this; - } - - /** - * Get the attributes property: The secret management attributes. - * - * @return the attributes value. - */ - public SecretAttributes getAttributes() { - return this.attributes; - } - - /** - * Set the attributes property: The secret management attributes. - * - * @param attributes the attributes value to set. - * @return the SecretItem object itself. - */ - public SecretItem setAttributes(SecretAttributes attributes) { - this.attributes = attributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretItem object itself. - */ - public SecretItem setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the contentType property: Type of the secret value such as a password. - * - * @return the contentType value. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType property: Type of the secret value such as a password. - * - * @param contentType the contentType value to set. - * @return the SecretItem object itself. - */ - public SecretItem setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @return the managed value. - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Set the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the SecretItem object itself. - */ - SecretItem setManaged(Boolean managed) { - this.managed = managed; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", this.id); - jsonWriter.writeJsonField("attributes", this.attributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("contentType", this.contentType); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretItem from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretItem if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. - * @throws IOException If an error occurs while reading the SecretItem. - */ - public static SecretItem fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretItem deserializedSecretItem = new SecretItem(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedSecretItem.id = reader.getString(); - } else if ("attributes".equals(fieldName)) { - deserializedSecretItem.attributes = SecretAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSecretItem.tags = tags; - } else if ("contentType".equals(fieldName)) { - deserializedSecretItem.contentType = reader.getString(); - } else if ("managed".equals(fieldName)) { - deserializedSecretItem.managed = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretItem; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java deleted file mode 100644 index 3b55cb272de6d..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The secret list result. - */ -@Immutable -public final class SecretListResult implements JsonSerializable { - /* - * A response message containing a list of secrets in the key vault along with a link to the next page of secrets. - */ - private List value; - - /* - * The URL to get the next set of secrets. - */ - private String nextLink; - - /** - * Creates an instance of SecretListResult class. - */ - public SecretListResult() { - } - - /** - * Get the value property: A response message containing a list of secrets in the key vault along with a link to the - * next page of secrets. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of secrets. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretListResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SecretListResult. - */ - public static SecretListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretListResult deserializedSecretListResult = new SecretListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> SecretItem.fromJson(reader1)); - deserializedSecretListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSecretListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java deleted file mode 100644 index 12e7f9132c164..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Properties of the key backing a certificate. - */ -@Fluent -public final class SecretProperties implements JsonSerializable { - /* - * The media type (MIME type). - */ - private String contentType; - - /** - * Creates an instance of SecretProperties class. - */ - public SecretProperties() { - } - - /** - * Get the contentType property: The media type (MIME type). - * - * @return the contentType value. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType property: The media type (MIME type). - * - * @param contentType the contentType value to set. - * @return the SecretProperties object itself. - */ - public SecretProperties setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("contentType", this.contentType); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretProperties if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SecretProperties. - */ - public static SecretProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretProperties deserializedSecretProperties = new SecretProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - deserializedSecretProperties.contentType = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretProperties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java deleted file mode 100644 index b4bd7300816fe..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Objects; - -/** - * The secret restore parameters. - */ -@Fluent -public final class SecretRestoreParameters implements JsonSerializable { - /* - * The backup blob associated with a secret bundle. - */ - private Base64Url secretBundleBackup; - - /** - * Creates an instance of SecretRestoreParameters class. - */ - public SecretRestoreParameters() { - } - - /** - * Get the secretBundleBackup property: The backup blob associated with a secret bundle. - * - * @return the secretBundleBackup value. - */ - public byte[] getSecretBundleBackup() { - if (this.secretBundleBackup == null) { - return null; - } - return this.secretBundleBackup.decodedBytes(); - } - - /** - * Set the secretBundleBackup property: The backup blob associated with a secret bundle. - * - * @param secretBundleBackup the secretBundleBackup value to set. - * @return the SecretRestoreParameters object itself. - */ - public SecretRestoreParameters setSecretBundleBackup(byte[] secretBundleBackup) { - if (secretBundleBackup == null) { - this.secretBundleBackup = null; - } else { - this.secretBundleBackup = Base64Url.encode(CoreUtils.clone(secretBundleBackup)); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", Objects.toString(this.secretBundleBackup, null)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretRestoreParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretRestoreParameters if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SecretRestoreParameters. - */ - public static SecretRestoreParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretRestoreParameters deserializedSecretRestoreParameters = new SecretRestoreParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedSecretRestoreParameters.secretBundleBackup - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretRestoreParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java deleted file mode 100644 index 2e968c4ee8992..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * The secret set parameters. - */ -@Fluent -public final class SecretSetParameters implements JsonSerializable { - /* - * The value of the secret. - */ - private String value; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /* - * Type of the secret value such as a password. - */ - private String secretContentType; - - /* - * The secret management attributes. - */ - private SecretAttributes secretAttributes; - - /** - * Creates an instance of SecretSetParameters class. - */ - public SecretSetParameters() { - } - - /** - * Get the value property: The value of the secret. - * - * @return the value value. - */ - public String getValue() { - return this.value; - } - - /** - * Set the value property: The value of the secret. - * - * @param value the value value to set. - * @return the SecretSetParameters object itself. - */ - public SecretSetParameters setValue(String value) { - this.value = value; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretSetParameters object itself. - */ - public SecretSetParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the secretContentType property: Type of the secret value such as a password. - * - * @return the secretContentType value. - */ - public String getSecretContentType() { - return this.secretContentType; - } - - /** - * Set the secretContentType property: Type of the secret value such as a password. - * - * @param secretContentType the secretContentType value to set. - * @return the SecretSetParameters object itself. - */ - public SecretSetParameters setSecretContentType(String secretContentType) { - this.secretContentType = secretContentType; - return this; - } - - /** - * Get the secretAttributes property: The secret management attributes. - * - * @return the secretAttributes value. - */ - public SecretAttributes getSecretAttributes() { - return this.secretAttributes; - } - - /** - * Set the secretAttributes property: The secret management attributes. - * - * @param secretAttributes the secretAttributes value to set. - * @return the SecretSetParameters object itself. - */ - public SecretSetParameters setSecretAttributes(SecretAttributes secretAttributes) { - this.secretAttributes = secretAttributes; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", this.value); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("contentType", this.secretContentType); - jsonWriter.writeJsonField("attributes", this.secretAttributes); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretSetParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretSetParameters if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SecretSetParameters. - */ - public static SecretSetParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretSetParameters deserializedSecretSetParameters = new SecretSetParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedSecretSetParameters.value = reader.getString(); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSecretSetParameters.tags = tags; - } else if ("contentType".equals(fieldName)) { - deserializedSecretSetParameters.secretContentType = reader.getString(); - } else if ("attributes".equals(fieldName)) { - deserializedSecretSetParameters.secretAttributes = SecretAttributes.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretSetParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java deleted file mode 100644 index d0b2f5eed2f27..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * The secret update parameters. - */ -@Fluent -public final class SecretUpdateParameters implements JsonSerializable { - /* - * Type of the secret value such as a password. - */ - private String secretContentType; - - /* - * The secret management attributes. - */ - private SecretAttributes secretAttributes; - - /* - * Application specific metadata in the form of key-value pairs. - */ - private Map tags; - - /** - * Creates an instance of SecretUpdateParameters class. - */ - public SecretUpdateParameters() { - } - - /** - * Get the secretContentType property: Type of the secret value such as a password. - * - * @return the secretContentType value. - */ - public String getSecretContentType() { - return this.secretContentType; - } - - /** - * Set the secretContentType property: Type of the secret value such as a password. - * - * @param secretContentType the secretContentType value to set. - * @return the SecretUpdateParameters object itself. - */ - public SecretUpdateParameters setSecretContentType(String secretContentType) { - this.secretContentType = secretContentType; - return this; - } - - /** - * Get the secretAttributes property: The secret management attributes. - * - * @return the secretAttributes value. - */ - public SecretAttributes getSecretAttributes() { - return this.secretAttributes; - } - - /** - * Set the secretAttributes property: The secret management attributes. - * - * @param secretAttributes the secretAttributes value to set. - * @return the SecretUpdateParameters object itself. - */ - public SecretUpdateParameters setSecretAttributes(SecretAttributes secretAttributes) { - this.secretAttributes = secretAttributes; - return this; - } - - /** - * Get the tags property: Application specific metadata in the form of key-value pairs. - * - * @return the tags value. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretUpdateParameters object itself. - */ - public SecretUpdateParameters setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("contentType", this.secretContentType); - jsonWriter.writeJsonField("attributes", this.secretAttributes); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretUpdateParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretUpdateParameters if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the SecretUpdateParameters. - */ - public static SecretUpdateParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretUpdateParameters deserializedSecretUpdateParameters = new SecretUpdateParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - deserializedSecretUpdateParameters.secretContentType = reader.getString(); - } else if ("attributes".equals(fieldName)) { - deserializedSecretUpdateParameters.secretAttributes = SecretAttributes.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSecretUpdateParameters.tags = tags; - } else { - reader.skipChildren(); - } - } - - return deserializedSecretUpdateParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java deleted file mode 100644 index daa9d2230aed8..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.secrets.implementation.models; - -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.security.keyvault.secrets.implementation.DeletedSecretHelper; -import com.azure.security.keyvault.secrets.implementation.SecretPropertiesHelper; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Objects; -import java.util.function.Consumer; - -/** - * Utility methods for KeyVault Secrets models. - */ -public final class SecretsModelsUtils { - private static final ClientLogger LOGGER = new ClientLogger(SecretsModelsUtils.class); - - public static SecretAttributes createSecretAttributes(SecretProperties secretProperties) { - if (secretProperties == null) { - return null; - } - - return new SecretAttributes().setEnabled(secretProperties.isEnabled()) - .setNotBefore(secretProperties.getNotBefore()) - .setExpires(secretProperties.getExpiresOn()); - } - - public static KeyVaultSecret createKeyVaultSecret(SecretBundle secretBundle) { - if (secretBundle == null) { - return null; - } - - KeyVaultSecret keyVaultSecret = new KeyVaultSecret(null, secretBundle.getValue()); - setSecretPropertiesValues(secretBundle, keyVaultSecret.getProperties()); - - return keyVaultSecret; - } - - public static SecretProperties createSecretProperties(SecretBundle secretBundle) { - if (secretBundle == null) { - return null; - } - - SecretProperties secretProperties = new SecretProperties(); - setSecretPropertiesValues(secretBundle, secretProperties); - - return secretProperties; - } - - private static void setSecretPropertiesValues(SecretBundle secretBundle, SecretProperties secretProperties) { - secretProperties.setContentType(secretBundle.getContentType()).setTags(secretBundle.getTags()); - - SecretPropertiesHelper.setId(secretProperties, secretBundle.getId()); - SecretPropertiesHelper.setKeyId(secretProperties, secretBundle.getKid()); - SecretPropertiesHelper.setManaged(secretProperties, secretBundle.isManaged()); - - SecretAttributes secretAttributes = secretBundle.getAttributes(); - if (secretAttributes != null) { - secretProperties.setEnabled(secretAttributes.isEnabled()) - .setExpiresOn(secretAttributes.getExpires()) - .setNotBefore(secretAttributes.getNotBefore()); - - SecretPropertiesHelper.setCreatedOn(secretProperties, secretAttributes.getCreated()); - SecretPropertiesHelper.setUpdatedOn(secretProperties, secretAttributes.getUpdated()); - SecretPropertiesHelper.setRecoveryLevel(secretProperties, - Objects.toString(secretAttributes.getRecoveryLevel(), null)); - SecretPropertiesHelper.setRecoverableDays(secretProperties, secretAttributes.getRecoverableDays()); - } - - unpackId(secretBundle.getId(), name -> SecretPropertiesHelper.setName(secretProperties, name), - version -> SecretPropertiesHelper.setVersion(secretProperties, version)); - } - - public static SecretProperties createSecretProperties(SecretItem secretItem) { - if (secretItem == null) { - return null; - } - - SecretProperties secretProperties = new SecretProperties(); - setSecretPropertiesValues(secretItem, secretProperties); - - return secretProperties; - } - - private static void setSecretPropertiesValues(SecretItem secretItem, SecretProperties secretProperties) { - secretProperties.setContentType(secretItem.getContentType()).setTags(secretItem.getTags()); - - SecretPropertiesHelper.setId(secretProperties, secretItem.getId()); - SecretPropertiesHelper.setManaged(secretProperties, secretItem.isManaged()); - - SecretAttributes secretAttributes = secretItem.getAttributes(); - if (secretAttributes != null) { - secretProperties.setEnabled(secretAttributes.isEnabled()) - .setExpiresOn(secretAttributes.getExpires()) - .setNotBefore(secretAttributes.getNotBefore()); - - SecretPropertiesHelper.setCreatedOn(secretProperties, secretAttributes.getCreated()); - SecretPropertiesHelper.setUpdatedOn(secretProperties, secretAttributes.getUpdated()); - SecretPropertiesHelper.setRecoveryLevel(secretProperties, - Objects.toString(secretAttributes.getRecoveryLevel(), null)); - SecretPropertiesHelper.setRecoverableDays(secretProperties, secretAttributes.getRecoverableDays()); - } - - unpackId(secretItem.getId(), name -> SecretPropertiesHelper.setName(secretProperties, name), - version -> SecretPropertiesHelper.setVersion(secretProperties, version)); - } - - public static DeletedSecret createDeletedSecret(DeletedSecretBundle deletedSecretBundle) { - if (deletedSecretBundle == null) { - return null; - } - - DeletedSecret deletedSecret = new DeletedSecret(); - setSecretPropertiesValues(deletedSecretBundle, deletedSecret.getProperties()); - - DeletedSecretHelper.setRecoveryId(deletedSecret, deletedSecretBundle.getRecoveryId()); - DeletedSecretHelper.setScheduledPurgeDate(deletedSecret, deletedSecretBundle.getScheduledPurgeDate()); - DeletedSecretHelper.setDeletedOn(deletedSecret, deletedSecretBundle.getDeletedDate()); - - return deletedSecret; - } - - public static DeletedSecret createDeletedSecret(DeletedSecretItem deletedSecretItem) { - if (deletedSecretItem == null) { - return null; - } - - DeletedSecret deletedSecret = new DeletedSecret(); - setSecretPropertiesValues(deletedSecretItem, deletedSecret.getProperties()); - - DeletedSecretHelper.setRecoveryId(deletedSecret, deletedSecretItem.getRecoveryId()); - DeletedSecretHelper.setScheduledPurgeDate(deletedSecret, deletedSecretItem.getScheduledPurgeDate()); - DeletedSecretHelper.setDeletedOn(deletedSecret, deletedSecretItem.getDeletedDate()); - - return deletedSecret; - } - - public static void unpackId(String id, Consumer nameConsumer, Consumer versionConsumer) { - if (CoreUtils.isNullOrEmpty(id)) { - return; - } - - try { - URL url = new URL(id); - String[] tokens = url.getPath().split("/"); - - if (tokens.length >= 3) { - nameConsumer.accept(tokens[2]); - } - - if (tokens.length >= 4) { - versionConsumer.accept(tokens[3]); - } - } catch (MalformedURLException e) { - // Should never come here. - LOGGER.error("Received Malformed Secret Id URL from KV Service"); - } - } - - public static OffsetDateTime epochToOffsetDateTime(JsonReader epochReader) throws IOException { - Instant instant = Instant.ofEpochMilli(epochReader.getLong() * 1000L); - return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); - } - - private SecretsModelsUtils() { - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java deleted file mode 100644 index e43601b6a57b2..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the data models for SecretClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - */ -package com.azure.security.keyvault.secrets.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java deleted file mode 100644 index e199af1c54cff..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the implementations for SecretClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. - */ -package com.azure.security.keyvault.secrets.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java deleted file mode 100644 index 9b1359b1ca1d6..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.models; - -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.secrets.SecretAsyncClient; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.implementation.DeletedSecretHelper; -import com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils; - -import java.io.IOException; -import java.time.OffsetDateTime; - -/** - * Deleted Secret is the resource consisting of name, recovery id, deleted date, scheduled purge date and its attributes - * inherited from {@link KeyVaultSecret}. - * It is managed by Secret Service. - * - * @see SecretClient - * @see SecretAsyncClient - */ -public final class DeletedSecret extends KeyVaultSecret { - - static { - DeletedSecretHelper.setAccessor(new DeletedSecretHelper.DeletedSecretAccessor() { - @Override - public void setRecoveryId(DeletedSecret deletedSecret, String recoveryId) { - deletedSecret.recoveryId = recoveryId; - } - - @Override - public void setScheduledPurgeDate(DeletedSecret deletedSecret, OffsetDateTime scheduledPurgeDate) { - deletedSecret.scheduledPurgeDate = scheduledPurgeDate; - } - - @Override - public void setDeletedOn(DeletedSecret deletedSecret, OffsetDateTime deletedOn) { - deletedSecret.deletedOn = deletedOn; - } - }); - } - - /** - * The url of the recovery object, used to identify and recover the deleted secret. - */ - private String recoveryId; - - /** - * The time when the secret is scheduled to be purged, in UTC. - */ - private OffsetDateTime scheduledPurgeDate; - - /** - * The time when the secret was deleted, in UTC. - */ - private OffsetDateTime deletedOn; - - /** - * Creates a new instance of {@link DeletedSecret}. - */ - public DeletedSecret() { - } - - /** - * Get the recoveryId identifier. - * - * @return the recoveryId identifier. - */ - public String getRecoveryId() { - return this.recoveryId; - } - - /** - * Get the scheduled purge UTC time. - * - * @return the scheduledPurgeDate UTC time. - */ - public OffsetDateTime getScheduledPurgeDate() { - return scheduledPurgeDate; - } - - /** - * Get the deleted UTC time. - * - * @return the deletedDate UTC time. - */ - public OffsetDateTime getDeletedOn() { - return this.deletedOn; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("value", getValue()) - .writeStringField("recoveryId", recoveryId) - .writeEndObject(); - } - - /** - * Reads an instance of {@link DeletedSecret} from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of {@link DeletedSecret} if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the {@link DeletedSecret}. - */ - public static DeletedSecret fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedSecret deletedSecret = new DeletedSecret(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deletedSecret.value = reader.getString(); - } else if ("id".equals(fieldName)) { - deletedSecret.properties.id = reader.getString(); - SecretsModelsUtils.unpackId(deletedSecret.properties.id, - name -> deletedSecret.properties.name = name, - version -> deletedSecret.properties.version = version); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - SecretProperties.deserializeAttributes(reader, deletedSecret.properties); - } else if ("managed".equals(fieldName)) { - deletedSecret.properties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("kid".equals(fieldName)) { - deletedSecret.properties.keyId = reader.getString(); - } else if ("contentType".equals(fieldName)) { - deletedSecret.properties.contentType = reader.getString(); - } else if ("tags".equals(fieldName)) { - deletedSecret.properties.tags = reader.readMap(JsonReader::getString); - } else if ("recoveryId".equals(fieldName)) { - deletedSecret.recoveryId = reader.getString(); - } else if ("scheduledPurgeDate".equals(fieldName)) { - deletedSecret.scheduledPurgeDate = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else if ("deletedDate".equals(fieldName)) { - deletedSecret.deletedOn = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else { - reader.skipChildren(); - } - } - - return deletedSecret; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java deleted file mode 100644 index a56a11ae0d522..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.secrets.SecretAsyncClient; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils; - -import java.io.IOException; -import java.util.Objects; - -/** - * Secret is the resource consisting of name, value and its attributes specified in {@link SecretProperties}. - * It is managed by Secret Service. - * - * @see SecretClient - * @see SecretAsyncClient - */ -@Fluent -public class KeyVaultSecret implements JsonSerializable { - - /** - * The value of the secret. - */ - String value; - - /** - * The secret properties. - */ - SecretProperties properties; - - /** - * Creates an empty instance of the Secret. - */ - KeyVaultSecret() { - properties = new SecretProperties(); - } - - /** - * Creates a Secret with {@code name} and {@code value}. - * - * @param name The name of the secret. - * @param value the value of the secret. - */ - public KeyVaultSecret(String name, String value) { - properties = new SecretProperties(name); - this.value = value; - } - - /** - * Get the value of the secret. - * - * @return the secret value - */ - public String getValue() { - return this.value; - } - - /** - * Get the secret identifier. - * - * @return the secret identifier. - */ - public String getId() { - return properties.getId(); - } - - /** - * Get the secret name. - * - * @return the secret name. - */ - public String getName() { - return properties.getName(); - } - - /** - * Get the secret properties - * @return the Secret properties - */ - public SecretProperties getProperties() { - return this.properties; - } - - /** - * Set the secret properties - * @param properties The Secret properties - * @throws NullPointerException if {@code properties} is null. - * @return the updated secret object - */ - public KeyVaultSecret setProperties(SecretProperties properties) { - Objects.requireNonNull(properties); - properties.name = this.properties.name; - this.properties = properties; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject().writeStringField("value", value).writeEndObject(); - } - - /** - * Reads an instance of {@link KeyVaultSecret} from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of {@link KeyVaultSecret} if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IOException If an error occurs while reading the {@link KeyVaultSecret}. - */ - public static KeyVaultSecret fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultSecret keyVaultSecret = new KeyVaultSecret(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - keyVaultSecret.value = reader.getString(); - } else if ("id".equals(fieldName)) { - keyVaultSecret.properties.id = reader.getString(); - SecretsModelsUtils.unpackId(keyVaultSecret.properties.id, - name -> keyVaultSecret.properties.name = name, - version -> keyVaultSecret.properties.version = version); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - SecretProperties.deserializeAttributes(reader, keyVaultSecret.properties); - } else if ("managed".equals(fieldName)) { - keyVaultSecret.properties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("kid".equals(fieldName)) { - keyVaultSecret.properties.keyId = reader.getString(); - } else if ("contentType".equals(fieldName)) { - keyVaultSecret.properties.contentType = reader.getString(); - } else if ("tags".equals(fieldName)) { - keyVaultSecret.properties.tags = reader.readMap(JsonReader::getString); - } else { - reader.skipChildren(); - } - } - - return keyVaultSecret; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifier.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifier.java deleted file mode 100644 index 2f8eaa9cdbeeb..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifier.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.secrets.SecretAsyncClient; -import com.azure.security.keyvault.secrets.SecretClient; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * Information about a {@link KeyVaultSecret} parsed from the secret URL. You can use this information when calling - * methods of {@link SecretClient} or {@link SecretAsyncClient}. - */ -@Immutable -public final class KeyVaultSecretIdentifier { - private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSecretIdentifier.class); - - private final String sourceId; - private final String vaultUrl; - private final String name; - private final String version; - - /** - * Create a new {@link KeyVaultSecretIdentifier} from a given Key Vault identifier. - * - *

Some examples: - * - *

    - *
  • https://{key-vault-name}.vault.azure.net/secrets/{secret-name}
  • - *
  • https://{key-vault-name}.vault.azure.net/secrets/{secret-name}/pending
  • - *
  • https://{key-vault-name}.vault.azure.net/secrets/{secret-name}/{unique-version-id}
  • - *
  • https://{key-vault-name}.vault.azure.net/deletedsecrets/{deleted-secret-name}
  • - *
- * - * @param sourceId The identifier to extract information from. - * - * @throws IllegalArgumentException If {@code sourceId} is an invalid Key Vault Secret identifier. - * @throws NullPointerException If {@code sourceId} is {@code null}. - */ - public KeyVaultSecretIdentifier(String sourceId) { - if (sourceId == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'sourceId' cannot be null.")); - } - - try { - final URL url = new URL(sourceId); - // We expect an sourceId with either 3 or 4 path segments: key vault + collection + name + "pending"/version - final String[] pathSegments = url.getPath().split("/"); - - // More or less segments in the URI than expected. - if (pathSegments.length != 3 && pathSegments.length != 4) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("'sourceId' is not a valid Key Vault identifier.")); - } - - this.sourceId = sourceId; - this.vaultUrl = url.getProtocol() + "://" + url.getHost(); - this.name = pathSegments[2]; - this.version = pathSegments.length == 4 ? pathSegments[3] : null; - } catch (MalformedURLException e) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("'sourceId' is not a valid Key Vault identifier.", e)); - } - } - - /** - * Gets the key identifier used to create this object - * - * @return The secret identifier. - */ - public String getSourceId() { - return sourceId; - } - - /** - * Gets the URL of the Key Vault. - * - * @return The Key Vault URL. - */ - public String getVaultUrl() { - return vaultUrl; - } - - /** - * Gets the name of the secret. - * - * @return The secret name. - */ - public String getName() { - return name; - } - - /** - * Gets the optional version of the secret. - * - * @return The secret version. - */ - public String getVersion() { - return version; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java deleted file mode 100644 index 554043fbb5c72..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java +++ /dev/null @@ -1,439 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.security.keyvault.secrets.SecretAsyncClient; -import com.azure.security.keyvault.secrets.SecretClient; -import com.azure.security.keyvault.secrets.implementation.SecretPropertiesHelper; -import com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils; - -import java.io.IOException; -import java.time.OffsetDateTime; -import java.util.Map; -import java.util.Objects; - -/** - * SecretProperties is the resource containing all the properties of the secret except its value. - * It is managed by the Secret Service. - * - * @see SecretClient - * @see SecretAsyncClient - */ -@Fluent -public class SecretProperties implements JsonSerializable { - static { - SecretPropertiesHelper.setAccessor(new SecretPropertiesHelper.SecretPropertiesAccessor() { - @Override - public void setId(SecretProperties properties, String id) { - properties.id = id; - } - - @Override - public void setVersion(SecretProperties properties, String version) { - properties.version = version; - } - - @Override - public void setCreatedOn(SecretProperties properties, OffsetDateTime createdOn) { - properties.createdOn = createdOn; - } - - @Override - public void setUpdatedOn(SecretProperties properties, OffsetDateTime updatedOn) { - properties.updatedOn = updatedOn; - } - - @Override - public void setName(SecretProperties properties, String name) { - properties.name = name; - } - - @Override - public void setRecoveryLevel(SecretProperties properties, String recoveryLevel) { - properties.recoveryLevel = recoveryLevel; - } - - @Override - public void setKeyId(SecretProperties properties, String keyId) { - properties.keyId = keyId; - } - - @Override - public void setManaged(SecretProperties properties, Boolean managed) { - properties.managed = managed; - } - - @Override - public void setRecoverableDays(SecretProperties properties, Integer recoverableDays) { - properties.recoverableDays = recoverableDays; - } - }); - } - - /** - * The secret id. - */ - String id; - - /** - * The secret version. - */ - String version; - - /** - * Determines whether the object is enabled. - */ - Boolean enabled; - - /** - * Not before date in UTC. - */ - OffsetDateTime notBefore; - - /** - * Expiry date in UTC. - */ - OffsetDateTime expiresOn; - - /** - * Creation time in UTC. - */ - OffsetDateTime createdOn; - - /** - * Last updated time in UTC. - */ - OffsetDateTime updatedOn; - - /** - * The secret name. - */ - String name; - - /** - * Reflects the deletion recovery level currently in effect for secrets in - * the current vault. If it contains 'Purgeable', the secret can be - * permanently deleted by a privileged user; otherwise, only the system can - * purge the secret, at the end of the retention interval. Possible values - * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', - * 'Recoverable+ProtectedSubscription'. - */ - String recoveryLevel; - - /** - * The content type of the secret. - */ - String contentType; - - /** - * Application specific metadata in the form of key-value pairs. - */ - Map tags; - - /** - * If this is a secret backing a KV certificate, then this field specifies - * the corresponding key backing the KV certificate. - */ - String keyId; - - /** - * True if the secret's lifetime is managed by key vault. If this is a - * secret backing a certificate, then managed will be true. - */ - Boolean managed; - - /** - * The number of days a secret is retained before being deleted for a soft delete-enabled Key Vault. - */ - private Integer recoverableDays; - - SecretProperties(String secretName) { - this.name = secretName; - } - - /** - * Creates empty instance of SecretProperties. - */ - public SecretProperties() { - } - - /** - * Get the secret name. - * - * @return the name of the secret. - */ - public String getName() { - return this.name; - } - - /** - * Get the recovery level of the secret. - - * @return the recoveryLevel of the secret. - */ - public String getRecoveryLevel() { - return recoveryLevel; - } - - /** - * Get the enabled value. - * - * @return the enabled value - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled value. - * - * @param enabled The enabled value to set - * @throws NullPointerException if {@code enabled} is null. - * @return the SecretProperties object itself. - */ - public SecretProperties setEnabled(Boolean enabled) { - Objects.requireNonNull(enabled); - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore UTC time. - * - * @return the notBefore UTC time. - */ - public OffsetDateTime getNotBefore() { - return notBefore; - } - - /** - * Set the {@link OffsetDateTime notBefore} UTC time. - * - * @param notBefore The notBefore UTC time to set - * @return the SecretProperties object itself. - */ - public SecretProperties setNotBefore(OffsetDateTime notBefore) { - this.notBefore = notBefore; - return this; - } - - /** - * Get the Secret Expiry time in UTC. - * - * @return the expires UTC time. - */ - public OffsetDateTime getExpiresOn() { - if (this.expiresOn == null) { - return null; - } - return this.expiresOn; - } - - /** - * Set the {@link OffsetDateTime expires} UTC time. - * - * @param expiresOn The expiry time to set for the secret. - * @return the SecretProperties object itself. - */ - public SecretProperties setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - return this; - } - - /** - * Get the the UTC time at which secret was created. - * - * @return the created UTC time. - */ - public OffsetDateTime getCreatedOn() { - return createdOn; - } - - /** - * Get the UTC time at which secret was last updated. - * - * @return the last updated UTC time. - */ - public OffsetDateTime getUpdatedOn() { - return updatedOn; - } - - /** - * Get the secret identifier. - * - * @return the secret identifier. - */ - public String getId() { - return this.id; - } - - /** - * Get the content type. - * - * @return the content type. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType. - * - * @param contentType The contentType to set - * @return the updated SecretProperties object itself. - */ - public SecretProperties setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Get the tags associated with the secret. - * - * @return the value of the tags. - */ - public Map getTags() { - return this.tags; - } - - /** - * Set the tags to be associated with the secret. - * - * @param tags The tags to set - * @return the updated SecretProperties object itself. - */ - public SecretProperties setTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the keyId identifier. - * - * @return the keyId identifier. - */ - public String getKeyId() { - return this.keyId; - } - - /** - * Get the managed value. - * - * @return the managed value - */ - public Boolean isManaged() { - return this.managed; - } - - /** - * Get the version of the secret. - * - * @return the version of the secret. - */ - public String getVersion() { - return this.version; - } - - /** - * Gets the number of days a secret is retained before being deleted for a soft delete-enabled Key Vault. - * @return the recoverable days. - */ - public Integer getRecoverableDays() { - return recoverableDays; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("contentType", contentType) - .writeMapField("tags", tags, JsonWriter::writeString) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link SecretProperties}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return An instance of {@link SecretProperties} that the JSON stream represented, may return null. - * @throws IOException If a {@link SecretProperties} fails to be read from the {@code jsonReader}. - */ - public static SecretProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretProperties secretProperties = new SecretProperties(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - secretProperties.contentType = reader.getString(); - } else if ("tags".equals(fieldName)) { - secretProperties.tags = reader.readMap(JsonReader::getString); - } else if ("kid".equals(fieldName)) { - secretProperties.keyId = reader.getString(); - } else if ("managed".equals(fieldName)) { - secretProperties.managed = reader.getNullable(JsonReader::getBoolean); - } else if ("recoverableDays".equals(fieldName)) { - secretProperties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("attributes".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - deserializeAttributes(reader, secretProperties); - } else if ("id".equals(fieldName)) { - secretProperties.id = reader.getString(); - SecretsModelsUtils.unpackId(secretProperties.id, name -> secretProperties.name = name, - version -> secretProperties.version = version); - } else { - reader.skipChildren(); - } - } - - return secretProperties; - }); - } - - static void deserializeAttributes(JsonReader reader, SecretProperties secretProperties) throws IOException { - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - secretProperties.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - secretProperties.notBefore = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else if ("exp".equals(fieldName)) { - secretProperties.expiresOn = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else if ("created".equals(fieldName)) { - secretProperties.createdOn = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else if ("updated".equals(fieldName)) { - secretProperties.updatedOn = reader.getNullable(SecretsModelsUtils::epochToOffsetDateTime); - } else if ("recoveryLevel".equals(fieldName)) { - secretProperties.recoveryLevel = reader.getString(); - } else if ("contentType".equals(fieldName)) { - String contentType = reader.getString(); - secretProperties.contentType = contentType == null ? secretProperties.contentType : contentType; - } else if ("keyId".equals(fieldName)) { - String keyId = reader.getString(); - secretProperties.keyId = keyId == null ? secretProperties.keyId : keyId; - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(JsonReader::getString); - secretProperties.tags = tags == null ? secretProperties.tags : tags; - } else if ("managed".equals(fieldName)) { - Boolean managed = reader.getNullable(JsonReader::getBoolean); - secretProperties.managed = managed == null ? secretProperties.managed : managed; - } else if ("recoverableDays".equals(fieldName)) { - secretProperties.recoverableDays = reader.getNullable(JsonReader::getInt); - } else if ("id".equals(fieldName)) { - secretProperties.id = reader.getString(); - SecretsModelsUtils.unpackId(secretProperties.id, name -> secretProperties.name = name, - version -> secretProperties.version = version); - } else { - reader.skipChildren(); - } - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/package-info.java deleted file mode 100644 index 4faed30de5b17..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing classes used for representing secrets, deleted secrets and their attributes in - * Azure Key Vault. - */ -package com.azure.security.keyvault.secrets.models; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java deleted file mode 100644 index 94fd5bc936d05..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - *

Azure Key Vault is a cloud-based service - * provided by Microsoft Azure that allows users to store, manage, and access secrets, such as passwords, certificates, - * and other sensitive information, securely in the cloud. The service provides a centralized and secure location for - * storing secrets, which can be accessed by authorized applications and users with appropriate permissions. - * Azure Key Vault Secrets offers several key features, including:

- *
    - *
  • Secret management: It allows users to store, manage, and access secrets securely, and provides features such - * as versioning, backup, and restoration.
  • - *
  • Access control: It offers - * - * role-based access control (RBAC) and enables users to grant specific permissions to access secrets to - * other users, applications, or services.
  • - *
  • Integration with other Azure services: Azure Key Vault Secrets can be integrated with other Azure services, - * such as Azure App Service, Azure Functions, and Azure Virtual Machines, to simplify the process of securing - * sensitive information.
  • - *
  • High availability and scalability: The service is designed to provide high availability and scalability, - * with the ability to handle large volumes of secrets and requests.
  • - *
- * - *

The Azure Key Vault Secrets client library allows developers to interact with the Azure Key Vault service - * from their applications. The library provides a set of APIs that enable developers to securely store, manage, and - * retrieve secrets in a key vault, and supports operations such as creating, updating, deleting, and retrieving secrets.

- * - *

Key Concepts:

- * - *

What is a Secret Client?

- *

The secret client performs the interactions with the Azure Key Vault service for getting, setting, updating, - * deleting, and listing secrets and its versions. Asynchronous (SecretAsyncClient) and synchronous (SecretClient) - * clients exist in the SDK allowing for selection of a client based on an application's use case. - * Once you've initialized a secret, you can interact with the primary resource types in Key Vault.

- * - *

What is an Azure Key Vault Secret ?

- *

A secret is the fundamental resource within Azure Key Vault. From a developer's perspective, Key Vault APIs - * accept and return secret values as strings. In addition to the secret data, the following attributes may be - * specified:

- * - *
    - *
  1. enabled: Specifies whether the secret data can be retrieved.
  2. - *
  3. notBefore: Identifies the time after which the secret will be active.
  4. - *
  5. expires: Identifies the expiration time on or after which the secret data should not be retrieved.
  6. - *
  7. created: Indicates when this version of the secret was created.
  8. - *
  9. updated: Indicates when this version of the secret was updated.
  10. - *
- * - *

Getting Started

- * - *

In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link com.azure.security.keyvault.secrets.SecretClient} or {@link com.azure.security.keyvault.secrets.SecretAsyncClient} class, a vault url and a credential object.

- * - *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, - * which is appropriate for most scenarios, including local development and production environments. Additionally, - * we recommend using a - * - * managed identity for authentication in production environments. - * You can find more information on different ways of authenticating and their corresponding credential types in the - * - * Azure Identity documentation".

- * - *

Sample: Construct Synchronous Secret Client

- * - *

The following code sample demonstrates the creation of a {@link com.azure.security.keyvault.secrets.SecretClient}, - * using the {@link com.azure.security.keyvault.secrets.SecretClientBuilder} to configure it.

- * - * - *
- * SecretClient secretClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildClient();
- * 
- * - * - *

Sample: Construct Asynchronous Secret Client

- * - *

The following code sample demonstrates the creation of a - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}, using the - * {@link com.azure.security.keyvault.secrets.SecretClientBuilder} to configure it.

- * - * - *
- * SecretAsyncClient secretAsyncClient = new SecretClientBuilder()
- *     .credential(new DefaultAzureCredentialBuilder().build())
- *     .vaultUrl("<your-key-vault-url>")
- *     .buildAsyncClient();
- * 
- * - * - *
- * - *

Create a Secret

- * The {@link com.azure.security.keyvault.secrets.SecretClient} or - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient} can be used to create a secret in the key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously create and store a secret in the key vault, - * using the {@link com.azure.security.keyvault.secrets.SecretClient#setSecret(java.lang.String, java.lang.String)} API. - *

- * - * - *
- * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
- * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
- * 
- * - * - *

Asynchronous Code Sample:

- *

The following code sample demonstrates how to asynchronously create and store a secret in the key vault, - * using the {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

- * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

- * - *
- * - *

Get a Secret

- * The {@link com.azure.security.keyvault.secrets.SecretClient} or - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient} can be used to retrieve a secret from the - * key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously retrieve a previously stored secret from the - * key vault, using the {@link com.azure.security.keyvault.secrets.SecretClient#getSecret(java.lang.String)} API.

- * - * - *
- * KeyVaultSecret secret = secretClient.getSecret("secretName");
- * System.out.printf("Secret is returned with name %s and value %s%n",
- *     secret.getName(), secret.getValue());
- * 
- * - * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

- * - *
- * - *

Delete a Secret

- * The {@link com.azure.security.keyvault.secrets.SecretClient} or - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient} can be used to delete a secret from the - * key vault. - * - *

Synchronous Code Sample:

- *

The following code sample demonstrates how to synchronously delete a secret from the - * key vault, using the {@link com.azure.security.keyvault.secrets.SecretClient#beginDeleteSecret(java.lang.String)} API. - *

- * - * - *
- * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
- *
- * // Deleted Secret is accessible as soon as polling begins.
- * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
- *
- * // Deletion date only works for a SoftDelete-enabled Key Vault.
- * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
- *     .getDeletedOn().toString());
- * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
- *     .getRecoveryId());
- *
- * // Secret is being deleted on server.
- * deleteSecretPoller.waitForCompletion();
- * 
- * - * - *

Note: For the asynchronous sample, refer to - * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

- * - * @see com.azure.security.keyvault.secrets.SecretClient - * @see com.azure.security.keyvault.secrets.SecretAsyncClient - * @see com.azure.security.keyvault.secrets.SecretClientBuilder - * @see com.azure.security.keyvault.secrets.models.KeyVaultSecret - */ -package com.azure.security.keyvault.secrets; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java deleted file mode 100644 index 2280fd863c41f..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -module com.azure.security.keyvault.secrets { - requires transitive com.azure.core; - requires com.azure.json; - - exports com.azure.security.keyvault.secrets; - exports com.azure.security.keyvault.secrets.models; - - opens com.azure.security.keyvault.secrets to com.azure.core; - opens com.azure.security.keyvault.secrets.implementation to com.azure.core; - opens com.azure.security.keyvault.secrets.implementation.models to com.azure.core; - opens com.azure.security.keyvault.secrets.models to com.azure.core; -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/proxy-config.json b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/proxy-config.json deleted file mode 100644 index 417708f4ba956..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/proxy-config.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - ["com.azure.security.keyvault.secrets.implementation.SecretClientImpl$SecretClientService"] -] diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/reflect-config.json b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/reflect-config.json deleted file mode 100644 index f9134d5ad3c1f..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/reflect-config.json +++ /dev/null @@ -1,104 +0,0 @@ -[ - { - "name": "com.azure.security.keyvault.secrets.SecretAsyncClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.SecretClient", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.SecretClientBuilder", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.SecretServiceVersion", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.DeletedSecretPage", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.KeyVaultErrorCodeStrings", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretBackup", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretClientImpl", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretPropertiesPage", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretRequestAttributes", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.implementation.SecretRestoreRequestParameters", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.models.DeletedSecret", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.models.KeyVaultSecret", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.models.KeyVaultSecretIdentifier", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - }, - { - "name": "com.azure.security.keyvault.secrets.models.SecretProperties", - "allDeclaredConstructors": true, - "allDeclaredFields": true, - "allDeclaredMethods": true - } -] \ No newline at end of file diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json deleted file mode 100644 index e190caaf40a9e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "resources": { - "includes": [ - { - "pattern": "azure-key-vault-secrets.properties" - }, - { - "pattern": "kvErrorStrings.properties" - } - ] - }, - "bundles": [] -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties deleted file mode 100644 index ca812989b4f27..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties +++ /dev/null @@ -1,2 +0,0 @@ -name=${project.artifactId} -version=${project.version} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md deleted file mode 100644 index c6add772b022b..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -page_type: sample -languages: - - java -products: - - azure - - azure-key-vault -urlFragment: keyvault-secrets-samples ---- - -# Azure Key Vault Secret Samples client library for Java -This document explains samples and how to use them. - -## Key concepts -Key concepts are explained in detail [here][SDK_README_KEY_CONCEPTS]. - -## Getting started -Getting started explained in detail [here][SDK_README_GETTING_STARTED]. - -## Examples - Following section document various examples. - -### Hello World Samples -* [HelloWorld.java][sample_helloWorld] - and [HelloWorldAsync.java][sample_helloWorldAsync] - Contains samples for following scenarios: - * Create a Secret - * Retrieve a Secret - * Update a Secret - * Delete a Secret - -### List Operations Samples -* [ListOperations.java][sample_list] and [ListOperationsAsync.java][sample_listAsync] - Contains samples for following scenarios: - * Create a Secret - * List Secrets - * Create new version of existing secret. - * List versions of an existing secret. - -### Backup And Restore Operations Samples -* [BackupAndRestoreOperations.java][sample_BackupRestore] and [BackupAndRestoreOperationsAsync.java][sample_BackupRestoreAsync] - Contains samples for following scenarios: - * Create a Secret - * Backup a Secret -- Write it to a file. - * Delete a secret - * Restore a secret - -### Managing Deleted Secrets Samples: -* [ManagingDeletedSecrets.java][sample_ManageDeleted] and [ManagingDeletedSecretsAsync.java][sample_ManageDeletedAsync] - Contains samples for following scenarios: - * Create a Secret - * Delete a secret - * List deleted secrets - * Recover a deleted secret - * Purge Deleted secret - -## Troubleshooting -### General -Key Vault clients raise exceptions. For example, if you try to retrieve a secret after it is deleted a `404` error is returned, indicating resource not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error. -```java -try { - SecretClient.getSecret("deletedSecret") -} catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); -} -``` - -## Next steps -Start using KeyVault Java SDK in your solutions. Our SDK details could be found at [SDK README][SECRETS_SDK_README]. - -### Additional Documentation -For more extensive documentation on Azure Key Vault, see the [API reference documentation][azkeyvault_rest]. - -## Contributing -This project welcomes contributions and suggestions. Find [more contributing][SDK_README_CONTRIBUTING] details here. - - -[SECRETS_SDK_README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md -[SDK_README_GETTING_STARTED]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md#getting-started -[SDK_README_KEY_CONCEPTS]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md#key-concepts -[SDK_README_CONTRIBUTING]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md#contributing -[azkeyvault_rest]: https://learn.microsoft.com/rest/api/keyvault/ -[sample_helloWorld]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java -[sample_helloWorldAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java -[sample_list]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java -[sample_listAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java -[sample_BackupRestore]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java -[sample_BackupRestoreAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java -[sample_ManageDeleted]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java -[sample_ManageDeletedAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-secrets%2Fsrc%2Fsamples%2FREADME.png) diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java deleted file mode 100644 index 27938c5ccef53..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to backup and restore secrets in the key vault. - */ -public class BackupAndRestoreOperations { - /** - * Authenticates with the key vault and shows how to backup and restore secrets in the key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - * @throws IOException when writing backup to file is unsuccessful. - */ - public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { - /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretClient client = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in - // the key vault, then a new version of the secret is created. - client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - // Backups are good to have, if in case secrets get accidentally deleted by you. - // For long term storage, it is ideal to write the backup to a file. - String backupFilePath = "YOUR_BACKUP_FILE_PATH"; - byte[] secretBackup = client.backupSecret("StorageAccountPassword"); - - writeBackupToFile(secretBackup, backupFilePath); - - // The storage account secret is no longer in use, so you delete it. - SyncPoller deletedStorageSecretPoller = - client.beginDeleteSecret("StorageAccountPassword"); - PollResponse pollResponse = deletedStorageSecretPoller.poll(); - DeletedSecret deletedStorageSecret = pollResponse.getValue(); - - System.out.println("Deleted Date %s" + deletedStorageSecret.getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecret.getRecoveryId()); - - // Secret is being deleted on server. - deletedStorageSecretPoller.waitForCompletion(); - - //To ensure the secret is deleted server-side. - Thread.sleep(30000); - - // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. - client.purgeDeletedSecret("StorageAccountPassword"); - - // To ensure the secret is purged server-side. - Thread.sleep(15000); - - // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. - byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); - KeyVaultSecret restoredSecret = client.restoreSecretBackup(backupFromFile); - } - - private static void writeBackupToFile(byte[] bytes, String filePath) { - try { - File file = new File(filePath); - - if (file.exists()) { - file.delete(); - } - - file.createNewFile(); - - OutputStream os = new FileOutputStream(file); - os.write(bytes); - - System.out.println("Successfully wrote backup to file."); - - // Close the file - os.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java deleted file mode 100644 index 8d2f52cc53d61..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously backup and restore secrets in the key vault. - */ -public class BackupAndRestoreOperationsAsync { - /** - * Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - * @throws IOException when writing backup to file is unsuccessful. - */ - public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { - /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in - // the key vault, then a new version of the secret is created. - secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - // Backups are good to have, if in case secrets get accidentally deleted by you. - // For long term storage, it is ideal to write the backup to a file. - String backupFilePath = "YOUR_BACKUP_FILE_PATH"; - - secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> { - byte[] backupBytes = backupResponse; - - writeBackupToFile(backupBytes, backupFilePath); - }); - - Thread.sleep(7000); - - // The storage account secret is no longer in use, so you delete it. - secretAsyncClient.beginDeleteSecret("StorageAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - - //To ensure the file is deleted server-side. - Thread.sleep(30000); - - // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. - secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") - .subscribe(purgeResponse -> - System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); - - // To ensure the secret is purged server-side. - Thread.sleep(15000); - - // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. - byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); - secretAsyncClient.restoreSecretBackup(backupFromFile).subscribe(secretResponse -> - System.out.printf("Restored Secret with name %s %n", secretResponse.getName())); - - // To ensure the secret is restored server-side. - Thread.sleep(15000); - } - - private static void writeBackupToFile(byte[] bytes, String filePath) { - try { - File file = new File(filePath); - - if (file.exists()) { - file.delete(); - } - - file.createNewFile(); - - OutputStream os = new FileOutputStream(file); - os.write(bytes); - - System.out.println("Successfully wrote backup to file."); - - // Close the file - os.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java deleted file mode 100644 index 78c772ab5859a..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to set, get, update and delete a secret. - */ -public class HelloWorld { - /** - * Authenticates with the key vault and shows how to set, get, update and delete a secret in the key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException, IllegalArgumentException { - /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the - // key vault, then a new version of the secret is created. - secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - // Let's get the bank secret from the key vault. - KeyVaultSecret bankSecret = secretClient.getSecret("BankAccountPassword"); - - System.out.printf("Secret is returned with name %s and value %s \n", bankSecret.getName(), bankSecret.getValue()); - - // After one year, the bank account is still active, we need to update the expiry time of the secret. - // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the - // value of the secret. - bankSecret.getProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - SecretProperties updatedSecret = secretClient.updateSecretProperties(bankSecret.getProperties()); - - System.out.printf("Secret's updated expiry time %s \n", updatedSecret.getExpiresOn()); - - // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. - // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot - // change the value of the secret. - secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "bhjd4DDgsa") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - // The bank account was closed, need to delete its credentials from the key vault. - SyncPoller deletedBankSecretPoller = - secretClient.beginDeleteSecret("BankAccountPassword"); - PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); - - System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); - - // Secret is being deleted on the server. - deletedBankSecretPoller.waitForCompletion(); - - // If the key vault is soft-delete enabled, then deleted secrets need to be purged for permanent deletion. - secretClient.purgeDeletedSecret("BankAccountPassword"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java deleted file mode 100644 index 91a114dd82013..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously set, get, update and delete a secret. - */ -public class HelloWorldAsync { - /** - * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the - // key vault, then a new version of the secret is created. - secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue())); - - Thread.sleep(2000); - - // Let's get the bank secret from the key vault. - secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> - System.out.printf("Secret returned with name %s , value %s %n", secretResponse.getName(), secretResponse.getValue())); - - Thread.sleep(2000); - - // After one year, the bank account is still active, we need to update the expiry time of the secret. - // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the - // value of the secret. - secretAsyncClient.getSecret("BankAccountPassword") - .subscribe(secretResponse -> { - KeyVaultSecret secret = secretResponse; - - //Update the expiry time of the secret. - secret.getProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)); - secretAsyncClient.updateSecretProperties(secret.getProperties()) - .subscribe(updatedSecretResponse -> - System.out.printf("Secret's updated expiry time %s %n", - updatedSecretResponse.getExpiresOn().toString())); - }); - - Thread.sleep(2000); - - // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. - // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot - // change the value of the secret. - secretAsyncClient.setSecret("BankAccountPassword", "fakePasswordPlaceholder") - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - // The bank account was closed, need to delete its credentials from the key vault. - secretAsyncClient.beginDeleteSecret("BankAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - - // To ensure the secret is deleted server-side. - Thread.sleep(30000); - - // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. - secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") - .subscribe(purgeResponse -> - System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); - - // To ensure the secret is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java deleted file mode 100644 index 832dc68f830d9..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to list secrets and versions of a given secret in the key vault. - */ -public class ListOperations { - /** - * Authenticates with the key vault and shows how to list secrets and list versions of a specific secret in the key - * vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - */ - public static void main(String[] args) throws IllegalArgumentException { - /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretClient client = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret - // already exists in the key vault, then a new version of the secret is created. - client.setSecret(new KeyVaultSecret("StorageAccountPassword", "fakePasswordPlaceholder") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - client.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their values. - // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to get the secret with its value information. - for (SecretProperties secret : client.listPropertiesOfSecrets()) { - if (!secret.isEnabled()) { - continue; - } - KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Received secret with name %s and value %s \n", secretWithValue.getName(), secretWithValue.getValue()); - } - - // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects the new password. - // Calling setSecret on an existing secret creates a new version of the secret in the key vault with the new value. - client.setSecret("BankAccountPassword", "fakePasswordPlaceholder"); - - // You need to check all the different values your bank account password secret had previously. Lets print all the versions of this secret. - for (SecretProperties secret : client.listPropertiesOfSecretVersions("BankAccountPassword")) { - KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); - - System.out.printf("Received secret's version with name %s and value %s", secretWithValue.getName(), - secretWithValue.getValue()); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java deleted file mode 100644 index 258dbe78f0a66..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously list secrets and versions of a given secret in the key vault. - */ -public class ListOperationsAsync { - /** - * Authenticates with the key vault and shows how to asynchronously list secrets and list versions of a specific - * secret in the key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already - // exists in the key vault, then a new version of the secret is created. - secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue())); - - Thread.sleep(2000); - - // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their - // values. List operations don't return the secrets with value information. So, for each returned secret we - // call getSecret() to get the secret with its value information. - secretAsyncClient.listPropertiesOfSecrets() - .subscribe(secret -> - secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) - .subscribe(secretResponse -> - System.out.printf("Received secret with name %s and value %s \n", secretResponse.getName(), - secretResponse.getValue()))); - - Thread.sleep(15000); - - // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects - // the new password. Calling setSecret on an existing secret creates a new version of the secret in the key - // vault with the new value. - secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "sskdjfsdasdjsd") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - // You need to check all the different values your bank account password secret had previously. Lets print all - // the versions of this secret. - secretAsyncClient.listPropertiesOfSecretVersions("BankAccountPassword") - .subscribe(secret -> - secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) - .subscribe(secretResponse -> - System.out.printf("Received secret's version with name %s and value %s \n", - secretResponse.getName(), secretResponse.getValue()))); - - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java deleted file mode 100644 index 260af3222ad8b..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to list, recover and purge deleted secrets in a soft-delete enabled key vault. - */ -public class ManagingDeletedSecrets { - /** - * Authenticates with the key vault and shows how to list, recover and purge deleted secrets in a soft-delete - * enabled key vault. - * - * @param args Unused. Arguments to the program. - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws IllegalArgumentException, InterruptedException { - /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted - secrets to be retained for a given retention period (90 days). During this period deleted secrets can be - recovered and if a secret needs to be permanently deleted then it needs to be purged. */ - - /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default - Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretClient client = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - - // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already - // exists in the key vault, then a new version of the secret is created. - client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - client.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))); - - // The storage account was closed, need to delete its credentials from the key vault. - SyncPoller deletedBankSecretPoller = client.beginDeleteSecret("BankAccountPassword"); - - PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); - - System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); - - // The secret is being deleted on the server. - deletedBankSecretPoller.waitForCompletion(); - - // We accidentally deleted bank account secret. Let's recover it. - // A deleted secret can only be recovered if the key vault is soft-delete enabled. - SyncPoller recoverSecretPoller = - client.beginRecoverDeletedSecret("BankAccountPassword"); - - PollResponse recoverSecretResponse = recoverSecretPoller.poll(); - - System.out.println("Recovered Key Name %s" + recoverSecretResponse.getValue().getName()); - System.out.printf("Recovered Key's Id %s", recoverSecretResponse.getValue().getId()); - - // The secret is being recovered on the server. - recoverSecretPoller.waitForCompletion(); - - // The bank account and storage accounts got closed. - // Let's delete bank and storage accounts secrets. - SyncPoller deletedBankPwdSecretPoller = - client.beginDeleteSecret("BankAccountPassword"); - PollResponse deletedBankPwdSecretPollResponse = deletedBankPwdSecretPoller.poll(); - - System.out.println("Deleted Date %s" + deletedBankPwdSecretPollResponse.getValue().getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", - deletedBankPwdSecretPollResponse.getValue().getRecoveryId()); - - // The secret is being deleted on the server. - deletedBankPwdSecretPoller.waitForCompletion(); - - SyncPoller deletedStorageSecretPoller = - client.beginDeleteSecret("StorageAccountPassword"); - PollResponse deletedStorageSecretPollResponse = deletedStorageSecretPoller.poll(); - - System.out.println("Deleted Date %s" + deletedStorageSecretPollResponse.getValue().getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecretPollResponse.getValue().getRecoveryId()); - - // The secret is being deleted on the server. - deletedStorageSecretPoller.waitForCompletion(); - - // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. - for (DeletedSecret delSecret : client.listDeletedSecrets()) { - System.out.printf("Deleted secret's recovery Id %s", delSecret.getRecoveryId()); - } - - // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. - client.purgeDeletedSecret("StorageAccountPassword"); - client.purgeDeletedSecret("BankAccountPassword"); - - // To ensure the secret is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java deleted file mode 100644 index be097d9bacb69..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * Sample demonstrates how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault. - */ -public class ManagingDeletedSecretsAsync { - /** - * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a - * soft-delete enabled key vault. - * - * @param args Unused. Arguments to the program. - * - * @throws IllegalArgumentException when invalid key vault endpoint is passed. - * @throws InterruptedException when the thread is interrupted in sleep mode. - */ - public static void main(String[] args) throws InterruptedException { - /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted - secrets to be retained for a given retention period (90 days). During this period deleted secrets can be - recovered and if a secret needs to be permanently deleted then it needs to be purged. */ - - /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using - default Azure credentials. For more information on this and other types of credentials, see this document: - https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. - - To get started, you'll need a URL to an Azure Key Vault. See the README - (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) - for links and instructions. */ - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret - // already exists in the key vault, then a new version of the secret is created. - secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .setProperties(new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusYears(1)))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), - secretResponse.getValue())); - - Thread.sleep(2000); - - // The storage account was closed, need to delete its credentials from the key vault. - secretAsyncClient.beginDeleteSecret("BankAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - - // To ensure the secret is deleted server-side. - Thread.sleep(30000); - - // We accidentally deleted bank account secret. Let's recover it. - // A deleted secret can only be recovered if the key vault is soft-delete enabled. - secretAsyncClient.beginRecoverDeletedSecret("BankAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); - System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); - }); - - // To ensure the secret is recovered server-side. - Thread.sleep(10000); - - // The bank account and storage accounts got closed. - // Let's delete bank and storage accounts secrets. - secretAsyncClient.beginDeleteSecret("BankAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - - secretAsyncClient.beginDeleteSecret("StorageAccountPassword") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - - // To ensure the secret is deleted server-side. - Thread.sleep(30000); - - // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. - secretAsyncClient.listDeletedSecrets() - .subscribe(deletedSecret -> - System.out.printf("Deleted secret's recovery Id %s %n", deletedSecret.getRecoveryId())); - - Thread.sleep(15000); - - // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. - secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") - .subscribe(purgeResponse -> - System.out.printf("Storage account secret purge status response %d %n", purgeResponse.getStatusCode())); - - secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") - .subscribe(purgeResponse -> - System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); - - // To ensure the secret is purged server-side. - Thread.sleep(15000); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/PersistentTokenCacheDemo.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/PersistentTokenCacheDemo.java deleted file mode 100644 index d74bbc6464e82..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/PersistentTokenCacheDemo.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.identity.SharedTokenCacheCredential; -import com.azure.identity.SharedTokenCacheCredentialBuilder; - -/** - * Sample showing how to authenticate to Key Vault with a shared token cache credential. - */ -public class PersistentTokenCacheDemo { - /** - * Authenticates from shared token cache and gets a secret. - * - * @param args Unused. Arguments to the program. - */ - public static void main(String[] args) { - // Wrote to AZURE_USERNAME env variable. - SharedTokenCacheCredential defaultCredential = new SharedTokenCacheCredentialBuilder() - .clientId("") - .build(); - - SecretClient client = new SecretClientBuilder() - .vaultUrl("") - .credential(defaultCredential) - .buildClient(); - - // Try to get a secret! Only works if you are logged in. - System.out.println("\nWhat is the super secret secret?\n\n"); - - KeyVaultSecret secret = client.getSecret("the-secret"); - - System.out.println("Secret was found: " + secret.getValue()); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java deleted file mode 100644 index 0926105b75545..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ReadmeSamples.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -@SuppressWarnings("unused") -public class ReadmeSamples { - private final SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - private final SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildAsyncClient(); - - public void createSecretClient() { - // BEGIN: readme-sample-createSecretClient - SecretClient secretClient = new SecretClientBuilder() - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: readme-sample-createSecretClient - } - - public void createSecret() { - // BEGIN: readme-sample-createSecret - KeyVaultSecret secret = secretClient.setSecret("", ""); - System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); - // END: readme-sample-createSecret - } - - public void retrieveSecret() { - // BEGIN: readme-sample-retrieveSecret - KeyVaultSecret secret = secretClient.getSecret(""); - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); - // END: readme-sample-retrieveSecret - } - - public void updateSecret() { - // BEGIN: readme-sample-updateSecret - // Get the secret to update. - KeyVaultSecret secret = secretClient.getSecret(""); - // Update the expiry time of the secret. - secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); - SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secret.getProperties()); - System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn()); - // END: readme-sample-updateSecret - } - - public void deleteSecret() { - // BEGIN: readme-sample-deleteSecret - SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); - - // Deleted secret is accessible as soon as polling begins. - PollResponse deletedSecretPollResponse = deletedSecretPoller.poll(); - - // Deletion date only works for a SoftDelete-enabled Key Vault. - System.out.printf("Deletion date: %s%n", deletedSecretPollResponse.getValue().getDeletedOn()); - - // Secret is being deleted on server. - deletedSecretPoller.waitForCompletion(); - // END: readme-sample-deleteSecret - } - - public void listSecrets() { - // BEGIN: readme-sample-listSecrets - // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to - // get the secret with its value information. - for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretWithValue.getName(), - secretWithValue.getValue()); - } - // END: readme-sample-listSecrets - } - - public void createSecretAsync() { - // BEGIN: readme-sample-createSecretAsync - secretAsyncClient.setSecret("", "") - .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", - secret.getName(), secret.getValue())); - // END: readme-sample-createSecretAsync - } - - public void retrieveSecretAsync() { - // BEGIN: readme-sample-retrieveSecretAsync - secretAsyncClient.getSecret("") - .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", - secret.getName(), secret.getValue())); - // END: readme-sample-retrieveSecretAsync - } - - public void updateSecretAsync() { - // BEGIN: readme-sample-updateSecretAsync - secretAsyncClient.getSecret("") - .flatMap(secret -> { - // Update the expiry time of the secret. - secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); - return secretAsyncClient.updateSecretProperties(secret.getProperties()); - }).subscribe(updatedSecretProperties -> - System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); - // END: readme-sample-updateSecretAsync - } - - public void deleteSecretAsync() { - // BEGIN: readme-sample-deleteSecretAsync - secretAsyncClient.beginDeleteSecret("") - .subscribe(pollResponse -> { - System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); - System.out.printf("Deleted secret name: %s%n", pollResponse.getValue().getName()); - System.out.printf("Deleted secret value: %s%n", pollResponse.getValue().getValue()); - }); - // END: readme-sample-deleteSecretAsync - } - - public void listSecretsAsync() { - // BEGIN: readme-sample-listSecretsAsync - // The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` - // to get its value as well. - secretAsyncClient.listPropertiesOfSecrets() - .flatMap(secretProperties -> - secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) - .subscribe(secretResponse -> - System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), - secretResponse.getValue())); - // END: readme-sample-listSecretsAsync - } - - public void troubleshooting() { - // BEGIN: readme-sample-troubleshooting - try { - secretClient.getSecret(""); - } catch (ResourceNotFoundException e) { - System.out.println(e.getMessage()); - } - // END: readme-sample-troubleshooting - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretAsyncClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretAsyncClientJavaDocCodeSnippets.java deleted file mode 100644 index 8cbe0001e494b..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretAsyncClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; -import reactor.util.context.Context; - -import java.time.OffsetDateTime; - -/** - * This class contains code samples for generating javadocs through doclets for {@link SecretAsyncClient}. - */ -public final class SecretAsyncClientJavaDocCodeSnippets { - private final String key1 = "key1"; - private final String key2 = "key2"; - private final String value1 = "val1"; - private final String value2 = "val2"; - - /** - * Generates code sample for creating a {@link SecretAsyncClient}. - * - * @return An instance of {@link SecretAsyncClient}. - */ - public SecretAsyncClient createAsyncClientWithHttpclient() { - // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .vaultUrl("") - .credential(new DefaultAzureCredentialBuilder().build()) - .httpClient(HttpClient.createDefault()) - .buildAsyncClient(); - // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient - return secretAsyncClient; - } - - /** - * Generates code sample for creating a {@link SecretAsyncClient}. - * - * @return An instance of {@link SecretAsyncClient}. - */ - private SecretAsyncClient getAsyncSecretClient() { - // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation - SecretAsyncClient secretAsyncClient = new SecretClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .vaultUrl("") - .buildAsyncClient(); - // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation - return secretAsyncClient; - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#getSecret(String, String)}. - */ - public void getSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string-string - String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; - secretAsyncClient.getSecret("secretName", secretVersion) - // Passing a Context is optional and useful if you want a set of data to flow through the request. - // Otherwise, the line below can be removed. - .contextWrite(Context.of(key1, value1, key2, value2)) - .subscribe(secretWithVersion -> - System.out.printf("Secret is returned with name %s and value %s %n", - secretWithVersion.getName(), secretWithVersion.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.getSecret#string-string - - // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string - secretAsyncClient.getSecret("secretName") - .subscribe(secretWithVersion -> - System.out.printf("Secret is returned with name %s and value %s %n", - secretWithVersion.getName(), secretWithVersion.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.getSecret#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#getSecretWithResponse(String, String)}. - */ - public void getSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - - // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string - String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; - secretAsyncClient.getSecretWithResponse("secretName", secretVersion) - // Passing a Context is optional and useful if you want a set of data to flow through the request. - // Otherwise, the line below can be removed. - .contextWrite(Context.of(key1, value1, key2, value2)) - .subscribe(secretWithVersion -> - System.out.printf("Secret is returned with name %s and value %s %n", - secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue())); - // END: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#setSecret(KeyVaultSecret)}. - */ - public void setSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#secret - SecretProperties properties = new SecretProperties() - .setExpiresOn(OffsetDateTime.now().plusDays(60)); - KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") - .setProperties(properties); - - secretAsyncClient.setSecret(newSecret) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", - secretResponse.getName(), secretResponse.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.setSecret#secret - - // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#string-string - secretAsyncClient.setSecret("secretName", "secretValue") - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s%n", - secretResponse.getName(), secretResponse.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.setSecret#string-string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#setSecretWithResponse(KeyVaultSecret)}. - */ - public void setSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret - KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue"). - setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); - secretAsyncClient.setSecretWithResponse(newSecret) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s %n", - secretResponse.getValue().getName(), secretResponse.getValue().getValue())); - // END: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#updateSecretProperties(SecretProperties)}. - */ - public void updateSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties - secretAsyncClient.getSecret("secretName") - .subscribe(secretResponseValue -> { - SecretProperties secretProperties = secretResponseValue.getProperties(); - //Update the not before time of the secret. - secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); - secretAsyncClient.updateSecretProperties(secretProperties) - .subscribe(secretResponse -> - System.out.printf("Secret's updated not before time %s %n", - secretResponse.getNotBefore().toString())); - }); - // END: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties - } - - /** - * Method to insert code snippets for - * {@link SecretAsyncClient#updateSecretPropertiesWithResponse(SecretProperties)}. - */ - public void updateSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties - secretAsyncClient.getSecret("secretName") - .subscribe(secretResponseValue -> { - SecretProperties secretProperties = secretResponseValue.getProperties(); - //Update the not before time of the secret. - secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); - secretAsyncClient.updateSecretPropertiesWithResponse(secretProperties) - .subscribe(secretResponse -> - System.out.printf("Secret's updated not before time %s %n", - secretResponse.getValue().getNotBefore().toString())); - }); - // END: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#beginDeleteSecret(String)}. - */ - public void deleteSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.deleteSecret#String - secretAsyncClient.beginDeleteSecret("secretName") - .subscribe(pollResponse -> { - System.out.println("Delete Status: " + pollResponse.getStatus().toString()); - System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); - }); - // END: com.azure.keyvault.secrets.SecretClient.deleteSecret#String - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecret(String)}. - */ - public void getDeletedSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string - secretAsyncClient.getDeletedSecret("secretName") - .subscribe(deletedSecretResponse -> - System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId())); - // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecretWithResponse(String)}. - */ - public void getDeletedSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string - secretAsyncClient.getDeletedSecretWithResponse("secretName") - .subscribe(deletedSecretResponse -> - System.out.printf("Deleted Secret's Recovery Id %s %n", - deletedSecretResponse.getValue().getRecoveryId())); - // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecret(String)}. - */ - public void purgeDeletedSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string - secretAsyncClient.purgeDeletedSecret("deletedSecretName") - .doOnSuccess(purgeResponse -> - System.out.println("Successfully Purged deleted Secret")) - .subscribe(); - // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecretWithResponse(String)}. - */ - public void purgeDeletedSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string - secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName") - .subscribe(purgeResponse -> - System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); - // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#beginRecoverDeletedSecret(String)}. - */ - public void recoverDeletedSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String - secretAsyncClient.beginRecoverDeletedSecret("deletedSecretName") - .subscribe(pollResponse -> { - System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); - System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); - System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); - }); - // END: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#backupSecret(String)}. - */ - public void backupSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecret#string - secretAsyncClient.backupSecret("secretName") - .subscribe(secretBackupResponse -> - System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.length)); - // END: com.azure.keyvault.secrets.SecretClient.backupSecret#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#backupSecretWithResponse(String)}. - */ - public void backupSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string - secretAsyncClient.backupSecretWithResponse("secretName") - .subscribe(secretBackupResponse -> - System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.getValue().length)); - // END: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackup(byte[])}. - */ - public void restoreSecretCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte - // Pass the secret backup byte array to the restore operation. - byte[] secretBackupByteArray = {}; - secretAsyncClient.restoreSecretBackup(secretBackupByteArray) - .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", - secretResponse.getName(), secretResponse.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackupWithResponse(byte[])}. - */ - public void restoreSecretWithResponseCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte - // Pass the secret backup byte array to the restore operation. - byte[] secretBackupByteArray = {}; - secretAsyncClient.restoreSecretBackupWithResponse(secretBackupByteArray) - .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", - secretResponse.getValue().getName(), secretResponse.getValue().getValue())); - // END: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecrets()}. - */ - public void listSecretsCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecrets - secretAsyncClient.listPropertiesOfSecrets() - .flatMap(secretProperties -> { - String name = secretProperties.getName(); - String version = secretProperties.getVersion(); - - System.out.printf("Getting secret name: '%s', version: %s%n", name, version); - return secretAsyncClient.getSecret(name, version); - }) - .subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s", - secretResponse.getName(), secretResponse.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.listSecrets - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#listDeletedSecrets()}. - */ - public void listDeletedSecretsCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets - secretAsyncClient.listDeletedSecrets() - .subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n", - deletedSecretResponse.getRecoveryId())); - // END: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets - } - - /** - * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecretVersions(String)}. - */ - public void listSecretVersionsCodeSnippets() { - SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); - // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string - secretAsyncClient.listPropertiesOfSecretVersions("secretName") - .flatMap(secretProperties -> { - System.out.println("Get secret value for version: " + secretProperties.getVersion()); - return secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); - }) - .subscribe(secret -> System.out.printf("Received secret with name %s and type %s%n", - secret.getName(), secret.getValue())); - // END: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java deleted file mode 100644 index 7a0625a9b159e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.polling.PollResponse; -import com.azure.core.util.polling.SyncPoller; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; - -import java.time.OffsetDateTime; - -/** - * This class contains code samples for generating javadocs through doclets for {@link SecretClient}. - */ -public final class SecretClientJavaDocCodeSnippets { - private final String key1 = "key1"; - private final String key2 = "key2"; - private final String value1 = "val1"; - private final String value2 = "val2"; - - /** - * Generates code sample for creating a {@link SecretClient}. - * - * @return An instance of {@link SecretClient}. - */ - private SecretClient getSecretClient() { - // BEGIN: com.azure.security.keyvault.SecretClient.instantiation - SecretClient secretClient = new SecretClientBuilder() - .credential(new DefaultAzureCredentialBuilder().build()) - .vaultUrl("") - .buildClient(); - // END: com.azure.security.keyvault.SecretClient.instantiation - return secretClient; - } - - /** - * Method to insert code snippets for {@link SecretClient#getSecret(String, String)}. - */ - public void getSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#secretProperties - for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Secret is returned with name %s and value %s%n", secretWithValue.getName(), - secretWithValue.getValue()); - } - // END: com.azure.security.keyvault.SecretClient.getSecret#secretProperties - - // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string-string - String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; - KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion); - System.out.printf("Secret is returned with name %s and value %s%n", - secretWithVersion.getName(), secretWithVersion.getValue()); - // END: com.azure.security.keyvault.SecretClient.getSecret#string-string - - // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string - KeyVaultSecret secret = secretClient.getSecret("secretName"); - System.out.printf("Secret is returned with name %s and value %s%n", - secret.getName(), secret.getValue()); - // END: com.azure.security.keyvault.SecretClient.getSecret#string - } - - /** - * Method to insert code snippets for {@link SecretClient#getSecretWithResponse(String, String, Context)}. - */ - public void getSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - - // BEGIN: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context - String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; - KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion, - new Context(key2, value2)).getValue(); - System.out.printf("Secret is returned with name %s and value %s%n", - secretWithVersion.getName(), secretWithVersion.getValue()); - // END: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#setSecret(KeyVaultSecret)}. - */ - public void setSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#secret - KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") - .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); - KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret); - System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(), - returnedSecret.getValue()); - // END: com.azure.security.keyvault.SecretClient.setSecret#secret - - // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#string-string - KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue"); - System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); - // END: com.azure.security.keyvault.SecretClient.setSecret#string-string - } - - /** - * Method to insert code snippets for {@link SecretClient#setSecretWithResponse(KeyVaultSecret, Context)}. - */ - public void setSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context - KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") - .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); - KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue(); - System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); - // END: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#updateSecretProperties(SecretProperties)}. - */ - public void updateSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties - SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); - secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); - SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties); - KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName()); - System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", - updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); - // END: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties - } - - /** - * Method to insert code snippets for - * {@link SecretClient#updateSecretPropertiesWithResponse(SecretProperties, Context)}. - */ - public void updateSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context - SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); - secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); - SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties, - new Context(key2, value2)).getValue(); - KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName()); - System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", - updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); - // END: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. - */ - public void deleteSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.deleteSecret#String - SyncPoller deleteSecretPoller = secretClient.beginDeleteSecret("secretName"); - - // Deleted Secret is accessible as soon as polling begins. - PollResponse deleteSecretPollResponse = deleteSecretPoller.poll(); - - // Deletion date only works for a SoftDelete-enabled Key Vault. - System.out.println("Deleted Date %s" + deleteSecretPollResponse.getValue() - .getDeletedOn().toString()); - System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue() - .getRecoveryId()); - - // Secret is being deleted on server. - deleteSecretPoller.waitForCompletion(); - // END: com.azure.security.keyvault.SecretClient.deleteSecret#String - } - - /** - * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. - */ - public void getDeletedSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecret#string - DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName"); - System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); - // END: com.azure.security.keyvault.SecretClient.getDeletedSecret#string - } - - /** - * Method to insert code snippets for {@link SecretClient#getDeletedSecretWithResponse(String, Context)}. - */ - public void getDeletedSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context - DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName", - new Context(key2, value2)).getValue(); - System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); - // END: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#purgeDeletedSecret(String)}. - */ - public void purgeDeletedSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - - // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string - secretClient.purgeDeletedSecret("secretName"); - // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string - } - - /** - * Method to insert code snippets for {@link SecretClient#purgeDeletedSecretWithResponse(String, Context)}. - */ - public void purgeDeletedSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context - Response purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName", - new Context(key1, value1)); - System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode()); - // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#beginRecoverDeletedSecret(String)}. - */ - public void recoverDeletedSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String - SyncPoller recoverSecretPoller = - secretClient.beginRecoverDeletedSecret("deletedSecretName"); - - // Deleted Secret can be accessed as soon as polling is in progress. - PollResponse recoveredSecretPollResponse = recoverSecretPoller.poll(); - System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName()); - System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId()); - - // Key is being recovered on server. - recoverSecretPoller.waitForCompletion(); - // END: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String - } - - /** - * Method to insert code snippets for {@link SecretClient#backupSecret(String)}. - */ - public void backupSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.backupSecret#string - byte[] secretBackup = secretClient.backupSecret("secretName"); - System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); - // END: com.azure.security.keyvault.SecretClient.backupSecret#string - } - - /** - * Method to insert code snippets for {@link SecretClient#backupSecretWithResponse(String, Context)}. - */ - public void backupSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context - byte[] secretBackup = secretClient.backupSecretWithResponse("secretName", - new Context(key1, value1)).getValue(); - System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); - // END: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#restoreSecretBackup(byte[])}. - */ - public void restoreSecretCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecret#byte - // Pass the secret backup byte array of the secret to be restored. - byte[] secretBackupByteArray = {}; - KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray); - System.out - .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); - // END: com.azure.security.keyvault.SecretClient.restoreSecret#byte - } - - /** - * Method to insert code snippets for {@link SecretClient#restoreSecretBackupWithResponse(byte[], Context)}. - */ - public void restoreSecretWithResponseCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context - // Pass the secret backup byte array of the secret to be restored. - byte[] secretBackupByteArray = {}; - KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray, - new Context(key2, value2)).getValue(); - System.out - .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); - // END: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context - } - - /** - * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecrets()}. - */ - public void listSecretsCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets - for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Received secret with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - } - // END: com.azure.security.keyvault.SecretClient.listSecrets - - // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets#Context - for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Received secret with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - } - // END: com.azure.security.keyvault.SecretClient.listSecrets#Context - - // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage - secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> { - System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), - resp.getRequest().getUrl(), resp.getStatusCode()); - resp.getItems().forEach(value -> { - KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); - System.out.printf("Received secret with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - }); - }); - // END: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage - } - - /** - * Method to insert code snippets for {@link SecretClient#listDeletedSecrets()} - */ - public void listDeletedSecretsCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets - for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) { - System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); - } - // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets - - // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context - for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) { - System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); - } - // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context - - // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage - secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> { - System.out.printf("Got response headers . Url: %s, Status code: %d %n", - resp.getRequest().getUrl(), resp.getStatusCode()); - resp.getItems().forEach(value -> { - System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId()); - }); - }); - // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage - } - - /** - * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecretVersions(String)}. - */ - public void listSecretVersionsCodeSnippets() { - SecretClient secretClient = getSecretClient(); - // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string - for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Received secret's version with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - } - // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string - - // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context - for (SecretProperties secret : secretClient - .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) { - KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); - System.out.printf("Received secret's version with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - } - // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context - - // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage - secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2)) - .iterableByPage().forEach(resp -> { - System.out.printf("Got response headers . Url: %s, Status code: %d %n", - resp.getRequest().getUrl(), resp.getStatusCode()); - resp.getItems().forEach(value -> { - KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); - System.out.printf("Received secret's version with name %s and value %s", - secretWithValue.getName(), secretWithValue.getValue()); - }); - }); - // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java deleted file mode 100644 index bdcba1517425f..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.test.SyncAsyncExtension; -import com.azure.core.test.annotation.SyncAsyncTest; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.Base64Util; -import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; -import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; -import java.util.stream.Stream; - -import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; -import static com.azure.core.util.CoreUtils.isNullOrEmpty; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.SAME_THREAD) -public class KeyVaultCredentialPolicyTest { - private static final String AUTHENTICATE_HEADER - = "Bearer authorization=\"https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd022db57\", " - + "resource=\"https://vault.azure.net\""; - private static final String AUTHENTICATE_HEADER_WITH_CLAIMS - = "Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", " - + "error=\"insufficient_claims\", " - + "claims=\"eyJhY2Nlc3NfdG9rZW4iOnsiYWNycyI6eyJlc3NlbnRpYWwiOnRydWUsInZhbHVlIjoiY3AxIn19fQ==\""; - private static final String DECODED_CLAIMS = "{\"access_token\":{\"acrs\":{\"essential\":true,\"value\":\"cp1\"}}}"; - private static final String BEARER = "Bearer"; - private static final String BODY = "this is a sample body"; - private static final Flux BODY_FLUX = Flux.defer( - () -> Flux.fromStream(Stream.of(BODY.split("")).map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))))); - private static final String FAKE_ENCODED_CREDENTIAL - = Base64Util.encodeToString("user:fakePasswordPlaceholder".getBytes(StandardCharsets.UTF_8)); - private static final List> BASE_ASSERTIONS = Arrays.asList( - tokenRequestContext -> !tokenRequestContext.getScopes().isEmpty(), - tokenRequestContext -> !isNullOrEmpty(tokenRequestContext.getTenantId()), TokenRequestContext::isCaeEnabled); - - private HttpResponse simpleResponse; - private HttpResponse unauthorizedHttpResponseWithWrongStatusCode; - private HttpResponse unauthorizedHttpResponseWithHeader; - private HttpResponse unauthorizedHttpResponseWithoutHeader; - private HttpResponse unauthorizedHttpResponseWithHeaderAndClaims; - private HttpPipelineCallContext callContext; - private HttpPipelineCallContext differentScopeContext; - private HttpPipelineCallContext testContext; - private HttpPipelineCallContext bodyContext; - private HttpPipelineCallContext bodyFluxContext; - private TokenCredential credential; - - private static HttpPipelineCallContext createCallContext(HttpRequest request, Context context) { - AtomicReference callContextReference = new AtomicReference<>(); - - HttpPipeline callContextCreator = new HttpPipelineBuilder().policies((callContext, next) -> { - callContextReference.set(callContext); - - return next.process(); - }).httpClient(ignored -> Mono.empty()).build(); - - callContextCreator.sendSync(request, context); - - return callContextReference.get(); - } - - @BeforeEach - public void setup() { - HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net"); - HttpRequest requestWithDifferentScope = new HttpRequest(HttpMethod.GET, "https://mytest.azurecr.io"); - - Context bodyContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BinaryData.fromString(BODY)) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - Context bodyFluxContextContext = new Context("KeyVaultCredentialPolicyStashedBody", BODY_FLUX) - .addData("KeyVaultCredentialPolicyStashedContentLength", "21"); - - MockHttpResponse simpleResponse - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 200); - - MockHttpResponse unauthorizedResponseWithWrongStatusCode - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 500); - - MockHttpResponse unauthorizedResponseWithoutHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401); - - MockHttpResponse unauthorizedResponseWithHeader - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER)); - - MockHttpResponse unauthorizedResponseWithHeaderAndClaims - = new MockHttpResponse(new HttpRequest(HttpMethod.GET, "https://azure.com"), 401, - new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, AUTHENTICATE_HEADER_WITH_CLAIMS)); - - this.simpleResponse = simpleResponse; - this.unauthorizedHttpResponseWithWrongStatusCode = unauthorizedResponseWithWrongStatusCode; - this.unauthorizedHttpResponseWithHeader = unauthorizedResponseWithHeader; - this.unauthorizedHttpResponseWithoutHeader = unauthorizedResponseWithoutHeader; - this.unauthorizedHttpResponseWithHeaderAndClaims = unauthorizedResponseWithHeaderAndClaims; - this.callContext = createCallContext(request, Context.NONE); - this.differentScopeContext = createCallContext(requestWithDifferentScope, Context.NONE); - this.testContext = createCallContext(request, Context.NONE); - this.bodyContext = createCallContext(request, bodyContextContext); - this.bodyFluxContext = createCallContext(request, bodyFluxContextContext); - // Can't use BasicAuthenticationCredential until the following PR is merged: - // https://github.com/Azure/azure-sdk-for-java/pull/42238 - this.credential = tokenRequestContext -> Mono - .fromCallable(() -> new AccessToken(FAKE_ENCODED_CREDENTIAL, OffsetDateTime.MAX.minusYears(1))); - } - - @AfterEach - public void cleanup() { - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onNon401ErrorResponse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithWrongStatusCode)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void on401UnauthorizedResponseWithHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(unauthorizedHttpResponseWithHeader)) - .build(); - - SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - assertNotNull(this.callContext.getHttpRequest().getHeaders().get(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onChallengeCredentialPolicy() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - String tokenValue = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresent() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(onChallengeAndClearCache(policy, this.callContext, unauthorizedHttpResponseWithHeader) // Challenge cache created - .then(policy.authorizeRequest(this.testContext))) // Challenge cache used - .verifyComplete(); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge cache created - onChallengeAndClearCacheSync(policy, this.callContext, unauthorizedHttpResponseWithHeader); - // Challenge cache used - policy.authorizeRequestSync(this.testContext); - - String tokenValue = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeader).flatMap(authorized -> { - if (authorized) { - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion( - tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), 3); - - return policy.authorizeRequestOnChallenge(this.callContext, // Challenge with claims received - this.unauthorizedHttpResponseWithHeaderAndClaims).map(ignored -> firstToken); - } else { - return Mono.just(""); - } - })).assertNext(firstToken -> { - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaims() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - StepVerifier.create(policy.authorizeRequestOnChallenge(this.callContext, // Challenge cache created - this.unauthorizedHttpResponseWithHeaderAndClaims)).assertNext(result -> { - assertFalse(result); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - }).verifyComplete(); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeCachePresentWithClaimsSync() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - // Challenge cache created - assertTrue(policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeader)); - - String firstToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(firstToken.isEmpty()); - assertTrue(firstToken.startsWith(BEARER)); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // Challenge with claims received - assertTrue( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - - String newToken = this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - assertFalse(newToken.isEmpty()); - assertTrue(newToken.startsWith(BEARER)); - - assertNotEquals(firstToken, newToken); - - KeyVaultCredentialPolicy.clearCache(); - } - - @Test - public void onAuthorizeRequestChallengeNoCachePresentWithClaimsSync() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // Challenge with claims received - assertFalse( - policy.authorizeRequestOnChallengeSync(this.callContext, this.unauthorizedHttpResponseWithHeaderAndClaims)); - assertNull(this.testContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - - KeyVaultCredentialPolicy.clearCache(); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoCache() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - // No challenge cache to use - SyncAsyncExtension.execute(() -> policy.authorizeRequestSync(this.callContext), - () -> policy.authorizeRequest(this.callContext)); - - assertNull(this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); - } - - @SyncAsyncTest - public void testSetContentLengthHeader() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.bodyContext, this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.bodyFluxContext, this.unauthorizedHttpResponseWithHeader)); - - // Validate that the onChallengeSync ran successfully. - assertTrue(onChallenge); - - HttpHeaders headers = this.bodyFluxContext.getHttpRequest().getHeaders(); - String tokenValue = headers.getValue(AUTHORIZATION); - assertFalse(tokenValue.isEmpty()); - assertTrue(tokenValue.startsWith(BEARER)); - assertEquals("21", headers.getValue(HttpHeaderName.CONTENT_LENGTH)); - - HttpHeaders syncHeaders = this.bodyContext.getHttpRequest().getHeaders(); - String syncTokenValue = headers.getValue(AUTHORIZATION); - assertFalse(syncTokenValue.isEmpty()); - assertTrue(syncTokenValue.startsWith(BEARER)); - assertEquals("21", syncHeaders.getValue(HttpHeaderName.CONTENT_LENGTH)); - } - - @SyncAsyncTest - public void onAuthorizeRequestNoScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader), - () -> onChallengeAndClearCache(policy, this.callContext, this.unauthorizedHttpResponseWithoutHeader)); - - assertFalse(onChallenge); - } - - @Test - public void onAuthorizeRequestDifferentScope() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); - - assertThrows(RuntimeException.class, () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - StepVerifier - .create( - onChallengeAndClearCache(policy, this.differentScopeContext, this.unauthorizedHttpResponseWithHeader)) - .verifyErrorMessage("The challenge resource 'https://vault.azure.net/.default' does not match the " - + "requested domain. If you wish to disable this check for your client, pass 'true' to the " - + "SecretClientBuilder.disableChallengeResourceVerification() method when building it. See " - + "https://aka.ms/azsdk/blog/vault-uri for more information."); - } - - @SyncAsyncTest - public void onAuthorizeRequestDifferentScopeVerifyFalse() { - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, true); - - boolean onChallenge = SyncAsyncExtension.execute( - () -> onChallengeAndClearCacheSync(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader), - () -> onChallengeAndClearCache(policy, this.differentScopeContext, - this.unauthorizedHttpResponseWithHeader)); - - assertTrue(onChallenge); - } - - // Normal flow: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void processMultipleResponses() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request. - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - // On receiving an unauthorized response with claims, the token should be updated and a new attempt to make the - // original request should be made. - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the response with claims and set on the request. - assertNotNull(newToken); - // The token was updated. - assertNotEquals(firstToken, newToken); - // A subsequent request was successful. - assertEquals(simpleResponse, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized with claims - @SyncAsyncTest - public void processConsecutiveResponsesWithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response with claims is received, it shall be returned as is. - unauthorizedHttpResponseWithHeaderAndClaims, }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeaderAndClaims, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 200 OK -> 401 Unauthorized with claims -> 401 Unauthorized - @SyncAsyncTest - public void process401WithoutClaimsAfter401WithClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)) - .addAssertion(tokenRequestContext -> tokenRequestContext.getClaims() == null); - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - simpleResponse, - unauthorizedHttpResponseWithHeaderAndClaims, - // If a second consecutive unauthorized response is received, it shall be returned as is. - unauthorizedHttpResponseWithHeader }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String firstToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first response was unauthorized and a token was set on the request - assertNotNull(firstToken); - // On a second attempt, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - testCredential.replaceAssertion(tokenRequestContext -> DECODED_CLAIMS.equals(tokenRequestContext.getClaims()), - 3); - - HttpResponse newResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // A new token was fetched using the first response with claims and set on the request - assertNotEquals(firstToken, newToken); - // A subsequent request was unsuccessful. - assertEquals(unauthorizedHttpResponseWithHeader, newResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - // Edge case: 401 Unauthorized -> 401 Unauthorized with claims -> 200 OK - @SyncAsyncTest - public void process401WithClaimsAfter401WithoutClaims() { - MutableTestCredential testCredential = new MutableTestCredential(new ArrayList<>(BASE_ASSERTIONS)); - final String[] firstToken = new String[1]; - - testCredential.addAssertion(tokenRequestContext -> { - // This will ensure that that the first request does not contains claims, but the second does after - // receiving a 401 response with a challenge with claims. - testCredential.replaceAssertion( - anotherTokenRequestContext -> DECODED_CLAIMS.equals(anotherTokenRequestContext.getClaims()), 3); - - // We will also store the value of the first credential before it changes on a second call - firstToken[0] = Base64Util.encodeToString(testCredential.getCredential().getBytes(StandardCharsets.UTF_8)); - - assertNotNull(firstToken[0]); - - return tokenRequestContext.getClaims() == null; - }); - - HttpResponse[] responses = new HttpResponse[] { - unauthorizedHttpResponseWithHeader, - unauthorizedHttpResponseWithHeaderAndClaims, - simpleResponse }; - AtomicInteger currentResponse = new AtomicInteger(); - KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(testCredential, false); - - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policy) - .httpClient(ignored -> Mono.just(responses[currentResponse.getAndIncrement()])) - .build(); - - // The first request to a Key Vault endpoint without an access token will always return a 401 Unauthorized - // response with a WWW-Authenticate header containing an authentication challenge. - - HttpResponse firstResponse = SyncAsyncExtension.execute( - () -> pipeline.sendSync(this.callContext.getHttpRequest(), this.callContext.getContext()), - () -> pipeline.send(this.callContext.getHttpRequest(), this.callContext.getContext())); - - String newToken = this.callContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION); - - // The first unauthorized response caused a token to be set on the request, then the token was updated on a - // subsequent unauthorized response with claims. - assertNotEquals(firstToken[0], newToken); - // Finally, a successful response was received. - assertEquals(simpleResponse, firstResponse); - - KeyVaultCredentialPolicy.clearCache(); - } - - private Mono onChallengeAndClearCache(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - Mono onChallenge = policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallenge; - } - - private boolean onChallengeAndClearCacheSync(KeyVaultCredentialPolicy policy, HttpPipelineCallContext callContext, - HttpResponse unauthorizedHttpResponse) { - boolean onChallengeSync = policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponse); - - KeyVaultCredentialPolicy.clearCache(); - - return onChallengeSync; - } - - private static final class MutableTestCredential implements TokenCredential { - private String credential; - private List> assertions; - - private MutableTestCredential(List> assertions) { - this.credential = new Random().toString(); - this.assertions = assertions; - } - - /** - * @throws RuntimeException if any of the assertions fail. - */ - @Override - public Mono getToken(TokenRequestContext requestContext) { - if (requestContext.isCaeEnabled() && requestContext.getClaims() != null) { - credential = new Random().toString(); - } - - String encodedCredential = Base64Util.encodeToString(credential.getBytes(StandardCharsets.UTF_8)); - - for (int i = 0; i < assertions.size(); i++) { - if (!assertions.get(i).apply(requestContext)) { - return Mono.error(new RuntimeException(String.format("Assertion number %d failed", i))); - } - } - - return Mono.fromCallable(() -> new AccessToken(encodedCredential, OffsetDateTime.MAX.minusYears(1))); - } - - private MutableTestCredential setAssertions(List> assertions) { - this.assertions = assertions; - - return this; - } - - private MutableTestCredential addAssertion(Function assertion) { - assertions.add(assertion); - - return this; - } - - private MutableTestCredential replaceAssertion(Function assertion, int index) { - assertions.set(index, assertion); - - return this; - } - - private String getCredential() { - return this.credential; - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java deleted file mode 100644 index 24d7e65649aeb..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.util.CoreUtils; -import org.junit.jupiter.api.Test; - -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class KeyVaultSecretsUserAgentPropertiesTest { - - @Test - public void testAzureConfiguration() { - Map properties = CoreUtils.getProperties("azure-key-vault-secrets.properties"); - assertTrue(properties.get("name").matches("azure-security-keyvault-secrets")); - assertTrue(properties.get("version").matches("(\\d)+.(\\d)+.(\\d)+([-a-zA-Z0-9.])*")); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java deleted file mode 100644 index 3b73717bf38e7..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java +++ /dev/null @@ -1,574 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.core.util.polling.PollerFlux; -import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SecretAsyncClientTest extends SecretClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(SecretAsyncClientTest.class); - - private SecretAsyncClient secretAsyncClient; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - private void createSecretAsyncClient(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion, null); - } - - private void createSecretAsyncClient(HttpClient httpClient, SecretServiceVersion serviceVersion, - String testTenantId) { - secretAsyncClient = getClientBuilder( - buildAsyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - testTenantId, getEndpoint(), serviceVersion).buildAsyncClient(); - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertAsync().build(); - } - - /** - * Tests that a secret can be created in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - setSecretRunner((secretToSet) -> StepVerifier.create(secretAsyncClient.setSecret(secretToSet)) - .assertNext(response -> assertSecretEquals(secretToSet, response)) - .verifyComplete()); - } - - /** - * Tests that a secret can be created in the key vault while using a different tenant ID than the one that will be - * provided in the authentication challenge. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretWithMultipleTenants(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); - - setSecretRunner((secretToSet) -> StepVerifier.create(secretAsyncClient.setSecret(secretToSet)) - .assertNext(response -> assertSecretEquals(secretToSet, response)) - .verifyComplete()); - - KeyVaultCredentialPolicy.clearCache(); // Ensure we don't have anything cached and try again. - - setSecretRunner((secretToSet) -> StepVerifier.create(secretAsyncClient.setSecret(secretToSet)) - .assertNext(response -> assertSecretEquals(secretToSet, response)) - .verifyComplete()); - } - - /** - * Tests that we cannot create a secret when the key is an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.setSecret("", "A value")) - .verifyErrorSatisfies( - e -> assertRestException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD)); - } - - /** - * Tests that we can create secrets when value is not null or an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - setSecretEmptyValueRunner((secretToSet) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToSet.getName(), secretToSet.getValue())) - .assertNext(response -> assertSecretEquals(secretToSet, response)) - .verifyComplete(); - - StepVerifier.create(secretAsyncClient.getSecret(secretToSet.getName())) - .assertNext(response -> assertSecretEquals(secretToSet, response)) - .verifyComplete(); - }); - } - - /** - * Verifies that an exception is thrown when null secret object is passed for creation. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.setSecret(null)).verifyError(NullPointerException.class); - } - - /** - * Tests that a secret can be updated when it exists. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - updateSecretRunner((originalSecret, updatedSecret) -> { - StepVerifier.create(secretAsyncClient.setSecret(originalSecret)) - .assertNext(response -> assertSecretEquals(originalSecret, response)) - .verifyComplete(); - - StepVerifier - .create(secretAsyncClient.getSecret(originalSecret.getName()) - .flatMap(secretToUpdate -> secretAsyncClient.updateSecretProperties( - secretToUpdate.getProperties().setExpiresOn(updatedSecret.getProperties().getExpiresOn())))) - .assertNext(response -> { - assertNotNull(response); - assertEquals(originalSecret.getName(), response.getName()); - }) - .verifyComplete(); - - StepVerifier.create(secretAsyncClient.getSecret(originalSecret.getName())) - .assertNext(response -> assertSecretEquals(updatedSecret, response)) - .verifyComplete(); - }); - } - - /** - * Tests that a secret cannot be updated when it is disabled. 403 error is expected. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - updateDisabledSecretRunner((originalSecret, updatedSecret) -> { - StepVerifier.create(secretAsyncClient.setSecret(originalSecret)) - .assertNext(response -> assertSecretEquals(originalSecret, response)) - .verifyComplete(); - - StepVerifier.create(secretAsyncClient.getSecret(originalSecret.getName())) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_FORBIDDEN)); - }); - } - - /** - * Tests that an existing secret can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - getSecretRunner((secretToGet) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToGet)) - .assertNext(response -> assertSecretEquals(secretToGet, response)) - .verifyComplete(); - - StepVerifier.create(secretAsyncClient.getSecret(secretToGet.getName())) - .assertNext(response -> assertSecretEquals(secretToGet, response)) - .verifyComplete(); - }); - } - - /** - * Tests that a specific version of the secret can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - getSecretSpecificVersionRunner((secretWithOriginalValue, secretWithNewValue) -> { - StepVerifier - .create(secretAsyncClient.setSecret(secretWithOriginalValue) - .flatMap(secretVersionOne -> secretAsyncClient.getSecret(secretWithOriginalValue.getName(), - secretVersionOne.getProperties().getVersion()))) - .assertNext(response -> assertSecretEquals(secretWithOriginalValue, response)) - .verifyComplete(); - - StepVerifier - .create(secretAsyncClient.setSecret(secretWithNewValue) - .flatMap(secretVersionTwo -> secretAsyncClient.getSecret(secretWithNewValue.getName(), - secretVersionTwo.getProperties().getVersion()))) - .assertNext(response -> assertSecretEquals(secretWithNewValue, response)) - .verifyComplete(); - }); - } - - /** - * Tests that an attempt to get a non-existing secret throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.getSecret("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that an existing secret can be deleted. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - deleteSecretRunner((secretToDelete) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToDelete)) - .assertNext(response -> assertSecretEquals(secretToDelete, response)) - .verifyComplete(); - - PollerFlux poller - = setPlaybackPollerFluxPollInterval(secretAsyncClient.beginDeleteSecret(secretToDelete.getName())); - - StepVerifier.create(poller.last().map(AsyncPollResponse::getValue)).assertNext(deletedSecretResponse -> { - assertNotNull(deletedSecretResponse.getDeletedOn()); - assertNotNull(deletedSecretResponse.getRecoveryId()); - assertNotNull(deletedSecretResponse.getScheduledPurgeDate()); - assertEquals(secretToDelete.getName(), deletedSecretResponse.getName()); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to delete a non-existing secret throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.beginDeleteSecret("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a deleted secret can be retrieved on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - getDeletedSecretRunner((secretToDeleteAndGet) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToDeleteAndGet)) - .assertNext(secretResponse -> assertSecretEquals(secretToDeleteAndGet, secretResponse)) - .verifyComplete(); - - PollerFlux poller = setPlaybackPollerFluxPollInterval( - secretAsyncClient.beginDeleteSecret(secretToDeleteAndGet.getName())); - - StepVerifier.create(poller.last().then(secretAsyncClient.getDeletedSecret(secretToDeleteAndGet.getName()))) - .assertNext(deletedSecretResponse -> { - assertNotNull(deletedSecretResponse.getDeletedOn()); - assertNotNull(deletedSecretResponse.getRecoveryId()); - assertNotNull(deletedSecretResponse.getScheduledPurgeDate()); - assertEquals(secretToDeleteAndGet.getName(), deletedSecretResponse.getName()); - }) - .verifyComplete(); - }); - } - - /** - * Tests that an attempt to retrieve a non-existing deleted secret throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.getDeletedSecret("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a deleted secret can be recovered on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - recoverDeletedSecretRunner((secretToDeleteAndRecover) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToDeleteAndRecover)) - .assertNext(secretResponse -> assertSecretEquals(secretToDeleteAndRecover, secretResponse)) - .verifyComplete(); - - PollerFlux poller = setPlaybackPollerFluxPollInterval( - secretAsyncClient.beginDeleteSecret(secretToDeleteAndRecover.getName())); - - StepVerifier.create(poller.last() - .thenMany(setPlaybackPollerFluxPollInterval( - secretAsyncClient.beginRecoverDeletedSecret(secretToDeleteAndRecover.getName()))) - .last() - .map(AsyncPollResponse::getValue)).assertNext(secretResponse -> { - assertEquals(secretToDeleteAndRecover.getName(), secretResponse.getName()); - assertEquals(secretToDeleteAndRecover.getProperties().getNotBefore(), - secretResponse.getProperties().getNotBefore()); - assertEquals(secretToDeleteAndRecover.getProperties().getExpiresOn(), - secretResponse.getProperties().getExpiresOn()); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to recover a non-existing deleted secret throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.beginRecoverDeletedSecret("non-existing")) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a secret can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - backupSecretRunner((secretToBackup) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToBackup)) - .assertNext(secretResponse -> assertSecretEquals(secretToBackup, secretResponse)) - .verifyComplete(); - - StepVerifier.create(secretAsyncClient.backupSecret(secretToBackup.getName())).assertNext(backupBytes -> { - assertNotNull(backupBytes); - assertTrue(backupBytes.length > 0); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to back up a non-existing secret throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - StepVerifier.create(secretAsyncClient.backupSecret("non-existing")) - .verifyErrorSatisfies( - ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); - } - - /** - * Tests that a secret can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - restoreSecretRunner((secretToBackupAndRestore) -> { - StepVerifier.create(secretAsyncClient.setSecret(secretToBackupAndRestore)) - .assertNext(secretResponse -> assertSecretEquals(secretToBackupAndRestore, secretResponse)) - .verifyComplete(); - - byte[] backup = secretAsyncClient.backupSecret(secretToBackupAndRestore.getName()).block(); - - PollerFlux poller = setPlaybackPollerFluxPollInterval( - secretAsyncClient.beginDeleteSecret(secretToBackupAndRestore.getName())); - - StepVerifier - .create(poller.last() - .then(secretAsyncClient.purgeDeletedSecretWithResponse(secretToBackupAndRestore.getName()))) - .assertNext( - voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) - .verifyComplete(); - - pollOnSecretPurge(secretToBackupAndRestore.getName()); - - sleepIfRunningAgainstService(60000); - - StepVerifier.create(secretAsyncClient.restoreSecretBackup(backup)).assertNext(response -> { - assertEquals(secretToBackupAndRestore.getName(), response.getName()); - assertEquals(secretToBackupAndRestore.getProperties().getNotBefore(), - response.getProperties().getNotBefore()); - assertEquals(secretToBackupAndRestore.getProperties().getExpiresOn(), - response.getProperties().getExpiresOn()); - }).verifyComplete(); - }); - } - - /** - * Tests that an attempt to restore a secret from malformed backup bytes throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - byte[] secretBackupBytes = "non-existing".getBytes(); - - StepVerifier.create(secretAsyncClient.restoreSecretBackup(secretBackupBytes)) - .verifyErrorSatisfies( - e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); - } - - /** - * Tests that deleted secrets can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - // Skip when running against the service to avoid having pipeline runs take longer than they have to. - if (interceptorManager.isLiveMode()) { - return; - } - - listDeletedSecretsRunner((secretsToSetAndDelete) -> { - for (KeyVaultSecret secret : secretsToSetAndDelete.values()) { - StepVerifier.create(secretAsyncClient.setSecret(secret)) - .assertNext(secretResponse -> assertSecretEquals(secret, secretResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(10000); - - for (KeyVaultSecret secret : secretsToSetAndDelete.values()) { - PollerFlux poller - = setPlaybackPollerFluxPollInterval(secretAsyncClient.beginDeleteSecret(secret.getName())); - - StepVerifier.create(poller.last()).expectNextCount(1).verifyComplete(); - } - - sleepIfRunningAgainstService(60000); - - StepVerifier.create(secretAsyncClient.listDeletedSecrets().map(deletedSecret -> { - assertNotNull(deletedSecret.getDeletedOn()); - assertNotNull(deletedSecret.getRecoveryId()); - - return deletedSecret; - }).last()).assertNext(Assertions::assertNotNull).verifyComplete(); - }); - } - - /** - * Tests that secret versions can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - listSecretVersionsRunner((secretsToSetAndList) -> { - List output = new ArrayList<>(); - String secretName = null; - - for (KeyVaultSecret secret : secretsToSetAndList) { - secretName = secret.getName(); - - StepVerifier.create(secretAsyncClient.setSecret(secret)) - .assertNext(secretResponse -> assertSecretEquals(secret, secretResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(30000); - - StepVerifier.create(secretAsyncClient.listPropertiesOfSecretVersions(secretName).map(secretProperties -> { - output.add(secretProperties); - return Mono.empty(); - }).last()).assertNext(ignore -> assertEquals(secretsToSetAndList.size(), output.size())).verifyComplete(); - }); - } - - /** - * Tests that secrets can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createSecretAsyncClient(httpClient, serviceVersion); - - listSecretsRunner((secretsToSetAndList) -> { - for (KeyVaultSecret secret : secretsToSetAndList.values()) { - StepVerifier.create(secretAsyncClient.setSecret(secret)) - .assertNext(secretResponse -> assertSecretEquals(secret, secretResponse)) - .verifyComplete(); - } - - sleepIfRunningAgainstService(10000); - - StepVerifier.create(secretAsyncClient.listPropertiesOfSecrets().map(secret -> { - if (secretsToSetAndList.containsKey(secret.getName())) { - KeyVaultSecret expectedSecret = secretsToSetAndList.get(secret.getName()); - - assertEquals(expectedSecret.getProperties().getExpiresOn(), secret.getExpiresOn()); - assertEquals(expectedSecret.getProperties().getNotBefore(), secret.getNotBefore()); - - secretsToSetAndList.remove(secret.getName()); - } - - return secret; - }).last()).assertNext(ignored -> assertEquals(0, secretsToSetAndList.size())).verifyComplete(); - }); - } - - private void pollOnSecretPurge(String secretName) { - int pendingPollCount = 0; - - while (pendingPollCount < 10) { - DeletedSecret deletedSecret = null; - - try { - deletedSecret = secretAsyncClient.getDeletedSecret(secretName).block(); - } catch (ResourceNotFoundException ignored) { - } - - if (deletedSecret != null) { - sleepIfRunningAgainstService(2000); - pendingPollCount += 1; - } else { - return; - } - } - - LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Secret " + secretName + " was not purged"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java deleted file mode 100644 index 142c45abbba3e..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SecretClientBuilderTest { - private String vaultUrl; - private String secretName; - private SecretServiceVersion serviceVersion; - - @BeforeEach - public void setUp() { - vaultUrl = "https://key-vault-url.vault.azure.net/"; - secretName = "TestSecret"; - serviceVersion = SecretServiceVersion.V7_3; - } - - @Test - public void buildSyncClientTest() { - SecretClient secretClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(secretClient); - assertEquals(SecretClient.class.getSimpleName(), secretClient.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - SecretClient secretClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(secretClient); - assertEquals(SecretClient.class.getSimpleName(), secretClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - SecretAsyncClient secretAsyncClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(secretAsyncClient); - assertEquals(SecretAsyncClient.class.getSimpleName(), secretAsyncClient.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - SecretAsyncClient secretAsyncClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(secretAsyncClient); - assertEquals(SecretAsyncClient.class.getSimpleName(), secretAsyncClient.getClass().getSimpleName()); - } - - @Test - public void emptyVaultUrlThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SecretClientBuilder().vaultUrl("")); - } - - @Test - public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new SecretClientBuilder().credential(null)); - } - - @Test - public void clientOptionsIsPreferredOverLogOptions() { - SecretClient secretClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> secretClient.getSecret(secretName)); - } - - @Test - public void applicationIdFallsBackToLogOptions() { - SecretClient secretClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> secretClient.getSecret(secretName)); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - SecretClient secretClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.error(new HttpResponseException(new MockHttpResponse(httpRequest, 400))); - }) - .buildClient(); - - assertThrows(RuntimeException.class, () -> secretClient.getSecret(secretName)); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new SecretClientBuilder().vaultUrl(vaultUrl) - .serviceVersion(serviceVersion) - .credential(new TestUtils.TestCredential()) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } - - // This tests the policy is in the right place because if it were added per retry, it would be after the credentials - // and auth would fail because we changed a signed header. - @Test - public void addPerCallPolicy() { - SecretAsyncClient secretAsyncClient = new SecretClientBuilder().vaultUrl(vaultUrl) - .credential(new TestUtils.TestCredential()) - .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - HttpPipeline pipeline = secretAsyncClient.getHttpPipeline(); - - int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; - - for (int i = 0; i < pipeline.getPolicyCount(); i++) { - if (pipeline.getPolicy(i).getClass() == RetryPolicy.class) { - retryPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerCallPolicy.class) { - perCallPolicyPosition = i; - } - - if (pipeline.getPolicy(i).getClass() == TestUtils.PerRetryPolicy.class) { - perRetryPolicyPosition = i; - } - } - - assertTrue(perCallPolicyPosition != -1); - assertTrue(perCallPolicyPosition < retryPolicyPosition); - assertTrue(retryPolicyPosition < perRetryPolicyPosition); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java deleted file mode 100644 index 68df398db87e3..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTest.java +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpClient; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.logging.LogLevel; -import com.azure.core.util.polling.SyncPoller; -import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.models.DeletedSecret; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; -import io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SecretClientTest extends SecretClientTestBase { - private static final ClientLogger LOGGER = new ClientLogger(SecretClientTest.class); - - private SecretClient secretClient; - - @Override - protected void beforeTest() { - beforeTestSetup(); - } - - private void createClient(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion, null); - } - - private void createClient(HttpClient httpClient, SecretServiceVersion serviceVersion, String testTenantId) { - secretClient = getClientBuilder( - buildSyncAssertingClient( - interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), - testTenantId, getEndpoint(), serviceVersion).buildClient(); - - if (!interceptorManager.isLiveMode()) { - // Remove `id` and `name` sanitizers from the list of common sanitizers. - interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493"); - } - } - - private HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).assertSync().build(); - } - - /** - * Tests that a secret can be created in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - setSecretRunner((secretToSet) -> assertSecretEquals(secretToSet, secretClient.setSecret(secretToSet))); - } - - /** - * Tests that a secret can be created in the key vault while using a different tenant ID than the one that will be - * provided in the authentication challenge. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretWithMultipleTenants(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); - - setSecretRunner((secretToSet) -> assertSecretEquals(secretToSet, secretClient.setSecret(secretToSet))); - - KeyVaultCredentialPolicy.clearCache(); // Ensure we don't have anything cached and try again. - - setSecretRunner((secretToSet) -> assertSecretEquals(secretToSet, secretClient.setSecret(secretToSet))); - } - - /** - * Tests that we cannot create a secret when the secret is an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.setSecret("", "A value"), KeyVaultErrorException.class, - HttpURLConnection.HTTP_BAD_METHOD); - } - - /** - * Tests that we can create secrets when value is not null or an empty string. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - setSecretEmptyValueRunner((secretToSet) -> { - assertSecretEquals(secretToSet, secretClient.setSecret(secretToSet.getName(), secretToSet.getValue())); - assertSecretEquals(secretToSet, secretClient.getSecret(secretToSet.getName())); - }); - } - - /** - * Verifies that an exception is thrown when null secret object is passed for creation. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - assertThrows(NullPointerException.class, () -> secretClient.setSecret(null)); - } - - /** - * Tests that a secret can be updated when it exists. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - updateSecretRunner((originalSecret, updatedSecret) -> { - assertSecretEquals(originalSecret, secretClient.setSecret(originalSecret)); - - KeyVaultSecret secretToUpdate = secretClient.getSecret(originalSecret.getName()); - - secretClient.updateSecretProperties( - secretToUpdate.getProperties().setExpiresOn(updatedSecret.getProperties().getExpiresOn())); - - assertSecretEquals(updatedSecret, secretClient.getSecret(originalSecret.getName())); - }); - } - - /** - * Tests that a secret cannot be updated when it is disabled. 403 error is expected. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - updateDisabledSecretRunner((originalSecret, updatedSecret) -> { - assertSecretEquals(originalSecret, secretClient.setSecret(originalSecret)); - assertRestException(() -> secretClient.getSecret(originalSecret.getName()), ResourceModifiedException.class, - HttpURLConnection.HTTP_FORBIDDEN); - }); - } - - /** - * Tests that an existing secret can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - getSecretRunner((secretToGet) -> { - secretClient.setSecret(secretToGet); - - assertSecretEquals(secretToGet, secretClient.getSecret(secretToGet.getName())); - }); - } - - /** - * Tests that a specific version of the secret can be retrieved. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - getSecretSpecificVersionRunner((secretWithOriginalValue, secretWithNewValue) -> { - KeyVaultSecret secretVersionOne = secretClient.setSecret(secretWithOriginalValue); - KeyVaultSecret secretVersionTwo = secretClient.setSecret(secretWithNewValue); - - assertSecretEquals(secretWithOriginalValue, - secretClient.getSecret(secretVersionOne.getName(), secretVersionOne.getProperties().getVersion())); - assertSecretEquals(secretWithNewValue, - secretClient.getSecret(secretVersionTwo.getName(), secretVersionTwo.getProperties().getVersion())); - }); - } - - /** - * Tests that an attempt to get a non-existing secret throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.getSecret("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that an existing secret can be deleted. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - deleteSecretRunner((secretToDelete) -> { - assertSecretEquals(secretToDelete, secretClient.setSecret(secretToDelete)); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(secretClient.beginDeleteSecret(secretToDelete.getName())); - - DeletedSecret deletedSecret = poller.waitForCompletion().getValue(); - - assertNotNull(deletedSecret.getDeletedOn()); - assertNotNull(deletedSecret.getRecoveryId()); - assertNotNull(deletedSecret.getScheduledPurgeDate()); - assertEquals(secretToDelete.getName(), deletedSecret.getName()); - }); - } - - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.beginDeleteSecret("non-existing"), ResourceNotFoundException.class, - HttpResponseStatus.NOT_FOUND.code()); - } - - /** - * Tests that a deleted secret can be retrieved on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - getDeletedSecretRunner((secretToDeleteAndGet) -> { - assertSecretEquals(secretToDeleteAndGet, secretClient.setSecret(secretToDeleteAndGet)); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(secretClient.beginDeleteSecret(secretToDeleteAndGet.getName())); - - poller.waitForCompletion(); - - DeletedSecret deletedSecret = secretClient.getDeletedSecret(secretToDeleteAndGet.getName()); - - assertNotNull(deletedSecret.getDeletedOn()); - assertNotNull(deletedSecret.getRecoveryId()); - assertNotNull(deletedSecret.getScheduledPurgeDate()); - assertEquals(secretToDeleteAndGet.getName(), deletedSecret.getName()); - }); - } - - /** - * Tests that an attempt to retrieve a non-existing deleted secret throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.getDeletedSecret("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that a deleted secret can be recovered on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - recoverDeletedSecretRunner((secretToDeleteAndRecover) -> { - assertSecretEquals(secretToDeleteAndRecover, secretClient.setSecret(secretToDeleteAndRecover)); - - SyncPoller delPoller - = setPlaybackSyncPollerPollInterval(secretClient.beginDeleteSecret(secretToDeleteAndRecover.getName())); - - delPoller.waitForCompletion(); - - SyncPoller poller = setPlaybackSyncPollerPollInterval( - secretClient.beginRecoverDeletedSecret(secretToDeleteAndRecover.getName())); - - KeyVaultSecret recoveredSecret = poller.waitForCompletion().getValue(); - - assertEquals(secretToDeleteAndRecover.getName(), recoveredSecret.getName()); - assertEquals(secretToDeleteAndRecover.getProperties().getNotBefore(), - recoveredSecret.getProperties().getNotBefore()); - assertEquals(secretToDeleteAndRecover.getProperties().getExpiresOn(), - recoveredSecret.getProperties().getExpiresOn()); - }); - } - - /** - * Tests that an attempt to recover a non-existing deleted secret throws an error on a soft-delete enabled vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.beginRecoverDeletedSecret("non-existing"), - ResourceNotFoundException.class, HttpResponseStatus.NOT_FOUND.code()); - } - - /** - * Tests that a secret can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - backupSecretRunner((secretToBackup) -> { - assertSecretEquals(secretToBackup, secretClient.setSecret(secretToBackup)); - - byte[] backupBytes = (secretClient.backupSecret(secretToBackup.getName())); - - assertNotNull(backupBytes); - assertTrue(backupBytes.length > 0); - }); - } - - /** - * Tests that an attempt to back up a non-existing secret throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - assertRestException(() -> secretClient.backupSecret("non-existing"), ResourceNotFoundException.class, - HttpURLConnection.HTTP_NOT_FOUND); - } - - /** - * Tests that a secret can be backed up in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public synchronized void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - restoreSecretRunner((secretToBackupAndRestore) -> { - assertSecretEquals(secretToBackupAndRestore, secretClient.setSecret(secretToBackupAndRestore)); - - byte[] backupBytes = (secretClient.backupSecret(secretToBackupAndRestore.getName())); - - assertNotNull(backupBytes); - assertTrue(backupBytes.length > 0); - - SyncPoller poller - = setPlaybackSyncPollerPollInterval(secretClient.beginDeleteSecret(secretToBackupAndRestore.getName())); - - poller.waitForCompletion(); - - secretClient.purgeDeletedSecret(secretToBackupAndRestore.getName()); - pollOnSecretPurge(secretToBackupAndRestore.getName()); - - sleepIfRunningAgainstService(60000); - - KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(backupBytes); - - assertEquals(secretToBackupAndRestore.getName(), restoredSecret.getName()); - assertEquals(secretToBackupAndRestore.getProperties().getExpiresOn(), - restoredSecret.getProperties().getExpiresOn()); - }); - } - - /** - * Tests that an attempt to restore a secret from malformed backup bytes throws an error. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - byte[] secretBackupBytes = "non-existing".getBytes(); - - assertRestException(() -> secretClient.restoreSecretBackup(secretBackupBytes), ResourceModifiedException.class, - HttpURLConnection.HTTP_BAD_REQUEST); - } - - /** - * Tests that secrets can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - listSecretsRunner((secretsToSetAndList) -> { - for (KeyVaultSecret secret : secretsToSetAndList.values()) { - assertSecretEquals(secret, secretClient.setSecret(secret)); - } - - for (SecretProperties actualSecret : secretClient.listPropertiesOfSecrets()) { - if (secretsToSetAndList.containsKey(actualSecret.getName())) { - KeyVaultSecret expectedSecret = secretsToSetAndList.get(actualSecret.getName()); - - assertEquals(expectedSecret.getProperties().getExpiresOn(), actualSecret.getExpiresOn()); - assertEquals(expectedSecret.getProperties().getNotBefore(), actualSecret.getNotBefore()); - secretsToSetAndList.remove(actualSecret.getName()); - } - } - - assertEquals(0, secretsToSetAndList.size()); - }); - } - - /** - * Tests that deleted secrets can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - // Skip when running against the service to avoid having pipeline runs take longer than they have to. - if (interceptorManager.isLiveMode()) { - return; - } - - listDeletedSecretsRunner((secretsToSetAndDelete) -> { - for (KeyVaultSecret secret : secretsToSetAndDelete.values()) { - assertSecretEquals(secret, secretClient.setSecret(secret)); - } - - for (KeyVaultSecret secret : secretsToSetAndDelete.values()) { - SyncPoller poller - = setPlaybackSyncPollerPollInterval(secretClient.beginDeleteSecret(secret.getName())); - - poller.waitForCompletion(); - } - - sleepIfRunningAgainstService(60000); - - Iterable deletedSecrets = secretClient.listDeletedSecrets(); - - assertTrue(deletedSecrets.iterator().hasNext()); - - for (DeletedSecret deletedSecret : deletedSecrets) { - assertNotNull(deletedSecret.getDeletedOn()); - assertNotNull(deletedSecret.getRecoveryId()); - } - }); - } - - /** - * Tests that secret versions can be listed in the key vault. - */ - @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) - @MethodSource("getTestParameters") - public void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion) { - createClient(httpClient, serviceVersion); - - listSecretVersionsRunner((secretsToSetAndList) -> { - String secretName = null; - - for (KeyVaultSecret secret : secretsToSetAndList) { - secretName = secret.getName(); - - assertSecretEquals(secret, secretClient.setSecret(secret)); - } - - Iterable secretVersionsOutput = secretClient.listPropertiesOfSecretVersions(secretName); - List secretVersionsList = new ArrayList<>(); - - secretVersionsOutput.forEach(secretVersionsList::add); - - assertEquals(secretsToSetAndList.size(), secretVersionsList.size()); - }); - - } - - private void pollOnSecretPurge(String secretName) { - int pendingPollCount = 0; - - while (pendingPollCount < 10) { - DeletedSecret deletedSecret = null; - - try { - deletedSecret = secretClient.getDeletedSecret(secretName); - } catch (ResourceNotFoundException ignored) { - } - - if (deletedSecret != null) { - sleepIfRunningAgainstService(2000); - pendingPollCount += 1; - } else { - return; - } - } - - LOGGER.log(LogLevel.VERBOSE, () -> "Deleted Secret " + secretName + " was not purged"); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java deleted file mode 100644 index f2271f3088811..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxyRequestMatcher; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.secrets.models.KeyVaultSecret; -import com.azure.security.keyvault.secrets.models.SecretProperties; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.provider.Arguments; - -import java.time.Duration; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -public abstract class SecretClientTestBase extends TestProxyTestBase { - static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; - private static final String AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS - = "AZURE_KEYVAULT_TEST_SECRETS_SERVICE_VERSIONS"; - private static final String SERVICE_VERSION_FROM_ENV - = Configuration.getGlobalConfiguration().get(AZURE_TEST_KEYVAULT_SECRET_SERVICE_VERSIONS); - - private static final String SECRET_NAME = "javaSecretTemp"; - private static final String SECRET_VALUE = "Chocolate is hidden in the toothpaste cabinet"; - - private static final int MAX_RETRIES = 5; - private static final RetryOptions LIVE_RETRY_OPTIONS - = new RetryOptions(new ExponentialBackoffOptions().setMaxRetries(MAX_RETRIES) - .setBaseDelay(Duration.ofSeconds(2)) - .setMaxDelay(Duration.ofSeconds(16))); - - private static final RetryOptions PLAYBACK_RETRY_OPTIONS - = new RetryOptions(new FixedDelayOptions(MAX_RETRIES, Duration.ofMillis(1))); - - void beforeTestSetup() { - KeyVaultCredentialPolicy.clearCache(); - } - - SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, String endpoint, - SecretServiceVersion serviceVersion) { - TokenCredential credential; - - if (interceptorManager.isLiveMode()) { - credential = new AzurePowerShellCredentialBuilder().additionallyAllowedTenants("*").build(); - } else if (interceptorManager.isRecordMode()) { - credential = new DefaultAzureCredentialBuilder().additionallyAllowedTenants("*").build(); - } else { - credential = new MockTokenCredential(); - List customMatchers = new ArrayList<>(); - customMatchers.add(new BodilessMatcher()); - customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); - interceptorManager.addMatchers(customMatchers); - } - - SecretClientBuilder builder = new SecretClientBuilder().vaultUrl(endpoint) - .serviceVersion(serviceVersion) - .credential(credential) - .httpClient(httpClient); - - if (interceptorManager.isPlaybackMode()) { - return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); - } else { - builder.retryOptions(LIVE_RETRY_OPTIONS); - - return interceptorManager.isRecordMode() - ? builder.addPolicy(interceptorManager.getRecordPolicy()) - : builder; - } - } - - @Test - public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void setSecretRunner(Consumer testRunner) { - final Map tags = Collections.singletonMap("foo", "baz"); - - String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); - - final KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, SECRET_VALUE).setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 1, 30, 0, 0, 0, 0, ZoneOffset.UTC)) - .setNotBefore(OffsetDateTime.of(2000, 1, 30, 12, 59, 59, 0, ZoneOffset.UTC)) - .setTags(tags) - .setContentType("text")); - - testRunner.accept(secretToSet); - } - - @Test - public abstract void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void setSecretEmptyValue(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void setSecretEmptyValueRunner(Consumer testRunner) { - String resourceId = testResourceNamer.randomName(SECRET_NAME, 20); - KeyVaultSecret secretToSet = new KeyVaultSecret(resourceId, ""); - - testRunner.accept(secretToSet); - } - - @Test - public abstract void setSecretNull(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void updateSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void updateSecretRunner(BiConsumer testRunner) { - final Map tags = new HashMap<>(); - - tags.put("first tag", "first value"); - tags.put("second tag", "second value"); - - String resourceId = testResourceNamer.randomName("testSecretUpdate", 20); - final KeyVaultSecret originalSecret = new KeyVaultSecret(resourceId, "testSecretVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setTags(tags)); - - final KeyVaultSecret updatedSecret = new KeyVaultSecret(resourceId, "testSecretVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setTags(tags)); - - testRunner.accept(originalSecret, updatedSecret); - } - - @Test - public abstract void updateDisabledSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void updateDisabledSecretRunner(BiConsumer testRunner) { - String resourceId = testResourceNamer.randomName("testUpdateOfDisabledSecret", 35); - - final KeyVaultSecret originalSecret - = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setEnabled(false)); - - final KeyVaultSecret updatedSecret - = new KeyVaultSecret(resourceId, "testSecretUpdateDisabledVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)) - .setEnabled(false)); - - testRunner.accept(originalSecret, updatedSecret); - } - - @Test - public abstract void getSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void getSecretRunner(Consumer testRunner) { - String resourceId = testResourceNamer.randomName("testSecretGet", 20); - final KeyVaultSecret secretToGet = new KeyVaultSecret(resourceId, "testSecretGetVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToGet); - } - - @Test - public abstract void getSecretSpecificVersion(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void getSecretSpecificVersionRunner(BiConsumer testRunner) { - String resourceId = testResourceNamer.randomName("testSecretGetVersion", 30); - final KeyVaultSecret secretWithOriginalValue - = new KeyVaultSecret(resourceId, "testSecretGetVersionVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - final KeyVaultSecret secretWithNewValue = new KeyVaultSecret(resourceId, "newVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretWithOriginalValue, secretWithNewValue); - } - - @Test - public abstract void getSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void deleteSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void deleteSecretRunner(Consumer testRunner) { - String resourceId = testResourceNamer.randomName("testSecretDelete", 20); - final KeyVaultSecret secretToDelete = new KeyVaultSecret(resourceId, "testSecretDeleteVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToDelete); - } - - @Test - public abstract void deleteSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void getDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void getDeletedSecretRunner(Consumer testRunner) { - String resourceId = testResourceNamer.randomName("testSecretGetDeleted", 25); - final KeyVaultSecret secretToDeleteAndGet - = new KeyVaultSecret(resourceId, "testSecretGetDeleteVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToDeleteAndGet); - } - - @Test - public abstract void getDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void recoverDeletedSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void recoverDeletedSecretRunner(Consumer testRunner) { - String resourceId = testResourceNamer.randomName("testSecretRecover", 25); - final KeyVaultSecret secretToDeleteAndRecover - = new KeyVaultSecret(resourceId, "testSecretRecoverVal").setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToDeleteAndRecover); - } - - @Test - public abstract void recoverDeletedSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void backupSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void backupSecretRunner(Consumer testRunner) { - final KeyVaultSecret secretToBackup - = new KeyVaultSecret(testResourceNamer.randomName("testSecretBackup", 20), "testSecretBackupVal") - .setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2060, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToBackup); - } - - @Test - public abstract void backupSecretNotFound(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void restoreSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void restoreSecretRunner(Consumer testRunner) { - final KeyVaultSecret secretToBackupAndRestore - = new KeyVaultSecret(testResourceNamer.randomName("testSecretRestore", 20), "testSecretRestoreVal") - .setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2080, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - testRunner.accept(secretToBackupAndRestore); - } - - @Test - public abstract void restoreSecretFromMalformedBackup(HttpClient httpClient, SecretServiceVersion serviceVersion); - - @Test - public abstract void listSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void listSecretsRunner(Consumer> testRunner) { - HashMap secretsToSetAndList = new HashMap<>(); - - for (int i = 0; i < 2; i++) { - String secretName = testResourceNamer.randomName("listSecret", 20); - String secretVal = "listSecretVal" + i; - KeyVaultSecret secret = new KeyVaultSecret(secretName, secretVal).setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2050, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC))); - - secretsToSetAndList.put(secretName, secret); - } - - testRunner.accept(secretsToSetAndList); - } - - @Test - public abstract void listDeletedSecrets(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void listDeletedSecretsRunner(Consumer> testRunner) { - HashMap secretSecretsToSetAndDelete = new HashMap<>(); - - for (int i = 0; i < 3; i++) { - String secretName = testResourceNamer.randomName("listDeletedSecretsTest", 20); - String secretVal = "listDeletedSecretVal" + i; - - secretSecretsToSetAndDelete.put(secretName, new KeyVaultSecret(secretName, secretVal).setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2090, 5, 25, 0, 0, 0, 0, ZoneOffset.UTC)))); - } - - testRunner.accept(secretSecretsToSetAndDelete); - } - - @Test - public abstract void listSecretVersions(HttpClient httpClient, SecretServiceVersion serviceVersion); - - void listSecretVersionsRunner(Consumer> testRunner) { - List secretsToSetAndList = new ArrayList<>(); - String secretVal; - String secretName = testResourceNamer.randomName("listSecretVersion", 20); - - for (int i = 1; i < 5; i++) { - secretVal = "listSecretVersionVal" + i; - - secretsToSetAndList.add(new KeyVaultSecret(secretName, secretVal).setProperties( - new SecretProperties().setExpiresOn(OffsetDateTime.of(2090, 5, i, 0, 0, 0, 0, ZoneOffset.UTC)))); - } - - testRunner.accept(secretsToSetAndList); - } - - /** - * Helper method to verify that the returned ConfigurationSetting matches what was expected. - * - * @param expected ConfigurationSetting expected to be returned by the service. - * @param actual ConfigurationSetting contained in the RestResponse body. - */ - static void assertSecretEquals(KeyVaultSecret expected, KeyVaultSecret actual) { - assertEquals(expected.getName(), actual.getName()); - assertEquals(expected.getValue(), actual.getValue()); - assertEquals(expected.getProperties().getExpiresOn(), actual.getProperties().getExpiresOn()); - assertEquals(expected.getProperties().getNotBefore(), actual.getProperties().getNotBefore()); - assertEquals(expected.getProperties().getContentType(), actual.getProperties().getContentType()); - assertTagsEquals(expected.getProperties().getTags(), actual.getProperties().getTags()); - } - - static void assertTagsEquals(Map expected, Map actual) { - if (expected == null) { - assertNull(actual); - } else if (actual == null) { - fail("'expected' tags are null but 'actual' tags are not."); - } else { - assertEquals(expected.size(), actual.size()); - expected.forEach((key, value) -> assertEquals(value, actual.get(key))); - } - } - - public String getEndpoint() { - final String endpoint - = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https://localhost:8080"); - - Objects.requireNonNull(endpoint); - - return endpoint; - } - - static void assertRestException(Runnable exceptionThrower, - Class expectedExceptionType, int expectedStatusCode) { - assertRestException(assertThrows(expectedExceptionType, exceptionThrower::run), expectedExceptionType, - expectedStatusCode); - } - - static void assertRestException(Throwable exception, Class expectedExceptionType, - int expectedStatusCode) { - assertEquals(expectedExceptionType, exception.getClass()); - assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); - } - - /** - * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and - * service versions that should be tested. - * - * @return A stream of HttpClient and service version combinations to test. - */ - static Stream getTestParameters() { - // When this issues is closed, the newer version of junit will have better support for cartesian product of - // arguments - https://github.com/junit-team/junit5/issues/1427 - List argumentsList = new ArrayList<>(); - - getHttpClients().forEach(httpClient -> { - Arrays.stream(SecretServiceVersion.values()) - .filter(SecretClientTestBase::shouldServiceVersionBeTested) - .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); - }); - - return argumentsList.stream(); - } - - /** - * Returns whether the given service version match the rules of test framework. - * - *
    - *
  • Using latest service version as default if no environment variable is set.
  • - *
  • If it's set to ALL, all Service versions in {@link SecretServiceVersion} will be tested.
  • - *
  • Otherwise, Service version string should match env variable.
  • - *
- * - * Environment values currently supported are: "ALL", "${version}". - * Use comma to separate http clients want to test. - * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} - * - * @param serviceVersion ServiceVersion needs to check. - * - * @return Boolean indicates whether filters out the service version or not. - */ - private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { - if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { - return SecretServiceVersion.getLatest().equals(serviceVersion); - } - - if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { - return true; - } - - String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); - - return Arrays.stream(configuredServiceVersionList) - .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/TestUtils.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/TestUtils.java deleted file mode 100644 index 3376a7d5faf3f..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/TestUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.security.keyvault.secrets; - -import com.azure.core.credential.AccessToken; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.TokenRequestContext; -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.HttpPipelinePolicy; -import reactor.core.publisher.Mono; - -import java.time.OffsetDateTime; - -/** - * Common test utilities. - */ -public final class TestUtils { - /** - * Private constructor so this class cannot be instantiated. - */ - private TestUtils() { - } - - static class PerCallPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader("Custom-Header", "Some Value"); - return next.process(); - } - - @Override - public HttpPipelinePosition getPipelinePosition() { - return HttpPipelinePosition.PER_CALL; - } - } - - static class PerRetryPolicy implements HttpPipelinePolicy { - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.getHttpRequest().setHeader("Custom-Header", "Some Value"); - return next.process(); - } - } - - static class TestCredential implements TokenCredential { - @Override - public Mono getToken(TokenRequestContext request) { - return Mono.just(new AccessToken("TestAccessToken", OffsetDateTime.now().plusHours(1))); - } - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifierTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifierTest.java deleted file mode 100644 index c6a151e3e7a7b..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/models/KeyVaultSecretIdentifierTest.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.secrets.models; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class KeyVaultSecretIdentifierTest { - @Test - void parseWithoutVersion() { - String sourceId = "https://test-key-vault.vault.azure.net/secrets/test-secret"; - KeyVaultSecretIdentifier keyVaultSecretIdentifier = new KeyVaultSecretIdentifier(sourceId); - - assertEquals(sourceId, keyVaultSecretIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultSecretIdentifier.getVaultUrl()); - assertEquals("test-secret", keyVaultSecretIdentifier.getName()); - assertNull(keyVaultSecretIdentifier.getVersion()); - } - - @Test - void parseWithVersion() { - String sourceId = "https://test-key-vault.vault.azure.net/secrets/test-secret/version"; - KeyVaultSecretIdentifier keyVaultSecretIdentifier = new KeyVaultSecretIdentifier(sourceId); - - assertEquals(sourceId, keyVaultSecretIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultSecretIdentifier.getVaultUrl()); - assertEquals("test-secret", keyVaultSecretIdentifier.getName()); - assertEquals("version", keyVaultSecretIdentifier.getVersion()); - } - - @Test - void parseForDeletedSecret() { - String sourceId = "https://test-key-vault.vault.azure.net/deletedsecrets/test-secret"; - KeyVaultSecretIdentifier keyVaultSecretIdentifier = new KeyVaultSecretIdentifier(sourceId); - - assertEquals(sourceId, keyVaultSecretIdentifier.getSourceId()); - assertEquals("https://test-key-vault.vault.azure.net", keyVaultSecretIdentifier.getVaultUrl()); - assertEquals("test-secret", keyVaultSecretIdentifier.getName()); - } - - @Test - void parseNullIdentifier() { - assertThrows(NullPointerException.class, () -> new KeyVaultSecretIdentifier(null)); - } - - @Test - void parseInvalidIdentifierWithExtraSegment() { - String sourceId = "https://test-key-vault.vault.azure.net/secrets/test-secret/version/extra"; - assertThrows(IllegalArgumentException.class, () -> new KeyVaultSecretIdentifier(sourceId)); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/swagger/autorest.md b/sdk/keyvault/azure-security-keyvault-secrets/swagger/autorest.md deleted file mode 100644 index 41901fa14e8e8..0000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/swagger/autorest.md +++ /dev/null @@ -1,63 +0,0 @@ -# Azure Key Vault Secrets for Java - -> see https://aka.ms/autorest - -This is the Autorest configuration file for KeyVault Secrets. - ---- -## Getting Started -To build the SDK for KeyVault Secrets, simply [Install Autorest](https://aka.ms/autorest) and -in this folder, run: - -> `autorest` - -To see additional help and options, run: - -> `autorest --help` - -### Setup -```ps -npm install -g autorest -``` - -### Generation - -```ps -cd -autorest -``` - -## Configuration - -```yaml -use: '@autorest/java@4.1.42' -output-folder: ../ -java: true -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af9817c15d688c941cda106758045b5deb9a069/specification/keyvault/data-plane/Microsoft.KeyVault/preview/7.6-preview.1/secrets.json -title: SecretClient -namespace: com.azure.security.keyvault.secrets -models-subpackage: implementation.models -custom-types-subpackage: models -enable-sync-stack: true -generate-client-as-impl: true -license-header: MICROSOFT_MIT_SMALL -disable-client-builder: true -``` - -### Rename SecretSetParameters.contentType and SecretUpdateParameters.contentType to secretContentType - -This solves an issue with generators after 4.1.29 (uncertain of which version as the update went from 4.1.29 to 4.1.42) -where in the generated APIs using these types as parameters the previous constant for the request content type of -`String contentType = "application/json"` was removed and replaced with the `contentType` value for `SecretSetParameters` -or `SecretUpdateParameters`. Obtusely, this change causes the interface method to no longer add `@HeaderParam("Content-Type")` -using the `contentType` from `SecretSetParameters` or `SecretUpdateParameters` as the value, but fixes the issue as the -`@BodyParam` will set the content type to `application/json` as expected. - -```yaml -directive: - - from: secrets.json - where: $.definitions - transform: > - $.SecretSetParameters.properties.contentType["x-ms-client-name"] = "secretContentType"; - $.SecretUpdateParameters.properties.contentType["x-ms-client-name"] = "secretContentType"; -``` diff --git a/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml new file mode 100644 index 0000000000000..c321e4e6d599a --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml @@ -0,0 +1,5 @@ +directory: specification/keyvault/Security.KeyVault.Secrets +commit: e4fe31855597549a43777d2eb454137c80a75fab +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common