From fb9fcac30d9fd6f44cd9f9a8653b35cfb6d7d480 Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Thu, 28 May 2020 10:18:56 +0200 Subject: [PATCH] Integrate spring-javaformat Closes gh-564. --- pom.xml | 29 +- .../springframework/vault/VaultException.java | 3 +- .../vault/annotation/VaultPropertySource.java | 2 + .../VaultPropertySourceRegistrar.java | 92 ++--- .../annotation/VaultPropertySources.java | 1 + .../authentication/AppIdAuthentication.java | 28 +- .../AppIdAuthenticationOptions.java | 24 +- .../authentication/AppIdUserIdMechanism.java | 2 +- .../authentication/AppRoleAuthentication.java | 133 +++---- .../AppRoleAuthenticationOptions.java | 76 ++-- .../vault/authentication/AppRoleTokens.java | 6 + .../AuthenticationEventPublisher.java | 11 +- .../authentication/AuthenticationSteps.java | 129 +++--- .../AuthenticationStepsExecutor.java | 40 +- .../AuthenticationStepsFactory.java | 2 +- .../AuthenticationStepsOperator.java | 44 +- .../authentication/AuthenticationUtil.java | 2 +- .../authentication/AwsEc2Authentication.java | 53 +-- .../AwsEc2AuthenticationOptions.java | 37 +- .../authentication/AwsIamAuthentication.java | 68 ++-- .../AwsIamAuthenticationOptions.java | 41 +- .../AzureMsiAuthentication.java | 58 +-- .../AzureMsiAuthenticationOptions.java | 44 +- .../authentication/AzureVmEnvironment.java | 11 +- .../CachingVaultTokenSupplier.java | 14 +- .../authentication/ClientAuthentication.java | 2 +- .../ClientCertificateAuthentication.java | 34 +- ...lientCertificateAuthenticationOptions.java | 8 +- .../authentication/CredentialSupplier.java | 3 +- .../CubbyholeAuthentication.java | 61 ++- .../CubbyholeAuthenticationOptions.java | 37 +- .../DefaultGcpCredentialAccessors.java | 6 +- .../GcpComputeAuthentication.java | 33 +- .../GcpComputeAuthenticationOptions.java | 22 +- .../authentication/GcpCredentialSupplier.java | 3 +- .../authentication/GcpIamAuthentication.java | 32 +- .../GcpIamAuthenticationOptions.java | 64 ++- .../GcpJwtAuthenticationSupport.java | 24 +- .../authentication/GcpProjectIdAccessor.java | 2 +- .../GcpServiceAccountIdAccessor.java | 2 +- .../vault/authentication/IpAddressUserId.java | 1 + .../KubernetesAuthentication.java | 25 +- .../KubernetesAuthenticationOptions.java | 27 +- .../KubernetesServiceAccountTokenFile.java | 10 +- .../LifecycleAwareSessionManager.java | 90 ++--- .../LifecycleAwareSessionManagerSupport.java | 54 +-- .../vault/authentication/LoginToken.java | 21 +- .../authentication/LoginTokenAdapter.java | 24 +- .../vault/authentication/LoginTokenUtil.java | 9 +- .../authentication/MacAddressUserId.java | 49 +-- .../authentication/PcfAuthentication.java | 45 +-- .../PcfAuthenticationOptions.java | 55 +-- .../ReactiveLifecycleAwareSessionManager.java | 135 +++---- .../ReactiveSessionManager.java | 2 +- .../ResourceCredentialSupplier.java | 12 +- .../vault/authentication/SessionManager.java | 2 +- .../vault/authentication/Sha256.java | 6 +- .../authentication/SimpleSessionManager.java | 13 +- .../vault/authentication/StaticUserId.java | 4 +- .../authentication/TokenAuthentication.java | 21 +- .../authentication/UnwrappingEndpoints.java | 8 +- .../authentication/VaultLoginException.java | 11 +- .../VaultSessionManagerException.java | 3 +- .../VaultTokenLookupException.java | 3 +- .../VaultTokenRenewalException.java | 3 +- .../authentication/VaultTokenSupplier.java | 2 +- .../authentication/event/AfterLoginEvent.java | 4 +- .../event/AfterLoginTokenRenewedEvent.java | 4 +- .../event/AfterLoginTokenRevocationEvent.java | 4 +- .../event/AuthenticationErrorEvent.java | 4 +- .../event/AuthenticationErrorListener.java | 2 +- .../event/AuthenticationEvent.java | 4 +- .../event/AuthenticationListener.java | 2 +- .../event/BeforeLoginTokenRenewedEvent.java | 4 +- .../BeforeLoginTokenRevocationEvent.java | 4 +- .../event/LoginFailedEvent.java | 4 +- .../event/LoginTokenExpiredEvent.java | 4 +- .../event/LoginTokenRenewalFailedEvent.java | 4 +- .../LoginTokenRevocationFailedEvent.java | 4 +- .../client/ClientHttpConnectorFactory.java | 59 ++- .../ClientHttpRequestFactoryFactory.java | 159 +++----- .../vault/client/ReactiveVaultClients.java | 39 +- .../vault/client/RestTemplateBuilder.java | 62 +-- .../vault/client/RestTemplateCustomizer.java | 2 +- .../client/RestTemplateRequestCustomizer.java | 2 +- .../client/SimpleVaultEndpointProvider.java | 4 +- .../vault/client/VaultClients.java | 46 +-- .../vault/client/VaultEndpoint.java | 44 +- .../vault/client/VaultEndpointProvider.java | 2 +- .../vault/client/VaultHttpHeaders.java | 1 + .../vault/client/VaultResponses.java | 27 +- .../vault/client/WebClientBuilder.java | 35 +- .../vault/client/WebClientCustomizer.java | 2 +- .../AbstractReactiveVaultConfiguration.java | 32 +- .../config/AbstractVaultConfiguration.java | 64 ++- .../config/ClientHttpConnectorFactory.java | 8 +- .../ClientHttpRequestFactoryFactory.java | 8 +- .../config/EnvironmentVaultConfiguration.java | 97 ++--- .../vault/core/ReactiveVaultOperations.java | 23 +- .../vault/core/ReactiveVaultTemplate.java | 110 ++--- .../vault/core/RestOperationsCallback.java | 2 +- .../vault/core/VaultKeyValue1Template.java | 8 +- .../vault/core/VaultKeyValue2Accessor.java | 9 +- .../vault/core/VaultKeyValue2Template.java | 5 +- .../vault/core/VaultKeyValueAccessor.java | 38 +- .../vault/core/VaultKeyValueOperations.java | 4 +- .../core/VaultKeyValueOperationsSupport.java | 5 +- .../vault/core/VaultListResponse.java | 1 + .../vault/core/VaultOperations.java | 26 +- .../vault/core/VaultPkiOperations.java | 15 +- .../vault/core/VaultPkiTemplate.java | 57 ++- .../vault/core/VaultSysOperations.java | 15 +- .../vault/core/VaultSysTemplate.java | 151 ++++--- .../vault/core/VaultTemplate.java | 85 ++-- .../vault/core/VaultTokenOperations.java | 8 +- .../vault/core/VaultTokenTemplate.java | 23 +- .../vault/core/VaultTransitOperations.java | 38 +- .../vault/core/VaultTransitTemplate.java | 217 ++++------ .../VaultVersionedKeyValueOperations.java | 9 +- .../core/VaultVersionedKeyValueTemplate.java | 37 +- .../vault/core/VaultWrappingOperations.java | 5 - .../vault/core/VaultWrappingTemplate.java | 36 +- .../env/LeaseAwareVaultPropertySource.java | 75 ++-- .../vault/core/env/VaultPropertySource.java | 38 +- .../VaultPropertySourceNotFoundException.java | 3 +- .../vault/core/lease/LeaseEndpoints.java | 33 +- .../core/lease/SecretLeaseContainer.java | 245 +++++------- .../core/lease/SecretLeaseEventPublisher.java | 29 +- .../vault/core/lease/domain/Lease.java | 32 +- .../core/lease/domain/RequestedSecret.java | 22 +- .../event/AfterSecretLeaseRenewedEvent.java | 2 +- .../AfterSecretLeaseRevocationEvent.java | 2 +- .../BeforeSecretLeaseRevocationEvent.java | 5 +- .../core/lease/event/LeaseErrorListener.java | 2 +- .../vault/core/lease/event/LeaseListener.java | 2 +- .../lease/event/LeaseListenerAdapter.java | 1 + .../lease/event/SecretLeaseCreatedEvent.java | 7 +- .../lease/event/SecretLeaseErrorEvent.java | 7 +- .../core/lease/event/SecretLeaseEvent.java | 4 +- .../lease/event/SecretLeaseExpiredEvent.java | 2 +- .../core/lease/event/SecretNotFoundEvent.java | 2 +- .../vault/core/util/KeyValueDelegate.java | 33 +- .../vault/core/util/PropertyTransformer.java | 2 +- .../vault/core/util/PropertyTransformers.java | 17 +- .../EnableVaultRepositories.java | 1 + .../VaultRepositoriesRegistrar.java | 1 + ...VaultRepositoryConfigurationExtension.java | 50 +-- .../convert/AbstractVaultConverter.java | 8 +- .../convert/DefaultVaultTypeMapper.java | 28 +- .../convert/MappingVaultConverter.java | 223 ++++------- .../repository/convert/SecretDocument.java | 19 +- .../convert/SecretDocumentAccessor.java | 20 +- .../repository/convert/VaultConverter.java | 5 +- .../convert/VaultCustomConversions.java | 18 +- .../repository/convert/VaultTypeMapper.java | 2 +- .../core/MappingVaultEntityInformation.java | 5 +- .../core/VaultEntityInformation.java | 1 + .../repository/core/VaultKeyValueAdapter.java | 22 +- .../core/VaultKeyValueTemplate.java | 6 +- .../repository/core/VaultQueryEngine.java | 14 +- .../mapping/BasicVaultPersistentEntity.java | 19 +- .../vault/repository/mapping/Secret.java | 1 + .../mapping/VaultMappingContext.java | 20 +- .../mapping/VaultPersistentEntity.java | 4 +- .../mapping/VaultPersistentProperty.java | 8 +- .../repository/mapping/VaultSimpleTypes.java | 5 +- .../repository/query/VaultPartTreeQuery.java | 20 +- .../vault/repository/query/VaultQuery.java | 15 +- .../repository/query/VaultQueryCreator.java | 72 ++-- .../support/VaultRepositoryFactory.java | 5 +- .../support/VaultRepositoryFactoryBean.java | 5 +- .../vault/security/VaultBytesEncryptor.java | 8 +- .../security/VaultBytesKeyGenerator.java | 14 +- .../vault/support/AbstractResult.java | 13 +- .../vault/support/Certificate.java | 17 +- .../vault/support/CertificateBundle.java | 18 +- .../vault/support/Ciphertext.java | 11 +- .../vault/support/ClientOptions.java | 11 +- .../springframework/vault/support/Hmac.java | 10 +- .../vault/support/JsonMapFlattener.java | 37 +- .../vault/support/KeystoreUtil.java | 82 ++-- .../vault/support/LeaseStrategy.java | 4 +- .../vault/support/PemObject.java | 12 +- .../vault/support/Plaintext.java | 19 +- .../springframework/vault/support/Policy.java | 109 +++-- .../vault/support/RawTransitKey.java | 1 + .../vault/support/Signature.java | 10 +- .../vault/support/SignatureValidation.java | 11 +- .../vault/support/SslConfiguration.java | 212 ++++------ .../vault/support/TransitKeyType.java | 1 + .../support/VaultCertificateRequest.java | 67 ++-- .../support/VaultCertificateResponse.java | 1 + .../vault/support/VaultDecryptionResult.java | 6 +- .../vault/support/VaultEncryptionResult.java | 5 +- .../vault/support/VaultHealth.java | 1 + .../vault/support/VaultHmacRequest.java | 25 +- .../support/VaultInitializationRequest.java | 8 +- .../support/VaultInitializationResponse.java | 1 + .../vault/support/VaultMount.java | 25 +- .../vault/support/VaultResponse.java | 1 + .../vault/support/VaultResponseSupport.java | 40 +- .../VaultSignCertificateRequestResponse.java | 4 +- .../vault/support/VaultSignRequest.java | 19 +- .../VaultSignatureVerificationRequest.java | 39 +- .../vault/support/VaultToken.java | 11 +- .../vault/support/VaultTokenRequest.java | 66 +-- .../vault/support/VaultTokenResponse.java | 2 +- .../vault/support/VaultTransitContext.java | 29 +- .../vault/support/VaultTransitKey.java | 1 + .../support/VaultTransitKeyConfiguration.java | 28 +- .../VaultTransitKeyCreationRequest.java | 41 +- .../vault/support/VaultUnsealStatus.java | 1 + .../vault/support/Versioned.java | 80 ++-- .../vault/support/WrappedMetadata.java | 12 +- ...reVaultPropertySourceIntegrationTests.java | 30 +- ...rceInBeanConfigurationIntegrationTest.java | 9 +- .../VaultPropertySourceIntegrationTests.java | 23 +- ...ropertySourceMultipleIntegrationTests.java | 14 +- .../VaultPropertySourceUnitTests.java | 9 +- ...ppIdAuthenticationIntegrationTestBase.java | 9 +- .../AppIdAuthenticationIntegrationTests.java | 16 +- ...uthenticationOperatorIntegrationTests.java | 14 +- ...IdAuthenticationStepsIntegrationTests.java | 16 +- .../AppIdAuthenticationUnitTests.java | 20 +- ...RoleAuthenticationIntegrationTestBase.java | 25 +- ...AppRoleAuthenticationIntegrationTests.java | 85 ++-- ...leAuthenticationStepsIntegrationTests.java | 74 ++-- .../AppRoleAuthenticationUnitTests.java | 155 +++----- .../AuthenticationStepsExecutorUnitTests.java | 63 ++- .../AuthenticationStepsOperatorUnitTests.java | 40 +- .../AwsEc2AuthenticationUnitTests.java | 84 ++-- .../AwsIamAuthenticationUnitTests.java | 53 +-- .../AzureMsiAuthenticationUnitTests.java | 53 +-- ...cateAuthenticationIntegrationTestBase.java | 49 +-- ...ificateAuthenticationIntegrationTests.java | 62 ++- ...uthenticationOperatorIntegrationTests.java | 17 +- ...teAuthenticationStepsIntegrationTests.java | 28 +- ...entCertificateAuthenticationUnitTests.java | 26 +- ...tCertificateNamespaceIntegrationTests.java | 79 ++-- ...holeAuthenticationIntegrationTestBase.java | 17 +- ...bbyholeAuthenticationIntegrationTests.java | 23 +- ...uthenticationOperatorIntegrationTests.java | 16 +- ...leAuthenticationStepsIntegrationTests.java | 11 +- .../CubbyholeAuthenticationUnitTests.java | 109 ++--- .../GcpComputeAuthenticationUnitTests.java | 34 +- ...AuthenticationOptionsBuilderUnitTests.java | 56 +-- .../GcpIamAuthenticationUnitTests.java | 38 +- .../authentication/IpAddressUserIdTests.java | 4 +- .../KubeServiceAccountTokenFileUnitTests.java | 13 +- ...etesAuthenticationIntegrationTestBase.java | 39 +- ...ernetesAuthenticationIntegrationTests.java | 36 +- ...esAuthenticationStepsIntegrationTests.java | 13 +- .../KubernetesAuthenticationUnitTests.java | 35 +- ...leAwareSessionManagerIntegrationTests.java | 29 +- ...leAwareSessionManagerSupportUnitTests.java | 19 +- ...LifecycleAwareSessionManagerUnitTests.java | 297 +++++++------- .../LoginTokenAdapterUnitTests.java | 14 +- .../authentication/LoginTokenUnitTests.java | 7 +- .../MacAddressUserIdUnitTests.java | 11 +- .../PcfAuthenticationOptionsUnitTests.java | 9 +- .../PcfAuthenticationUnitTests.java | 27 +- ...leAwareSessionManagerIntegrationTests.java | 53 ++- ...LifecycleAwareSessionManagerUnitTests.java | 241 +++++------ ...uthenticationOperatorIntegrationTests.java | 25 +- ...enAuthenticationStepsIntegrationTests.java | 28 +- ...tHttpConnectorFactoryIntegrationTests.java | 6 +- ...RequestFactoryFactoryIntegrationTests.java | 14 +- .../client/ReactiveVaultClientsUnitTests.java | 20 +- .../client/RestTemplateBuilderUnitTests.java | 19 +- .../vault/client/VaultClientsUnitTests.java | 37 +- .../vault/client/VaultEndpointUnitTests.java | 7 +- .../vault/client/VaultResponsesUnitTests.java | 27 +- ...igurationAppIdAuthenticationUnitTests.java | 9 +- ...urationAppRoleAuthenticationUnitTests.java | 9 +- ...gurationAwsEc2AuthenticationUnitTests.java | 8 +- ...rationAzureMSIAuthenticationUnitTests.java | 18 +- ...tionClientCertAuthenticationUnitTests.java | 11 +- ...ationCubbyholeAuthenticationUnitTests.java | 8 +- ...tionKubernetesAuthenticationUnitTests.java | 9 +- ...nvironmentVaultConfigurationUnitTests.java | 29 +- ...VaultKeyValueTemplateIntegrationTests.java | 37 +- .../vault/core/PkiSecretIntegrationTests.java | 12 +- ...iveVaultTemplateAgentIntegrationTests.java | 20 +- ...eVaultTemplateGenericIntegrationTests.java | 84 ++-- .../VaultIntegrationTestConfiguration.java | 4 +- ...VaultKeyValueTemplateIntegrationTests.java | 8 +- ...alueTemplateVersionedIntegrationTests.java | 4 +- .../VaultNamespaceSecretIntegrationTests.java | 107 +++-- .../VaultPkiTemplateIntegrationTests.java | 73 ++-- .../VaultSysTemplateIntegrationTests.java | 93 ++--- .../vault/core/VaultSysTemplateUnitTests.java | 9 +- .../VaultTemplateAgentIntegrationTests.java | 16 +- .../VaultTemplateGenericIntegrationTests.java | 51 ++- .../VaultTemplateTransitIntegrationTests.java | 34 +- .../VaultTokenTemplateIntegrationTests.java | 49 +-- .../VaultTransitTemplateIntegrationTests.java | 353 ++++++++-------- ...ionedKeyValueTemplateIntegrationTests.java | 83 ++-- ...VaultWrappingTemplateIntegrationTests.java | 38 +- ...easeAwareVaultPropertySourceUnitTests.java | 48 +-- .../env/VaultPropertySourceUnitTests.java | 54 ++- ...sionedKeyValueBackendIntegrationTests.java | 7 +- ...icSecretsIntegrationTestConfiguration.java | 19 +- .../lease/SecretLeaseContainerUnitTests.java | 376 ++++++++---------- .../lease/domain/RequestedSecretTests.java | 1 + .../core/util/KeyValueDelegateUnitTests.java | 19 +- .../util/PropertyTransformersUnitTests.java | 18 +- .../vault/demo/SecurePropertyUsage.java | 11 +- .../springframework/vault/demo/VaultApp.java | 10 +- .../springframework/vault/domain/Person.java | 16 +- ...ipleSpringDataModulesIntegrationTests.java | 25 +- .../VaultRepositoryIntegrationTests.java | 39 +- .../DefaultVaultTypeMapperUnitTests.java | 97 ++--- .../MappingVaultConverterUnitTests.java | 88 ++-- .../BasicVaultPersistentEntityUnitTests.java | 22 +- .../mapping/VaultMappingContextUnitTests.java | 19 +- .../query/VaultQueryCreatorUnitTests.java | 27 +- .../VaultBytesEncryptorIntegrationTests.java | 18 +- ...aultBytesKeyGeneratorIntegrationTests.java | 4 +- .../support/CertificateBundleUnitTests.java | 12 +- .../vault/support/CertificateUnitTests.java | 19 +- .../support/JsonMapFlattenerUnitTests.java | 36 +- .../vault/support/ObjectMapperSupplier.java | 2 + .../support/PolicySerializationUnitTests.java | 55 +-- .../support/SslConfigurationUnitTests.java | 10 +- .../VaultCertificateRequestUnitTests.java | 4 +- .../support/VaultTokenRequestUnitTests.java | 13 +- .../support/VaultTransitContextUnitTests.java | 7 +- .../vault/util/CanConnect.java | 2 +- .../vault/util/IntegrationTestSupport.java | 3 +- .../vault/util/PrepareVault.java | 54 +-- .../vault/util/RequiresVaultVersion.java | 1 + .../springframework/vault/util/Settings.java | 14 +- .../vault/util/TestRestTemplateFactory.java | 29 +- .../vault/util/TestWebClientFactory.java | 5 +- .../vault/util/VaultExtension.java | 18 +- .../vault/util/VaultInitializer.java | 34 +- .../vault/util/VaultVersionExtension.java | 30 +- .../springframework/vault/util/Version.java | 65 ++- 338 files changed, 4456 insertions(+), 6299 deletions(-) diff --git a/pom.xml b/pom.xml index 012dd466..23da023e 100644 --- a/pom.xml +++ b/pom.xml @@ -233,6 +233,21 @@ + + io.spring.javaformat + spring-javaformat-maven-plugin + 0.0.22 + + + validate + true + + apply + + + + + org.jetbrains.kotlin kotlin-maven-plugin @@ -748,13 +763,13 @@ - - - - spring-plugins-release - https://repo.spring.io/plugins-release - - + + + + spring-plugins-release + https://repo.spring.io/plugins-release + + diff --git a/spring-vault-core/src/main/java/org/springframework/vault/VaultException.java b/spring-vault-core/src/main/java/org/springframework/vault/VaultException.java index 8967036e..3341ef05 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/VaultException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/VaultException.java @@ -27,7 +27,6 @@ public class VaultException extends NestedRuntimeException { /** * Create a {@code VaultException} with the specified detail message. - * * @param msg the detail message. */ public VaultException(String msg) { @@ -37,11 +36,11 @@ public class VaultException extends NestedRuntimeException { /** * Create a {@code VaultException} with the specified detail message and nested * exception. - * * @param msg the detail message. * @param cause the nested exception. */ public VaultException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java index 0a2ec6d6..e3b1c2dd 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java @@ -131,5 +131,7 @@ public @interface VaultPropertySource { * expires. */ ROTATE; + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java index 08ff4d92..d489c069 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java @@ -56,8 +56,8 @@ import org.springframework.vault.core.util.PropertyTransformers; * * @author Mark Paluch */ -class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, - BeanFactoryPostProcessor, EnvironmentAware { +class VaultPropertySourceRegistrar + implements ImportBeanDefinitionRegistrar, BeanFactoryPostProcessor, EnvironmentAware { private @Nullable Environment environment; @@ -67,24 +67,21 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class); MutablePropertySources propertySources = env.getPropertySources(); - registerPropertySources(beanFactory - .getBeansOfType( - org.springframework.vault.core.env.VaultPropertySource.class) - .values(), propertySources); + registerPropertySources( + beanFactory.getBeansOfType(org.springframework.vault.core.env.VaultPropertySource.class).values(), + propertySources); - registerPropertySources(beanFactory.getBeansOfType( - org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class) - .values(), propertySources); + registerPropertySources(beanFactory + .getBeansOfType(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class).values(), + propertySources); } - private void registerPropertySources( - Collection> propertySources, + private void registerPropertySources(Collection> propertySources, MutablePropertySources mutablePropertySources) { for (PropertySource vaultPropertySource : propertySources) { @@ -98,23 +95,20 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, } @Override - public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, - BeanDefinitionRegistry registry) { + public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null"); Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (!registry.isBeanNameInUse("VaultPropertySourceRegistrar")) { - registry.registerBeanDefinition("VaultPropertySourceRegistrar", - BeanDefinitionBuilder // - .rootBeanDefinition(VaultPropertySourceRegistrar.class) // - .setRole(BeanDefinition.ROLE_INFRASTRUCTURE) // - .getBeanDefinition()); + registry.registerBeanDefinition("VaultPropertySourceRegistrar", BeanDefinitionBuilder // + .rootBeanDefinition(VaultPropertySourceRegistrar.class) // + .setRole(BeanDefinition.ROLE_INFRASTRUCTURE) // + .getBeanDefinition()); } - Set propertySources = attributesForRepeatable( - annotationMetadata, VaultPropertySources.class.getName(), - VaultPropertySource.class.getName()); + Set propertySources = attributesForRepeatable(annotationMetadata, + VaultPropertySources.class.getName(), VaultPropertySource.class.getName()); int counter = 0; @@ -124,19 +118,14 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, String ref = propertySource.getString("vaultTemplateRef"); String propertyNamePrefix = propertySource.getString("propertyNamePrefix"); Renewal renewal = propertySource.getEnum("renewal"); - boolean ignoreSecretNotFound = propertySource - .getBoolean("ignoreSecretNotFound"); + boolean ignoreSecretNotFound = propertySource.getBoolean("ignoreSecretNotFound"); - Assert.isTrue(paths.length > 0, - "At least one @VaultPropertySource(value) location is required"); + Assert.isTrue(paths.length > 0, "At least one @VaultPropertySource(value) location is required"); - Assert.hasText(ref, - "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty"); + Assert.hasText(ref, "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty"); - PropertyTransformer propertyTransformer = StringUtils - .hasText(propertyNamePrefix) - ? PropertyTransformers.propertyNamePrefix(propertyNamePrefix) - : PropertyTransformers.noop(); + PropertyTransformer propertyTransformer = StringUtils.hasText(propertyNamePrefix) + ? PropertyTransformers.propertyNamePrefix(propertyNamePrefix) : PropertyTransformers.noop(); for (String propertyPath : paths) { @@ -144,9 +133,8 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, continue; } - AbstractBeanDefinition beanDefinition = createBeanDefinition(ref, renewal, - propertyTransformer, ignoreSecretNotFound, - potentiallyResolveRequiredPlaceholders(propertyPath)); + AbstractBeanDefinition beanDefinition = createBeanDefinition(ref, renewal, propertyTransformer, + ignoreSecretNotFound, potentiallyResolveRequiredPlaceholders(propertyPath)); do { String beanName = "vaultPropertySource#" + counter; @@ -164,23 +152,19 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, } private String potentiallyResolveRequiredPlaceholders(String expression) { - return this.environment != null - ? this.environment.resolveRequiredPlaceholders(expression) - : expression; + return this.environment != null ? this.environment.resolveRequiredPlaceholders(expression) : expression; } private AbstractBeanDefinition createBeanDefinition(String ref, Renewal renewal, - PropertyTransformer propertyTransformer, boolean ignoreResourceNotFound, - String propertyPath) { + PropertyTransformer propertyTransformer, boolean ignoreResourceNotFound, String propertyPath) { BeanDefinitionBuilder builder; if (isRenewable(renewal)) { - builder = BeanDefinitionBuilder.rootBeanDefinition( - org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class); + builder = BeanDefinitionBuilder + .rootBeanDefinition(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class); - RequestedSecret requestedSecret = renewal == Renewal.ROTATE - ? RequestedSecret.rotating(propertyPath) + RequestedSecret requestedSecret = renewal == Renewal.ROTATE ? RequestedSecret.rotating(propertyPath) : RequestedSecret.renewable(propertyPath); builder.addConstructorArgValue(propertyPath); @@ -188,8 +172,8 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, builder.addConstructorArgValue(requestedSecret); } else { - builder = BeanDefinitionBuilder.rootBeanDefinition( - org.springframework.vault.core.env.VaultPropertySource.class); + builder = BeanDefinitionBuilder + .rootBeanDefinition(org.springframework.vault.core.env.VaultPropertySource.class); builder.addConstructorArgValue(propertyPath); builder.addConstructorArgReference(ref); @@ -208,18 +192,15 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, } @SuppressWarnings("unchecked") - static Set attributesForRepeatable(AnnotationMetadata metadata, - String containerClassName, String annotationClassName) { + static Set attributesForRepeatable(AnnotationMetadata metadata, String containerClassName, + String annotationClassName) { Set result = new LinkedHashSet<>(); - addAttributesIfNotNull(result, - metadata.getAnnotationAttributes(annotationClassName, false)); + addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false)); - Map container = metadata - .getAnnotationAttributes(containerClassName, false); + Map container = metadata.getAnnotationAttributes(containerClassName, false); if (container != null && container.containsKey("value")) { - for (Map containedAttributes : (Map[]) container - .get("value")) { + for (Map containedAttributes : (Map[]) container.get("value")) { addAttributesIfNotNull(result, containedAttributes); } } @@ -232,4 +213,5 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, result.add(AnnotationAttributes.fromMap(attributes)); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java index 94d53f95..c159202a 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java @@ -42,4 +42,5 @@ import org.springframework.context.annotation.Import; public @interface VaultPropertySources { VaultPropertySource[] value(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java index 2769de54..52eee5eb 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java @@ -40,8 +40,7 @@ import org.springframework.web.client.RestOperations; * @deprecated since 2.2. Use {@link AppRoleAuthentication}. */ @Deprecated -public class AppIdAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class AppIdAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(AppIdAuthentication.class); @@ -52,12 +51,10 @@ public class AppIdAuthentication /** * Create a {@link AppIdAuthentication} using {@link AppIdAuthenticationOptions} and * {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public AppIdAuthentication(AppIdAuthenticationOptions options, - RestOperations restOperations) { + public AppIdAuthentication(AppIdAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "AppIdAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -69,19 +66,16 @@ public class AppIdAuthentication /** * Creates a {@link AuthenticationSteps} for AppId authentication given * {@link AppIdAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for AppId authentication. * @since 2.0 */ - public static AuthenticationSteps createAuthenticationSteps( - AppIdAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(AppIdAuthenticationOptions options) { Assert.notNull(options, "AppIdAuthenticationOptions must not be null"); return AuthenticationSteps - .fromSupplier(() -> getAppIdLogin(options.getAppId(), - options.getUserIdMechanism().createUserId())) // + .fromSupplier(() -> getAppIdLogin(options.getAppId(), options.getUserIdMechanism().createUserId())) // .login(AuthenticationUtil.getLoginPath(options.getPath())); } @@ -92,20 +86,19 @@ public class AppIdAuthentication @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(options); + return createAuthenticationSteps(this.options); } private VaultToken createTokenUsingAppId() { - Map login = getAppIdLogin(options.getAppId(), - options.getUserIdMechanism().createUserId()); + Map login = getAppIdLogin(this.options.getAppId(), + this.options.getUserIdMechanism().createUserId()); try { - VaultResponse response = restOperations.postForObject(AuthenticationUtil.getLoginPath(options.getPath()), - login, VaultResponse.class); + VaultResponse response = this.restOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using AppId authentication"); @@ -125,4 +118,5 @@ public class AppIdAuthentication return login; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java index e7bf5c5e..24ec520f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java @@ -50,8 +50,7 @@ public class AppIdAuthenticationOptions { */ private final AppIdUserIdMechanism userIdMechanism; - private AppIdAuthenticationOptions(String path, String appId, - AppIdUserIdMechanism userIdMechanism) { + private AppIdAuthenticationOptions(String path, String appId, AppIdUserIdMechanism userIdMechanism) { this.path = path; this.appId = appId; @@ -69,21 +68,21 @@ public class AppIdAuthenticationOptions { * @return the mount path. */ public String getPath() { - return path; + return this.path; } /** * @return the AppId. */ public String getAppId() { - return appId; + return this.appId; } /** * @return the {@link AppIdUserIdMechanism}. */ public AppIdUserIdMechanism getUserIdMechanism() { - return userIdMechanism; + return this.userIdMechanism; } /** @@ -102,7 +101,6 @@ public class AppIdAuthenticationOptions { /** * Configure the mount path. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AppIdAuthenticationOptionsBuilder}. * @see #DEFAULT_APPID_AUTHENTICATION_PATH @@ -117,7 +115,6 @@ public class AppIdAuthenticationOptions { /** * Configure the AppId. - * * @param appId must not be empty or {@literal null}. * @return {@code this} {@link AppIdAuthenticationOptionsBuilder}. */ @@ -131,12 +128,10 @@ public class AppIdAuthenticationOptions { /** * Configure the {@link AppIdUserIdMechanism}. - * * @param userIdMechanism must not be {@literal null}. * @return {@code this} {@link AppIdAuthenticationOptionsBuilder}. */ - public AppIdAuthenticationOptionsBuilder userIdMechanism( - AppIdUserIdMechanism userIdMechanism) { + public AppIdAuthenticationOptionsBuilder userIdMechanism(AppIdUserIdMechanism userIdMechanism) { Assert.notNull(userIdMechanism, "AppIdUserIdMechanism must not be null"); @@ -147,15 +142,16 @@ public class AppIdAuthenticationOptions { /** * Build a new {@link AppIdAuthenticationOptions} instance. Requires * {@link #userIdMechanism(AppIdUserIdMechanism)} to be configured. - * * @return a new {@link AppIdAuthenticationOptions}. */ public AppIdAuthenticationOptions build() { - Assert.hasText(appId, "AppId must not be empty"); - Assert.notNull(userIdMechanism, "AppIdUserIdMechanism must not be null"); + Assert.hasText(this.appId, "AppId must not be empty"); + Assert.notNull(this.userIdMechanism, "AppIdUserIdMechanism must not be null"); - return new AppIdAuthenticationOptions(path, appId, userIdMechanism); + return new AppIdAuthenticationOptions(this.path, this.appId, this.userIdMechanism); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java index e1adf238..60220314 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java @@ -30,8 +30,8 @@ public interface AppIdUserIdMechanism { /** * Create a UserId for AppId authentication. - * * @return the UserId. */ String createUserId(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java index 257f07f0..f703bc7d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java @@ -63,8 +63,7 @@ import static org.springframework.vault.authentication.AuthenticationUtil.getLog * @see Auth Backend: * AppRole */ -public class AppRoleAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class AppRoleAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(AppRoleAuthentication.class); @@ -75,12 +74,10 @@ public class AppRoleAuthentication /** * Create a {@link AppRoleAuthentication} using {@link AppRoleAuthenticationOptions} * and {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public AppRoleAuthentication(AppRoleAuthenticationOptions options, - RestOperations restOperations) { + public AppRoleAuthentication(AppRoleAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "AppRoleAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -92,35 +89,30 @@ public class AppRoleAuthentication /** * Creates a {@link AuthenticationSteps} for AppRole authentication given * {@link AppRoleAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for AppRole authentication. * @since 2.0 */ - public static AuthenticationSteps createAuthenticationSteps( - AppRoleAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(AppRoleAuthenticationOptions options) { Assert.notNull(options, "AppRoleAuthenticationOptions must not be null"); RoleId roleId = options.getRoleId(); SecretId secretId = options.getSecretId(); - return getAuthenticationSteps(options, roleId, secretId) - .login(getLoginPath(options.getPath())); + return getAuthenticationSteps(options, roleId, secretId).login(getLoginPath(options.getPath())); } - private static Node> getAuthenticationSteps( - AppRoleAuthenticationOptions options, RoleId roleId, SecretId secretId) { + private static Node> getAuthenticationSteps(AppRoleAuthenticationOptions options, RoleId roleId, + SecretId secretId) { Node roleIdSteps = getRoleIdSteps(options, roleId); Node secretIdSteps = getSecretIdSteps(options, secretId); - return roleIdSteps.zipWith(secretIdSteps) - .map(it -> getAppRoleLoginBody(it.getLeft(), it.getRight())); + return roleIdSteps.zipWith(secretIdSteps).map(it -> getAppRoleLoginBody(it.getLeft(), it.getRight())); } - private static Node getRoleIdSteps(AppRoleAuthenticationOptions options, - RoleId roleId) { + private static Node getRoleIdSteps(AppRoleAuthenticationOptions options, RoleId roleId) { if (roleId instanceof Provided) { return AuthenticationSteps.fromSupplier(((Provided) roleId)::getValue); @@ -131,24 +123,19 @@ public class AppRoleAuthentication HttpHeaders headers = createHttpHeaders(((Pull) roleId).getInitialToken()); return AuthenticationSteps - .fromHttpRequest(get(getRoleIdIdPath(options)).with(headers) - .as(VaultResponse.class)) - .map(vaultResponse -> (String) vaultResponse.getRequiredData() - .get("role_id")); + .fromHttpRequest(get(getRoleIdIdPath(options)).with(headers).as(VaultResponse.class)) + .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id")); } if (roleId instanceof Wrapped) { - return unwrapResponse(options.getUnwrappingEndpoints(), - ((Wrapped) roleId).getInitialToken()) - .map(vaultResponse -> (String) vaultResponse.getRequiredData() - .get("role_id")); + return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) roleId).getInitialToken()) + .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id")); } throw new IllegalArgumentException("Unknown RoleId configuration: " + roleId); } - private static Node getSecretIdSteps(AppRoleAuthenticationOptions options, - SecretId secretId) { + private static Node getSecretIdSteps(AppRoleAuthenticationOptions options, SecretId secretId) { if (secretId instanceof Provided) { return AuthenticationSteps.fromSupplier(((Provided) secretId)::getValue); @@ -158,31 +145,25 @@ public class AppRoleAuthentication HttpHeaders headers = createHttpHeaders(((Pull) secretId).getInitialToken()); return AuthenticationSteps - .fromHttpRequest(post(getSecretIdPath(options)).with(headers) - .as(VaultResponse.class)) - .map(vaultResponse -> (String) vaultResponse.getRequiredData() - .get("secret_id")); + .fromHttpRequest(post(getSecretIdPath(options)).with(headers).as(VaultResponse.class)) + .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id")); } if (secretId instanceof Wrapped) { - return unwrapResponse(options.getUnwrappingEndpoints(), - ((Wrapped) secretId).getInitialToken()) - .map(vaultResponse -> (String) vaultResponse.getRequiredData() - .get("secret_id")); + return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) secretId).getInitialToken()) + .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id")); } throw new IllegalArgumentException("Unknown SecretId configuration: " + secretId); } - private static Node unwrapResponse( - UnwrappingEndpoints unwrappingEndpoints, VaultToken token) { + private static Node unwrapResponse(UnwrappingEndpoints unwrappingEndpoints, VaultToken token) { return AuthenticationSteps - .fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), - unwrappingEndpoints.getPath()).with(createHttpHeaders(token)) - .as(VaultResponse.class)) + .fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), unwrappingEndpoints.getPath()) + .with(createHttpHeaders(token)).as(VaultResponse.class)) .map(unwrappingEndpoints::unwrap); } @@ -193,20 +174,18 @@ public class AppRoleAuthentication @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(options); + return createAuthenticationSteps(this.options); } private VaultToken createTokenUsingAppRole() { - Map login = getAppRoleLoginBody(options.getRoleId(), - options.getSecretId()); + Map login = getAppRoleLoginBody(this.options.getRoleId(), this.options.getSecretId()); try { - VaultResponse response = restOperations.postForObject( - getLoginPath(options.getPath()), login, VaultResponse.class); + VaultResponse response = this.restOperations.postForObject(getLoginPath(this.options.getPath()), login, + VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using AppRole authentication"); @@ -229,16 +208,13 @@ public class AppRoleAuthentication try { - ResponseEntity entity = restOperations.exchange( - getRoleIdIdPath(options), HttpMethod.GET, createHttpEntity(token), - VaultResponse.class); + ResponseEntity entity = this.restOperations.exchange(getRoleIdIdPath(this.options), + HttpMethod.GET, createHttpEntity(token), VaultResponse.class); return (String) entity.getBody().getRequiredData().get("role_id"); } catch (HttpStatusCodeException e) { - throw new VaultLoginException( - String.format("Cannot get Role id using AppRole: %s", - VaultResponses.getError(e.getResponseBodyAsString())), - e); + throw new VaultLoginException(String.format("Cannot get Role id using AppRole: %s", + VaultResponses.getError(e.getResponseBodyAsString())), e); } } @@ -247,22 +223,17 @@ public class AppRoleAuthentication VaultToken token = ((Wrapped) roleId).getInitialToken(); try { - UnwrappingEndpoints unwrappingEndpoints = options - .getUnwrappingEndpoints(); - ResponseEntity entity = restOperations.exchange( - unwrappingEndpoints.getPath(), - unwrappingEndpoints.getUnwrapRequestMethod(), - createHttpEntity(token), VaultResponse.class); + UnwrappingEndpoints unwrappingEndpoints = this.options.getUnwrappingEndpoints(); + ResponseEntity entity = this.restOperations.exchange(unwrappingEndpoints.getPath(), + unwrappingEndpoints.getUnwrapRequestMethod(), createHttpEntity(token), VaultResponse.class); VaultResponse response = unwrappingEndpoints.unwrap(entity.getBody()); return (String) response.getRequiredData().get("role_id"); } catch (HttpStatusCodeException e) { - throw new VaultLoginException( - String.format("Cannot unwrap Role id using AppRole: %s", - VaultResponses.getError(e.getResponseBodyAsString())), - e); + throw new VaultLoginException(String.format("Cannot unwrap Role id using AppRole: %s", + VaultResponses.getError(e.getResponseBodyAsString())), e); } } @@ -280,16 +251,13 @@ public class AppRoleAuthentication VaultToken token = ((Pull) secretId).getInitialToken(); try { - VaultResponse response = restOperations.postForObject( - getSecretIdPath(options), createHttpEntity(token), - VaultResponse.class); + VaultResponse response = this.restOperations.postForObject(getSecretIdPath(this.options), + createHttpEntity(token), VaultResponse.class); return (String) response.getRequiredData().get("secret_id"); } catch (HttpStatusCodeException e) { - throw new VaultLoginException( - String.format("Cannot get Secret id using AppRole: %s", - VaultResponses.getError(e.getResponseBodyAsString())), - e); + throw new VaultLoginException(String.format("Cannot get Secret id using AppRole: %s", + VaultResponses.getError(e.getResponseBodyAsString())), e); } } @@ -299,22 +267,17 @@ public class AppRoleAuthentication try { - UnwrappingEndpoints unwrappingEndpoints = options - .getUnwrappingEndpoints(); - ResponseEntity entity = restOperations.exchange( - unwrappingEndpoints.getPath(), - unwrappingEndpoints.getUnwrapRequestMethod(), - createHttpEntity(token), VaultResponse.class); + UnwrappingEndpoints unwrappingEndpoints = this.options.getUnwrappingEndpoints(); + ResponseEntity entity = this.restOperations.exchange(unwrappingEndpoints.getPath(), + unwrappingEndpoints.getUnwrapRequestMethod(), createHttpEntity(token), VaultResponse.class); VaultResponse response = unwrappingEndpoints.unwrap(entity.getBody()); return (String) response.getRequiredData().get("secret_id"); } catch (HttpStatusCodeException e) { - throw new VaultLoginException( - String.format("Cannot unwrap Role id using AppRole: %s", - VaultResponses.getError(e.getResponseBodyAsString())), - e); + throw new VaultLoginException(String.format("Cannot unwrap Role id using AppRole: %s", + VaultResponses.getError(e.getResponseBodyAsString())), e); } } @@ -346,8 +309,7 @@ public class AppRoleAuthentication return login; } - private static Map getAppRoleLoginBody(String roleId, - @Nullable String secretId) { + private static Map getAppRoleLoginBody(String roleId, @Nullable String secretId) { Map login = new HashMap<>(); @@ -361,12 +323,11 @@ public class AppRoleAuthentication } private static String getSecretIdPath(AppRoleAuthenticationOptions options) { - return String.format("auth/%s/role/%s/secret-id", options.getPath(), - options.getAppRole()); + return String.format("auth/%s/role/%s/secret-id", options.getPath(), options.getAppRole()); } private static String getRoleIdIdPath(AppRoleAuthenticationOptions options) { - return String.format("auth/%s/role/%s/role-id", options.getPath(), - options.getAppRole()); + return String.format("auth/%s/role/%s/role-id", options.getPath(), options.getAppRole()); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java index 05899542..4a7a3389 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java @@ -74,9 +74,8 @@ public class AppRoleAuthenticationOptions { @Deprecated private final VaultToken initialToken; - private AppRoleAuthenticationOptions(String path, RoleId roleId, SecretId secretId, - @Nullable String appRole, UnwrappingEndpoints unwrappingEndpoints, - @Nullable VaultToken initialToken) { + private AppRoleAuthenticationOptions(String path, RoleId roleId, SecretId secretId, @Nullable String appRole, + UnwrappingEndpoints unwrappingEndpoints, @Nullable VaultToken initialToken) { this.path = path; this.roleId = roleId; @@ -97,21 +96,21 @@ public class AppRoleAuthenticationOptions { * @return the mount path. */ public String getPath() { - return path; + return this.path; } /** * @return the RoleId. */ public RoleId getRoleId() { - return roleId; + return this.roleId; } /** * @return the bound SecretId. */ public SecretId getSecretId() { - return secretId; + return this.secretId; } /** @@ -120,7 +119,7 @@ public class AppRoleAuthenticationOptions { */ @Nullable public String getAppRole() { - return appRole; + return this.appRole; } /** @@ -128,7 +127,7 @@ public class AppRoleAuthenticationOptions { * @since 2.2 */ public UnwrappingEndpoints getUnwrappingEndpoints() { - return unwrappingEndpoints; + return this.unwrappingEndpoints; } /** @@ -140,7 +139,7 @@ public class AppRoleAuthenticationOptions { @Nullable @Deprecated public VaultToken getInitialToken() { - return initialToken; + return this.initialToken; } /** @@ -176,7 +175,6 @@ public class AppRoleAuthenticationOptions { /** * Configure the mount path. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @see #DEFAULT_APPROLE_AUTHENTICATION_PATH @@ -191,7 +189,6 @@ public class AppRoleAuthenticationOptions { /** * Configure the RoleId. - * * @param roleId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 2.0 @@ -206,10 +203,10 @@ public class AppRoleAuthenticationOptions { /** * Configure the RoleId. - * * @param roleId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. - * @deprecated since 2.0, use {@link #roleId(AppRoleAuthenticationOptions.RoleId)}. + * @deprecated since 2.0, use + * {@link #roleId(AppRoleAuthenticationOptions.RoleId)}. */ @Deprecated public AppRoleAuthenticationOptionsBuilder roleId(String roleId) { @@ -222,7 +219,6 @@ public class AppRoleAuthenticationOptions { /** * Configure a {@code secretId}. - * * @param secretId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 2.0 @@ -237,10 +233,10 @@ public class AppRoleAuthenticationOptions { /** * Configure a {@code secretId}. - * * @param secretId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. - * @deprecated since 2.0, use {@link #secretId(AppRoleAuthenticationOptions.SecretId)}. + * @deprecated since 2.0, use + * {@link #secretId(AppRoleAuthenticationOptions.SecretId)}. */ @Deprecated public AppRoleAuthenticationOptionsBuilder secretId(String secretId) { @@ -253,7 +249,6 @@ public class AppRoleAuthenticationOptions { /** * Configure a {@code appRole}. - * * @param appRole must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 1.1 @@ -268,13 +263,11 @@ public class AppRoleAuthenticationOptions { /** * Configure the {@link UnwrappingEndpoints} to use. - * * @param endpoints must not be {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder} * @since 2.2 */ - public AppRoleAuthenticationOptionsBuilder unwrappingEndpoints( - UnwrappingEndpoints endpoints) { + public AppRoleAuthenticationOptionsBuilder unwrappingEndpoints(UnwrappingEndpoints endpoints) { Assert.notNull(endpoints, "UnwrappingEndpoints must not be empty"); @@ -284,7 +277,6 @@ public class AppRoleAuthenticationOptions { /** * Configure a {@code initialToken}. - * * @param initialToken must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 1.1 @@ -305,47 +297,47 @@ public class AppRoleAuthenticationOptions { * Build a new {@link AppRoleAuthenticationOptions} instance. Requires * {@link #roleId(String)} for push mode or {@link #appRole(String)} and * {@link #initialToken(VaultToken)} for pull mode to be configured. - * * @return a new {@link AppRoleAuthenticationOptions}. */ public AppRoleAuthenticationOptions build() { - Assert.hasText(path, "Path must not be empty"); + Assert.hasText(this.path, "Path must not be empty"); - if (secretId == null) { + if (this.secretId == null) { - if (providedSecretId != null) { - secretId(SecretId.provided(providedSecretId)); + if (this.providedSecretId != null) { + secretId(SecretId.provided(this.providedSecretId)); } - else if (initialToken != null) { - secretId(SecretId.pull(initialToken)); + else if (this.initialToken != null) { + secretId(SecretId.pull(this.initialToken)); } else { secretId(SecretId.absent()); } } - if (roleId == null) { + if (this.roleId == null) { - if (providedRoleId != null) { - roleId(RoleId.provided(providedRoleId)); + if (this.providedRoleId != null) { + roleId(RoleId.provided(this.providedRoleId)); } else { - Assert.notNull(initialToken, + Assert.notNull(this.initialToken, "AppRole authentication configured for pull mode. InitialToken must not be null (pull mode)"); - roleId(RoleId.pull(initialToken)); + roleId(RoleId.pull(this.initialToken)); } } - if (roleId instanceof Pull || secretId instanceof Pull) { - Assert.notNull(appRole, + if (this.roleId instanceof Pull || this.secretId instanceof Pull) { + Assert.notNull(this.appRole, "AppRole authentication configured for pull mode. AppRole must not be null."); } - return new AppRoleAuthenticationOptions(path, roleId, secretId, appRole, - unwrappingEndpoints, initialToken); + return new AppRoleAuthenticationOptions(this.path, this.roleId, this.secretId, this.appRole, + this.unwrappingEndpoints, this.initialToken); } + } /** @@ -360,7 +352,6 @@ public class AppRoleAuthenticationOptions { /** * Create a {@link RoleId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token} from a Cubbyhole. - * * @param initialToken must not be {@literal null}. * @return {@link RoleId} object that obtains its value from unwrapping a response * using the {@link VaultToken initial token}. @@ -377,7 +368,6 @@ public class AppRoleAuthenticationOptions { * Create a {@link RoleId} that obtains its value using pull-mode, specifying a * {@link VaultToken initial token}. The token policy must allow reading the * roleId from {@code auth/approle/role/(role-name)/role-id}. - * * @param initialToken must not be {@literal null}. * @return {@link RoleId} that obtains its value using pull-mode. */ @@ -390,7 +380,6 @@ public class AppRoleAuthenticationOptions { /** * Create a {@link RoleId} that encapsulates a static {@code roleId}. - * * @param roleId must not be {@literal null} or empty. * @return {@link RoleId} that encapsulates a static {@code roleId}. */ @@ -400,6 +389,7 @@ public class AppRoleAuthenticationOptions { return new Provided(roleId); } + } /** @@ -414,7 +404,6 @@ public class AppRoleAuthenticationOptions { /** * Create a {@link SecretId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token} from a Cubbyhole. - * * @param initialToken must not be {@literal null}. * @return {@link SecretId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token}. @@ -431,7 +420,6 @@ public class AppRoleAuthenticationOptions { * Create a {@link SecretId} that obtains its value using pull-mode, specifying a * {@link VaultToken initial token}. The token policy must allow reading the * SecretId from {@code auth/approle/role/(role-name)/secret-id}. - * * @param initialToken must not be {@literal null}. * @return {@link SecretId} that obtains its value using pull-mode. */ @@ -444,7 +432,6 @@ public class AppRoleAuthenticationOptions { /** * Create a {@link SecretId} that encapsulates a static {@code secretId}. - * * @param secretId must not be {@literal null} or empty. * @return {@link SecretId} that encapsulates a static {@code SecretId}. */ @@ -458,11 +445,12 @@ public class AppRoleAuthenticationOptions { /** * Create a {@link SecretId} that represents an absent secretId. Using this object * will not send a secretId during AppRole login. - * * @return a {@link SecretId} that represents an absent secretId */ static SecretId absent() { return AbsentSecretId.INSTANCE; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleTokens.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleTokens.java index a282692e..2ae8d0bb 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleTokens.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleTokens.java @@ -31,7 +31,9 @@ class AppRoleTokens { * Absent secretId. */ enum AbsentSecretId implements SecretId { + INSTANCE; + } /** @@ -48,6 +50,7 @@ class AppRoleTokens { public VaultToken getInitialToken() { return this.initialToken; } + } /** @@ -64,6 +67,7 @@ class AppRoleTokens { public VaultToken getInitialToken() { return this.initialToken; } + } /** @@ -80,5 +84,7 @@ class AppRoleTokens { public String getValue() { return this.value; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationEventPublisher.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationEventPublisher.java index 14439a8d..c5acc0e7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationEventPublisher.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationEventPublisher.java @@ -46,7 +46,6 @@ public abstract class AuthenticationEventPublisher { /** * Add a {@link AuthenticationListener}. The listener starts receiving events as soon * as possible. - * * @param listener lease listener, must not be {@literal null}. */ public void addAuthenticationListener(AuthenticationListener listener) { @@ -58,7 +57,6 @@ public abstract class AuthenticationEventPublisher { /** * Remove a {@link AuthenticationListener}. - * * @param listener must not be {@literal null}. */ public void removeAuthenticationListener(AuthenticationListener listener) { @@ -68,7 +66,6 @@ public abstract class AuthenticationEventPublisher { /** * Add a {@link AuthenticationErrorListener}. The listener starts receiving events as * soon as possible. - * * @param listener lease listener, must not be {@literal null}. */ public void addErrorListener(AuthenticationErrorListener listener) { @@ -80,7 +77,6 @@ public abstract class AuthenticationEventPublisher { /** * Remove a {@link AuthenticationErrorListener}. - * * @param listener must not be {@literal null}. */ public void removeErrorListener(AuthenticationErrorListener listener) { @@ -89,25 +85,24 @@ public abstract class AuthenticationEventPublisher { /** * Dispatch the event to all {@link AuthenticationListener}s. - * * @param authenticationEvent the event to dispatch. */ void dispatch(AuthenticationEvent authenticationEvent) { - for (AuthenticationListener listener : listeners) { + for (AuthenticationListener listener : this.listeners) { listener.onAuthenticationEvent(authenticationEvent); } } /** * Dispatch the event to all {@link AuthenticationErrorListener}s. - * * @param authenticationEvent the event to dispatch. */ void dispatch(AuthenticationErrorEvent authenticationEvent) { - for (AuthenticationErrorListener listener : errorListeners) { + for (AuthenticationErrorListener listener : this.errorListeners) { listener.onAuthenticationError(authenticationEvent); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationSteps.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationSteps.java index c9d8b459..4ae2ad63 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationSteps.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationSteps.java @@ -70,7 +70,6 @@ import org.springframework.vault.support.VaultToken; * {@link AuthenticationSteps} describes the authentication flow. Computation on the * source data is only performed when the flow definition is interpreted by an executor. * - * * @author Mark Paluch * @since 2.0 * @see AuthenticationStepsFactory @@ -83,17 +82,15 @@ public class AuthenticationSteps { /** * Create a flow definition using a provided {@link VaultToken}. - * * @param token the token to be used from this {@link AuthenticationSteps}, must not - * be {@literal null}. + * be {@literal null}. * @return the {@link AuthenticationSteps}. */ public static AuthenticationSteps just(VaultToken token) { Assert.notNull(token, "Vault token must not be null"); - return new AuthenticationSteps( - new SupplierStep<>(() -> token, AuthenticationSteps.HEAD)); + return new AuthenticationSteps(new SupplierStep<>(() -> token, AuthenticationSteps.HEAD)); } /** @@ -106,15 +103,13 @@ public class AuthenticationSteps { Assert.notNull(request, "HttpRequest must not be null"); - return new AuthenticationSteps( - new HttpRequestNode<>(request, AuthenticationSteps.HEAD)); + return new AuthenticationSteps(new HttpRequestNode<>(request, AuthenticationSteps.HEAD)); } /** * Start flow composition from a {@link Supplier}. - * * @param supplier supplier function that will produce the flow value, must not be - * {@literal null}. + * {@literal null}. * @return the first {@link Node}. */ public static Node fromSupplier(Supplier supplier) { @@ -126,7 +121,6 @@ public class AuthenticationSteps { /** * Start flow composition from a {@link HttpRequest}. - * * @param request the HTTP request definition, must not be {@literal null}. * @return the first {@link Node}. */ @@ -143,7 +137,6 @@ public class AuthenticationSteps { /** * Return a {@link List} of node given a {@link PathAware} starting point. - * * @param pathAware must not be {@literal null}. * @return */ @@ -182,9 +175,8 @@ public class AuthenticationSteps { /** * Transform the state object into a different object. - * * @param mappingFunction mapping function to be applied to the state object, must - * not be {@literal null}. + * not be {@literal null}. * @param resulting object type * @return the next {@link Node}. */ @@ -197,7 +189,6 @@ public class AuthenticationSteps { /** * Combine the result from this {@link Node} and another into a {@link Pair}. - * * @return the next {@link Node}. * @since 2.1 */ @@ -211,9 +202,8 @@ public class AuthenticationSteps { /** * Callback with the current state object. - * * @param consumerFunction consumer function to be called with the state object, - * must not be {@literal null}. + * must not be {@literal null}. * @return the next {@link Node}. */ public Node onNext(Consumer consumerFunction) { @@ -225,7 +215,6 @@ public class AuthenticationSteps { /** * Request data using a {@link HttpRequest}. - * * @param request the HTTP request definition, must not be {@literal null}. * @return the next {@link Node}. */ @@ -239,9 +228,8 @@ public class AuthenticationSteps { /** * Terminal operation requesting a {@link VaultToken token} from Vault by posting * the current state to Vaults {@code uriTemplate}. - * * @param uriTemplate Vault authentication endpoint, must not be {@literal null} - * or empty. + * or empty. * @param uriVariables URI variables for URI template expansion. * @return the {@link AuthenticationSteps}. */ @@ -249,14 +237,12 @@ public class AuthenticationSteps { Assert.hasText(uriTemplate, "URI template must not be null or empty"); - return login(HttpRequestBuilder.post(uriTemplate, uriVariables) - .as(VaultResponse.class)); + return login(HttpRequestBuilder.post(uriTemplate, uriVariables).as(VaultResponse.class)); } /** * Terminal operation requesting a {@link VaultToken token} from Vault by issuing * a HTTP request with the current state to Vaults {@code uriTemplate}. - * * @param request HTTP request definition. * @return the {@link AuthenticationSteps}. */ @@ -270,18 +256,17 @@ public class AuthenticationSteps { /** * Terminal operation resulting in a {@link VaultToken token} by applying a * mapping {@link Function} to the current state object. - * * @param mappingFunction mapping function to be applied to the state object, must - * not be {@literal null}. + * not be {@literal null}. * @return the {@link AuthenticationSteps}. */ - public AuthenticationSteps login( - Function mappingFunction) { + public AuthenticationSteps login(Function mappingFunction) { Assert.notNull(mappingFunction, "Mapping function must not be null"); return new AuthenticationSteps(new MapStep<>(mappingFunction, this)); } + } /** @@ -305,7 +290,6 @@ public class AuthenticationSteps { /** * Builder entry point to {@code GET} from {@code uriTemplate}. - * * @param uriTemplate must not be {@literal null} or empty. * @param uriVariables the variables to expand the template. * @return a new {@link HttpRequestBuilder}. @@ -316,7 +300,6 @@ public class AuthenticationSteps { /** * Builder entry point to {@code GET} from {@code uri}. - * * @param uri must not be {@literal null}. * @return a new {@link HttpRequestBuilder}. */ @@ -326,19 +309,16 @@ public class AuthenticationSteps { /** * Builder entry point to {@code POST} to {@code uriTemplate}. - * * @param uriTemplate must not be {@literal null} or empty. * @param uriVariables the variables to expand the template. * @return a new {@link HttpRequestBuilder}. */ - public static HttpRequestBuilder post(String uriTemplate, - String... uriVariables) { + public static HttpRequestBuilder post(String uriTemplate, String... uriVariables) { return new HttpRequestBuilder(HttpMethod.POST, uriTemplate, uriVariables); } /** * Builder entry point to {@code POST} to {@code uri}. - * * @param uri must not be {@literal null}. * @return a new {@link HttpRequestBuilder}. */ @@ -348,14 +328,12 @@ public class AuthenticationSteps { /** * Builder entry point to use {@link HttpMethod} for {@code uriTemplate}. - * * @param uriTemplate must not be {@literal null} or empty. * @param uriVariables the variables to expand the template. * @return a new {@link HttpRequestBuilder}. * @since 2.2 */ - public static HttpRequestBuilder method(HttpMethod method, String uriTemplate, - String... uriVariables) { + public static HttpRequestBuilder method(HttpMethod method, String uriTemplate, String... uriVariables) { return new HttpRequestBuilder(method, uriTemplate, uriVariables); } @@ -364,16 +342,14 @@ public class AuthenticationSteps { this.uri = uri; } - private HttpRequestBuilder(HttpMethod method, @Nullable String uriTemplate, - @Nullable String[] urlVariables) { + private HttpRequestBuilder(HttpMethod method, @Nullable String uriTemplate, @Nullable String[] urlVariables) { this.method = method; this.uriTemplate = uriTemplate; this.urlVariables = urlVariables; } - private HttpRequestBuilder(HttpMethod method, @Nullable URI uri, - @Nullable String uriTemplate, @Nullable String[] urlVariables, - @Nullable HttpEntity entity) { + private HttpRequestBuilder(HttpMethod method, @Nullable URI uri, @Nullable String uriTemplate, + @Nullable String[] urlVariables, @Nullable HttpEntity entity) { this.method = method; this.uri = uri; this.uriTemplate = uriTemplate; @@ -383,7 +359,6 @@ public class AuthenticationSteps { /** * Configure a request {@link HttpEntity entity}. - * * @param httpEntity must not be {@literal null}. * @return a new {@link HttpRequestBuilder}. */ @@ -391,13 +366,11 @@ public class AuthenticationSteps { Assert.notNull(httpEntity, "HttpEntity must not be null"); - return new HttpRequestBuilder(method, uri, uriTemplate, urlVariables, - httpEntity); + return new HttpRequestBuilder(this.method, this.uri, this.uriTemplate, this.urlVariables, httpEntity); } /** * Configure a request {@link HttpHeaders headers}. - * * @param headers must not be {@literal null}. * @return a new {@link HttpRequestBuilder}. */ @@ -405,7 +378,7 @@ public class AuthenticationSteps { Assert.notNull(headers, "HttpHeaders must not be null"); - return new HttpRequestBuilder(method, uri, uriTemplate, urlVariables, + return new HttpRequestBuilder(this.method, this.uri, this.uriTemplate, this.urlVariables, new HttpEntity<>(headers)); } @@ -420,6 +393,7 @@ public class AuthenticationSteps { return new HttpRequest<>(this, type); } + } /** @@ -456,8 +430,8 @@ public class AuthenticationSteps { @Override public String toString() { - return String.format("%s %s AS %s", getMethod(), - getUri() != null ? getUri() : getUriTemplate(), getResponseType()); + return String.format("%s %s AS %s", getMethod(), getUri() != null ? getUri() : getUriTemplate(), + getResponseType()); } HttpMethod getMethod() { @@ -487,6 +461,7 @@ public class AuthenticationSteps { Class getResponseType() { return this.responseType; } + } static final class HttpRequestNode extends Node implements PathAware { @@ -502,7 +477,7 @@ public class AuthenticationSteps { @Override public String toString() { - return definition.toString(); + return this.definition.toString(); } public HttpRequest getDefinition() { @@ -520,13 +495,14 @@ public class AuthenticationSteps { if (!(o instanceof HttpRequestNode)) return false; HttpRequestNode that = (HttpRequestNode) o; - return definition.equals(that.definition) && previous.equals(that.previous); + return this.definition.equals(that.definition) && this.previous.equals(that.previous); } @Override public int hashCode() { - return Objects.hash(definition, previous); + return Objects.hash(this.definition, this.previous); } + } static final class MapStep extends Node implements PathAware { @@ -541,12 +517,12 @@ public class AuthenticationSteps { } O apply(I in) { - return mapper.apply(in); + return this.mapper.apply(in); } @Override public String toString() { - return "Map: " + mapper.toString(); + return "Map: " + this.mapper.toString(); } public Function getMapper() { @@ -564,13 +540,14 @@ public class AuthenticationSteps { if (!(o instanceof MapStep)) return false; MapStep mapStep = (MapStep) o; - return mapper.equals(mapStep.mapper) && previous.equals(mapStep.previous); + return this.mapper.equals(mapStep.mapper) && this.previous.equals(mapStep.previous); } @Override public int hashCode() { - return Objects.hash(mapper, previous); + return Objects.hash(this.mapper, this.previous); } + } static final class ZipStep extends Node> implements PathAware { @@ -586,7 +563,7 @@ public class AuthenticationSteps { @Override public Node getPrevious() { - return left; + return this.left; } @Override @@ -609,13 +586,14 @@ public class AuthenticationSteps { if (!(o instanceof ZipStep)) return false; ZipStep zipStep = (ZipStep) o; - return left.equals(zipStep.left) && right.equals(zipStep.right); + return this.left.equals(zipStep.left) && this.right.equals(zipStep.right); } @Override public int hashCode() { - return Objects.hash(left, right); + return Objects.hash(this.left, this.right); } + } static final class OnNextStep extends Node implements PathAware { @@ -630,13 +608,13 @@ public class AuthenticationSteps { } T apply(T in) { - consumer.accept(in); + this.consumer.accept(in); return in; } @Override public String toString() { - return "Consumer: " + consumer.toString(); + return "Consumer: " + this.consumer.toString(); } public Consumer getConsumer() { @@ -654,13 +632,14 @@ public class AuthenticationSteps { if (!(o instanceof OnNextStep)) return false; OnNextStep that = (OnNextStep) o; - return consumer.equals(that.consumer) && previous.equals(that.previous); + return this.consumer.equals(that.consumer) && this.previous.equals(that.previous); } @Override public int hashCode() { - return Objects.hash(consumer, previous); + return Objects.hash(this.consumer, this.previous); } + } static final class SupplierStep extends Node implements PathAware { @@ -675,12 +654,12 @@ public class AuthenticationSteps { } public T get() { - return supplier.get(); + return this.supplier.get(); } @Override public String toString() { - return "Supplier: " + supplier.toString(); + return "Supplier: " + this.supplier.toString(); } public Supplier getSupplier() { @@ -698,17 +677,20 @@ public class AuthenticationSteps { if (!(o instanceof SupplierStep)) return false; SupplierStep that = (SupplierStep) o; - return supplier.equals(that.supplier) && previous.equals(that.previous); + return this.supplier.equals(that.supplier) && this.previous.equals(that.previous); } @Override public int hashCode() { - return Objects.hash(supplier, previous); + return Objects.hash(this.supplier, this.previous); } + } interface PathAware { + Node getPrevious(); + } /** @@ -731,7 +713,6 @@ public class AuthenticationSteps { /** * Create a new {@link Pair} given {@code left} and {@code right} values. - * * @param left the left value. * @param right the right value. * @return the {@link Pair}. @@ -742,20 +723,18 @@ public class AuthenticationSteps { /** * Type-safe way to get the fist object of this {@link Pair}. - * * @return The first object */ public L getLeft() { - return left; + return this.left; } /** * Type-safe way to get the second object of this {@link Pair}. - * * @return The second object */ public R getRight() { - return right; + return this.right; } @Override @@ -765,22 +744,24 @@ public class AuthenticationSteps { if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; - return left.equals(pair.left) && right.equals(pair.right); + return this.left.equals(pair.left) && this.right.equals(pair.right); } @Override public int hashCode() { - return Objects.hash(left, right); + return Objects.hash(this.left, this.right); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [left=").append(left); - sb.append(", right=").append(right); + sb.append(" [left=").append(this.left); + sb.append(", right=").append(this.right); sb.append(']'); return sb.toString(); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsExecutor.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsExecutor.java index 64b5eb43..837e8c0c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsExecutor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsExecutor.java @@ -56,12 +56,10 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { /** * Create a new {@link AuthenticationStepsExecutor} given {@link AuthenticationSteps} * and {@link RestOperations}. - * * @param steps must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public AuthenticationStepsExecutor(AuthenticationSteps steps, - RestOperations restOperations) { + public AuthenticationStepsExecutor(AuthenticationSteps steps, RestOperations restOperations) { Assert.notNull(steps, "AuthenticationSteps must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -74,7 +72,7 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { @SuppressWarnings("unchecked") public VaultToken login() throws VaultException { - Iterable> steps = chain.steps; + Iterable> steps = this.chain.steps; Object state = evaluate(steps); @@ -89,9 +87,8 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { return LoginTokenUtil.from(response.getAuth()); } - throw new IllegalStateException(String.format( - "Cannot retrieve VaultToken from authentication chain. Got instead %s", - state)); + throw new IllegalStateException( + String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", state)); } private Object evaluate(Iterable> steps) { @@ -101,8 +98,7 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { for (Node o : steps) { if (logger.isDebugEnabled()) { - logger.debug( - String.format("Executing %s with current state %s", o, state)); + logger.debug(String.format("Executing %s with current state %s", o, state)); } try { @@ -127,19 +123,17 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { } if (logger.isDebugEnabled()) { - logger.debug( - String.format("Executed %s with current state %s", o, state)); + logger.debug(String.format("Executed %s with current state %s", o, state)); } } catch (HttpStatusCodeException e) { - throw new VaultLoginException(String.format( - "HTTP request %s in state %s failed with Status %s and body %s", - o, state, e.getRawStatusCode(), - VaultResponses.getError(e.getResponseBodyAsString())), e); + throw new VaultLoginException( + String.format("HTTP request %s in state %s failed with Status %s and body %s", o, state, + e.getRawStatusCode(), VaultResponses.getError(e.getResponseBodyAsString())), + e); } catch (RuntimeException e) { - throw new VaultLoginException( - String.format("Authentication execution failed in %s", o), e); + throw new VaultLoginException(String.format("Authentication execution failed in %s", o), e); } } return state; @@ -171,17 +165,14 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { if (definition.getUri() == null) { - ResponseEntity exchange = restOperations.exchange( - definition.getUriTemplate(), definition.getMethod(), - getEntity(definition.getEntity(), state), - definition.getResponseType(), + ResponseEntity exchange = this.restOperations.exchange(definition.getUriTemplate(), + definition.getMethod(), getEntity(definition.getEntity(), state), definition.getResponseType(), (Object[]) definition.getUrlVariables()); return exchange.getBody(); } - ResponseEntity exchange = restOperations.exchange(definition.getUri(), - definition.getMethod(), getEntity(definition.getEntity(), state), - definition.getResponseType()); + ResponseEntity exchange = this.restOperations.exchange(definition.getUri(), definition.getMethod(), + getEntity(definition.getEntity(), state), definition.getResponseType()); return exchange.getBody(); @@ -199,4 +190,5 @@ public class AuthenticationStepsExecutor implements ClientAuthentication { return entity; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsFactory.java index 8f72c58d..ea19b3f7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsFactory.java @@ -30,8 +30,8 @@ public interface AuthenticationStepsFactory { /** * Get the {@link AuthenticationSteps} describing an authentication flow. - * * @return the {@link AuthenticationSteps} describing an authentication flow. */ AuthenticationSteps getAuthenticationSteps(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsOperator.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsOperator.java index 33ea8e30..d3f9dfbd 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsOperator.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationStepsOperator.java @@ -52,8 +52,7 @@ import org.springframework.web.reactive.function.client.WebClient.RequestBodySpe */ public class AuthenticationStepsOperator implements VaultTokenSupplier { - private static final Log logger = LogFactory - .getLog(AuthenticationStepsOperator.class); + private static final Log logger = LogFactory.getLog(AuthenticationStepsOperator.class); private final AuthenticationSteps chain; @@ -62,7 +61,6 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { /** * Create a new {@link AuthenticationStepsOperator} given {@link AuthenticationSteps} * and {@link WebClient}. - * * @param steps must not be {@literal null}. * @param webClient must not be {@literal null}. */ @@ -78,7 +76,7 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { @Override public Mono getVaultToken() throws VaultException { - Mono state = createMono(chain.steps); + Mono state = createMono(this.chain.steps); return state.map(stateObject -> { @@ -95,11 +93,9 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { return LoginTokenUtil.from(response.getAuth()); } - throw new IllegalStateException(String.format( - "Cannot retrieve VaultToken from authentication chain. Got instead %s", - stateObject)); - }).onErrorMap(t -> new VaultLoginException( - "Cannot retrieve VaultToken from authentication chain", t)); + throw new IllegalStateException( + String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", stateObject)); + }).onErrorMap(t -> new VaultLoginException("Cannot retrieve VaultToken from authentication chain", t)); } private Mono createMono(Iterable> steps) { @@ -109,19 +105,15 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { for (Node o : steps) { if (logger.isDebugEnabled()) { - logger.debug( - String.format("Executing %s with current state %s", o, state)); + logger.debug(String.format("Executing %s with current state %s", o, state)); } if (o instanceof HttpRequestNode) { - state = state - .flatMap(stateObject -> doHttpRequest((HttpRequestNode) o, - stateObject)); + state = state.flatMap(stateObject -> doHttpRequest((HttpRequestNode) o, stateObject)); } if (o instanceof MapStep) { - state = state.map(stateObject -> doMapStep((MapStep) o, - stateObject)); + state = state.map(stateObject -> doMapStep((MapStep) o, stateObject)); } if (o instanceof ZipStep) { @@ -130,18 +122,15 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { } if (o instanceof OnNextStep) { - state = state.doOnNext( - stateObject -> doOnNext((OnNextStep) o, stateObject)); + state = state.doOnNext(stateObject -> doOnNext((OnNextStep) o, stateObject)); } if (o instanceof SupplierStep) { - state = state - .map(stateObject -> doSupplierStep((SupplierStep) o)); + state = state.map(stateObject -> doSupplierStep((SupplierStep) o)); } if (logger.isDebugEnabled()) { - logger.debug( - String.format("Executed %s with current state %s", o, state)); + logger.debug(String.format("Executed %s with current state %s", o, state)); } } return state; @@ -171,11 +160,11 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { RequestBodySpec spec; if (definition.getUri() == null) { - spec = webClient.method(definition.getMethod()).uri( - definition.getUriTemplate(), definition.getUrlVariables()); + spec = this.webClient.method(definition.getMethod()).uri(definition.getUriTemplate(), + definition.getUrlVariables()); } else { - spec = webClient.method(definition.getMethod()).uri(definition.getUri()); + spec = this.webClient.method(definition.getMethod()).uri(definition.getUri()); } for (Entry> header : entity.getHeaders().entrySet()) { @@ -183,8 +172,7 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { } if (entity.getBody() != null && !entity.getBody().equals(Undefinded.INSTANCE)) { - return spec.bodyValue(entity.getBody()).retrieve() - .bodyToMono(definition.getResponseType()); + return spec.bodyValue(entity.getBody()).retrieve().bodyToMono(definition.getResponseType()); } return spec.retrieve().bodyToMono(definition.getResponseType()); @@ -209,5 +197,7 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier { private Undefinded() { } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationUtil.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationUtil.java index a0099359..98f3d40e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationUtil.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AuthenticationUtil.java @@ -9,7 +9,6 @@ abstract class AuthenticationUtil { /** * Returns the login path for a {@code authMount}. - * * @param authMount * @return */ @@ -19,4 +18,5 @@ abstract class AuthenticationUtil { private AuthenticationUtil() { } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java index e4fc1c17..5af7abbb 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java @@ -46,8 +46,7 @@ import org.springframework.web.client.RestOperations; * @see Auth Backend: * aws-ec2 */ -public class AwsEc2Authentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class AwsEc2Authentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(AwsEc2Authentication.class); @@ -63,31 +62,26 @@ public class AwsEc2Authentication /** * Create a new {@link AwsEc2Authentication}. - * * @param vaultRestOperations must not be {@literal null}. */ public AwsEc2Authentication(RestOperations vaultRestOperations) { - this(AwsEc2AuthenticationOptions.DEFAULT, vaultRestOperations, - vaultRestOperations); + this(AwsEc2AuthenticationOptions.DEFAULT, vaultRestOperations, vaultRestOperations); } /** * Create a new {@link AwsEc2Authentication} specifying * {@link AwsEc2AuthenticationOptions}, a Vault and an AWS-Metadata-specific * {@link RestOperations}. - * * @param options must not be {@literal null}. * @param vaultRestOperations must not be {@literal null}. * @param awsMetadataRestOperations must not be {@literal null}. */ - public AwsEc2Authentication(AwsEc2AuthenticationOptions options, - RestOperations vaultRestOperations, + public AwsEc2Authentication(AwsEc2AuthenticationOptions options, RestOperations vaultRestOperations, RestOperations awsMetadataRestOperations) { Assert.notNull(options, "AwsEc2AuthenticationOptions must not be null"); Assert.notNull(vaultRestOperations, "Vault RestOperations must not be null"); - Assert.notNull(awsMetadataRestOperations, - "AWS Metadata RestOperations must not be null"); + Assert.notNull(awsMetadataRestOperations, "AWS Metadata RestOperations must not be null"); this.options = options; this.vaultRestOperations = vaultRestOperations; @@ -97,13 +91,11 @@ public class AwsEc2Authentication /** * Creates a {@link AuthenticationSteps} for AWS-EC2 authentication given * {@link AwsEc2AuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for AWS-EC2 authentication. * @since 2.0 */ - public static AuthenticationSteps createAuthenticationSteps( - AwsEc2AuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(AwsEc2AuthenticationOptions options) { Assert.notNull(options, "AwsEc2AuthenticationOptions must not be null"); @@ -112,14 +104,11 @@ public class AwsEc2Authentication return createAuthenticationSteps(options, nonce, () -> doCreateNonce(options)); } - protected static AuthenticationSteps createAuthenticationSteps( - AwsEc2AuthenticationOptions options, AtomicReference nonce, - Supplier nonceSupplier) { + protected static AuthenticationSteps createAuthenticationSteps(AwsEc2AuthenticationOptions options, + AtomicReference nonce, Supplier nonceSupplier) { return AuthenticationSteps - .fromHttpRequest(HttpRequestBuilder - .get(options.getIdentityDocumentUri().toString()) - .as(String.class)) // + .fromHttpRequest(HttpRequestBuilder.get(options.getIdentityDocumentUri().toString()).as(String.class)) // .map(pkcs7 -> pkcs7.replaceAll("\\r", "")) // .map(pkcs7 -> pkcs7.replace("\\n", "")) // .map(pkcs7 -> { @@ -158,19 +147,16 @@ public class AwsEc2Authentication try { - VaultResponse response = this.vaultRestOperations.postForObject( - AuthenticationUtil.getLoginPath(options.getPath()), login, VaultResponse.class); + VaultResponse response = this.vaultRestOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); if (logger.isDebugEnabled()) { if (response.getAuth().get("metadata") instanceof Map) { - Map metadata = (Map) response - .getAuth().get("metadata"); - logger.debug(String.format( - "Login successful using AWS-EC2 authentication for instance %s, AMI %s", + Map metadata = (Map) response.getAuth().get("metadata"); + logger.debug(String.format("Login successful using AWS-EC2 authentication for instance %s, AMI %s", metadata.get("instance_id"), metadata.get("instance_id"))); } else { @@ -189,8 +175,8 @@ public class AwsEc2Authentication Map login = new HashMap<>(); - if (StringUtils.hasText(options.getRole())) { - login.put("role", options.getRole()); + if (StringUtils.hasText(this.options.getRole())) { + login.put("role", this.options.getRole()); } if (Objects.equals(this.nonce.get(), EMPTY)) { @@ -200,8 +186,8 @@ public class AwsEc2Authentication login.put("nonce", new String(this.nonce.get())); try { - String pkcs7 = this.awsMetadataRestOperations - .getForObject(this.options.getIdentityDocumentUri(), String.class); + String pkcs7 = this.awsMetadataRestOperations.getForObject(this.options.getIdentityDocumentUri(), + String.class); if (StringUtils.hasText(pkcs7)) { login.put("pkcs7", pkcs7.replaceAll("\\r", "").replace("\\n", "")); } @@ -210,9 +196,7 @@ public class AwsEc2Authentication } catch (RestClientException e) { throw new VaultLoginException( - String.format("Cannot obtain Identity Document from %s", - options.getIdentityDocumentUri()), - e); + String.format("Cannot obtain Identity Document from %s", this.options.getIdentityDocumentUri()), e); } } @@ -223,4 +207,5 @@ public class AwsEc2Authentication private static char[] doCreateNonce(AwsEc2AuthenticationOptions options) { return options.getNonce().getValue(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java index d84172e5..796c9c8c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java @@ -69,12 +69,10 @@ public class AwsEc2AuthenticationOptions { private final Nonce nonce; private AwsEc2AuthenticationOptions() { - this(DEFAULT_AWS_AUTHENTICATION_PATH, DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI, "", - Nonce.generated()); + this(DEFAULT_AWS_AUTHENTICATION_PATH, DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI, "", Nonce.generated()); } - private AwsEc2AuthenticationOptions(String path, URI identityDocumentUri, - @Nullable String role, Nonce nonce) { + private AwsEc2AuthenticationOptions(String path, URI identityDocumentUri, @Nullable String role, Nonce nonce) { this.path = path; this.identityDocumentUri = identityDocumentUri; @@ -93,14 +91,14 @@ public class AwsEc2AuthenticationOptions { * @return the path of the aws-ec2 authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return the {@link URI} to the AWS EC2 PKCS#7-signed identity document. */ public URI getIdentityDocumentUri() { - return identityDocumentUri; + return this.identityDocumentUri; } /** @@ -108,14 +106,14 @@ public class AwsEc2AuthenticationOptions { */ @Nullable public String getRole() { - return role; + return this.role; } /** * @return the configured {@link Nonce}. */ public Nonce getNonce() { - return nonce; + return this.nonce; } /** @@ -124,6 +122,7 @@ public class AwsEc2AuthenticationOptions { public static class AwsEc2AuthenticationOptionsBuilder { private String path = DEFAULT_AWS_AUTHENTICATION_PATH; + private URI identityDocumentUri = DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI; @Nullable @@ -136,7 +135,6 @@ public class AwsEc2AuthenticationOptions { /** * Configure the mount path. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}. */ @@ -150,13 +148,11 @@ public class AwsEc2AuthenticationOptions { /** * Configure the Identity Document {@link URI}. - * * @param identityDocumentUri must not be {@literal null}. * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}. * @see #DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI */ - public AwsEc2AuthenticationOptionsBuilder identityDocumentUri( - URI identityDocumentUri) { + public AwsEc2AuthenticationOptionsBuilder identityDocumentUri(URI identityDocumentUri) { Assert.notNull(identityDocumentUri, "Identity document URI must not be null"); @@ -168,7 +164,6 @@ public class AwsEc2AuthenticationOptions { * Configure the name of the role against which the login is being attempted.If * role is not specified, then the login endpoint looks for a role bearing the * name of the AMI ID of the EC2 instance that is trying to login. - * * @param role may be empty or {@literal null}. * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}. */ @@ -181,7 +176,6 @@ public class AwsEc2AuthenticationOptions { /** * Configure a {@link Nonce} for login requests. Defaults to * {@link Nonce#generated()}. - * * @param nonce must not be {@literal null}. * @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}. * @since 1.1 @@ -196,16 +190,15 @@ public class AwsEc2AuthenticationOptions { /** * Build a new {@link AwsEc2AuthenticationOptions} instance. - * * @return a new {@link AwsEc2AuthenticationOptions}. */ public AwsEc2AuthenticationOptions build() { - Assert.notNull(identityDocumentUri, "IdentityDocumentUri must not be null"); + Assert.notNull(this.identityDocumentUri, "IdentityDocumentUri must not be null"); - return new AwsEc2AuthenticationOptions(path, identityDocumentUri, role, - nonce); + return new AwsEc2AuthenticationOptions(this.path, this.identityDocumentUri, this.role, this.nonce); } + } /** @@ -223,7 +216,6 @@ public class AwsEc2AuthenticationOptions { /** * Create a new generated {@link Nonce} using {@link UUID}. - * * @return a new generated {@link Nonce} using {@link UUID}. */ public static Nonce generated() { @@ -232,7 +224,6 @@ public class AwsEc2AuthenticationOptions { /** * Create a wrapped {@link Nonce} given a {@code nonce} value. - * * @return a wrapped {@link Nonce} given for the {@code nonce} value. */ public static Nonce provided(char[] nonce) { @@ -246,7 +237,7 @@ public class AwsEc2AuthenticationOptions { * @return the nonce value. */ public char[] getValue() { - return value; + return this.value; } static class Generated extends Nonce { @@ -254,6 +245,7 @@ public class AwsEc2AuthenticationOptions { Generated() { super(UUID.randomUUID().toString().toCharArray()); } + } static class Provided extends Nonce { @@ -261,6 +253,9 @@ public class AwsEc2AuthenticationOptions { Provided(char[] nonce) { super(nonce); } + } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthentication.java index 3c0d1831..8956f6c6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthentication.java @@ -66,8 +66,7 @@ import org.springframework.web.client.RestOperations; * "https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html">AWS: * GetCallerIdentity */ -public class AwsIamAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class AwsIamAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(AwsIamAuthentication.class); @@ -75,8 +74,7 @@ public class AwsIamAuthentication private static final String REQUEST_BODY = "Action=GetCallerIdentity&Version=2011-06-15"; - private static final String REQUEST_BODY_BASE64_ENCODED = Base64Utils - .encodeToString(REQUEST_BODY.getBytes()); + private static final String REQUEST_BODY_BASE64_ENCODED = Base64Utils.encodeToString(REQUEST_BODY.getBytes()); private final AwsIamAuthenticationOptions options; @@ -86,12 +84,10 @@ public class AwsIamAuthentication * Create a new {@link AwsIamAuthentication} specifying * {@link AwsIamAuthenticationOptions}, a Vault and an AWS-Metadata-specific * {@link RestOperations}. - * * @param options must not be {@literal null}. * @param vaultRestOperations must not be {@literal null}. */ - public AwsIamAuthentication(AwsIamAuthenticationOptions options, - RestOperations vaultRestOperations) { + public AwsIamAuthentication(AwsIamAuthenticationOptions options, RestOperations vaultRestOperations) { Assert.notNull(options, "AwsIamAuthenticationOptions must not be null"); Assert.notNull(vaultRestOperations, "Vault RestOperations must not be null"); @@ -105,13 +101,11 @@ public class AwsIamAuthentication * {@link AwsIamAuthenticationOptions}. The resulting {@link AuthenticationSteps} * reuse eagerly-fetched {@link AWSCredentials} to prevent blocking I/O during * authentication. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for AWS-IAM authentication. * @since 2.2 */ - public static AuthenticationSteps createAuthenticationSteps( - AwsIamAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(AwsIamAuthenticationOptions options) { Assert.notNull(options, "AwsIamAuthenticationOptions must not be null"); @@ -120,11 +114,10 @@ public class AwsIamAuthentication return createAuthenticationSteps(options, credentials); } - protected static AuthenticationSteps createAuthenticationSteps( - AwsIamAuthenticationOptions options, AWSCredentials credentials) { + protected static AuthenticationSteps createAuthenticationSteps(AwsIamAuthenticationOptions options, + AWSCredentials credentials) { - return AuthenticationSteps - .fromSupplier(() -> createRequestBody(options, credentials)) // + return AuthenticationSteps.fromSupplier(() -> createRequestBody(options, credentials)) // .login(AuthenticationUtil.getLoginPath(options.getPath())); } @@ -135,8 +128,7 @@ public class AwsIamAuthentication @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(this.options, - this.options.getCredentialsProvider().getCredentials()); + return createAuthenticationSteps(this.options, this.options.getCredentialsProvider().getCredentials()); } @SuppressWarnings("unchecked") @@ -146,21 +138,17 @@ public class AwsIamAuthentication try { - VaultResponse response = this.vaultRestOperations.postForObject( - AuthenticationUtil.getLoginPath(options.getPath()), login, VaultResponse.class); + VaultResponse response = this.vaultRestOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); if (logger.isDebugEnabled()) { if (response.getAuth().get("metadata") instanceof Map) { - Map metadata = (Map) response - .getAuth().get("metadata"); - logger.debug(String.format( - "Login successful using AWS-IAM authentication for user id %s, ARN %s", - metadata.get("client_user_id"), - metadata.get("canonical_arn"))); + Map metadata = (Map) response.getAuth().get("metadata"); + logger.debug(String.format("Login successful using AWS-IAM authentication for user id %s, ARN %s", + metadata.get("client_user_id"), metadata.get("canonical_arn"))); } else { logger.debug("Login successful using AWS-IAM authentication"); @@ -177,37 +165,31 @@ public class AwsIamAuthentication /** * Create the request body to perform a Vault login using the AWS-IAM authentication * method. - * * @param options must not be {@literal null}. * @return the map containing body key-value pairs. */ - protected static Map createRequestBody( - AwsIamAuthenticationOptions options) { - return createRequestBody(options, - options.getCredentialsProvider().getCredentials()); + protected static Map createRequestBody(AwsIamAuthenticationOptions options) { + return createRequestBody(options, options.getCredentialsProvider().getCredentials()); } /** * Create the request body to perform a Vault login using the AWS-IAM authentication * method. - * * @param options must not be {@literal null}. * @return the map containing body key-value pairs. */ - private static Map createRequestBody( - AwsIamAuthenticationOptions options, AWSCredentials credentials) { + private static Map createRequestBody(AwsIamAuthenticationOptions options, + AWSCredentials credentials) { Map login = new HashMap<>(); login.put("iam_http_request_method", "POST"); - login.put("iam_request_url", Base64Utils - .encodeToString(options.getEndpointUri().toString().getBytes())); + login.put("iam_request_url", Base64Utils.encodeToString(options.getEndpointUri().toString().getBytes())); login.put("iam_request_body", REQUEST_BODY_BASE64_ENCODED); String headerJson = getSignedHeaders(options, credentials); - login.put("iam_request_headers", - Base64Utils.encodeToString(headerJson.getBytes())); + login.put("iam_request_headers", Base64Utils.encodeToString(headerJson.getBytes())); if (!StringUtils.isEmpty(options.getRole())) { login.put("role", options.getRole()); @@ -215,8 +197,7 @@ public class AwsIamAuthentication return login; } - private static String getSignedHeaders(AwsIamAuthenticationOptions options, - AWSCredentials credentials) { + private static String getSignedHeaders(AwsIamAuthenticationOptions options, AWSCredentials credentials) { Map headers = createIamRequestHeaders(options); @@ -246,14 +227,12 @@ public class AwsIamAuthentication } } - private static Map createIamRequestHeaders( - AwsIamAuthenticationOptions options) { + private static Map createIamRequestHeaders(AwsIamAuthenticationOptions options) { Map headers = new LinkedHashMap<>(); headers.put(HttpHeaders.CONTENT_LENGTH, "" + REQUEST_BODY.length()); - headers.put(HttpHeaders.CONTENT_TYPE, - MediaType.APPLICATION_FORM_URLENCODED_VALUE); + headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); if (StringUtils.hasText(options.getServerId())) { headers.put("X-Vault-AWS-IAM-Server-ID", options.getServerId()); @@ -261,4 +240,5 @@ public class AwsIamAuthentication return headers; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthenticationOptions.java index da27c4ba..b9e1585c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsIamAuthenticationOptions.java @@ -71,8 +71,7 @@ public class AwsIamAuthenticationOptions { */ private final URI endpointUri; - private AwsIamAuthenticationOptions(String path, - AWSCredentialsProvider credentialsProvider, @Nullable String role, + private AwsIamAuthenticationOptions(String path, AWSCredentialsProvider credentialsProvider, @Nullable String role, @Nullable String serverId, URI endpointUri) { this.path = path; @@ -93,14 +92,14 @@ public class AwsIamAuthenticationOptions { * @return the path of the aws authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return the credentials provider to obtain AWS credentials. */ public AWSCredentialsProvider getCredentialsProvider() { - return credentialsProvider; + return this.credentialsProvider; } /** @@ -108,7 +107,7 @@ public class AwsIamAuthenticationOptions { */ @Nullable public String getRole() { - return role; + return this.role; } /** @@ -119,7 +118,7 @@ public class AwsIamAuthenticationOptions { */ @Nullable public String getServerId() { - return serverId; + return this.serverId; } /** @@ -130,14 +129,14 @@ public class AwsIamAuthenticationOptions { @Nullable @Deprecated public String getServerName() { - return serverId; + return this.serverId; } /** * @return STS server URI. */ public URI getEndpointUri() { - return endpointUri; + return this.endpointUri; } /** @@ -163,7 +162,6 @@ public class AwsIamAuthenticationOptions { /** * Configure the mount path, defaults to {@literal aws}. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. */ @@ -179,13 +177,11 @@ public class AwsIamAuthenticationOptions { * Configure static AWS credentials, required to calculate the signature. Either * use static credentials or provide a * {@link #credentialsProvider(AWSCredentialsProvider) credentials provider}. - * * @param credentials must not be {@literal null}. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. * @see #credentialsProvider(AWSCredentialsProvider) */ - public AwsIamAuthenticationOptionsBuilder credentials( - AWSCredentials credentials) { + public AwsIamAuthenticationOptionsBuilder credentials(AWSCredentials credentials) { Assert.notNull(credentials, "Credentials must not be null"); @@ -196,16 +192,13 @@ public class AwsIamAuthenticationOptions { * Configure an {@link AWSCredentialsProvider}, required to calculate the * signature. Alternatively, configure static {@link #credentials(AWSCredentials) * credentials}. - * * @param credentialsProvider must not be {@literal null}. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. * @see #credentials(AWSCredentials) */ - public AwsIamAuthenticationOptionsBuilder credentialsProvider( - AWSCredentialsProvider credentialsProvider) { + public AwsIamAuthenticationOptionsBuilder credentialsProvider(AWSCredentialsProvider credentialsProvider) { - Assert.notNull(credentialsProvider, - "AWSCredentialsProvider must not be null"); + Assert.notNull(credentialsProvider, "AWSCredentialsProvider must not be null"); this.credentialsProvider = credentialsProvider; return this; @@ -215,7 +208,6 @@ public class AwsIamAuthenticationOptions { * Configure the name of the role against which the login is being attempted. If * role is not specified, the friendly name (i.e., role name or username) of the * IAM principal authenticated. If a matching role is not found, login fails. - * * @param role must not be empty or {@literal null}. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. */ @@ -231,7 +223,6 @@ public class AwsIamAuthenticationOptions { * Configure a server name (used for {@literal Vault-AWS-IAM-Server-ID}) that is * included in the signature to mitigate the risk of replay attacks. Preferably * use the Vault server DNS name. - * * @param serverId must not be {@literal null} or empty. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. * @since 2.1 @@ -247,7 +238,6 @@ public class AwsIamAuthenticationOptions { /** * Configure a server name that is included in the signature to mitigate the risk * of replay attacks. Preferably use the Vault server DNS name. - * * @param serverName must not be {@literal null} or empty. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. */ @@ -258,7 +248,6 @@ public class AwsIamAuthenticationOptions { /** * Configure an endpoint URI of the STS API, defaults to * {@literal https://sts.amazonaws.com/}. - * * @param endpointUri must not be {@literal null}. * @return {@code this} {@link AwsIamAuthenticationOptionsBuilder}. */ @@ -272,16 +261,16 @@ public class AwsIamAuthenticationOptions { /** * Build a new {@link AwsIamAuthenticationOptions} instance. - * * @return a new {@link AwsIamAuthenticationOptions}. */ public AwsIamAuthenticationOptions build() { - Assert.state(credentialsProvider != null, - "Credentials or CredentialProvider must not be null"); + Assert.state(this.credentialsProvider != null, "Credentials or CredentialProvider must not be null"); - return new AwsIamAuthenticationOptions(path, credentialsProvider, role, - serverId, endpointUri); + return new AwsIamAuthenticationOptions(this.path, this.credentialsProvider, this.role, this.serverId, + this.endpointUri); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthentication.java index e9580d24..528a1063 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthentication.java @@ -73,12 +73,10 @@ public class AzureMsiAuthentication implements ClientAuthentication { /** * Create a new {@link AzureMsiAuthentication}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, - RestOperations restOperations) { + public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, RestOperations restOperations) { this(options, restOperations, restOperations); } @@ -86,19 +84,16 @@ public class AzureMsiAuthentication implements ClientAuthentication { * Create a new {@link AzureMsiAuthentication} specifying * {@link AzureMsiAuthenticationOptions}, a Vault and an Azure-Metadata-specific * {@link RestOperations}. - * * @param options must not be {@literal null}. * @param vaultRestOperations must not be {@literal null}. * @param azureMetadataRestOperations must not be {@literal null}. */ - public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, - RestOperations vaultRestOperations, + public AzureMsiAuthentication(AzureMsiAuthenticationOptions options, RestOperations vaultRestOperations, RestOperations azureMetadataRestOperations) { Assert.notNull(options, "AzureAuthenticationOptions must not be null"); Assert.notNull(vaultRestOperations, "Vault RestOperations must not be null"); - Assert.notNull(azureMetadataRestOperations, - "Azure Instance Metadata RestOperations must not be null"); + Assert.notNull(azureMetadataRestOperations, "Azure Instance Metadata RestOperations must not be null"); this.options = options; this.vaultRestOperations = vaultRestOperations; @@ -108,26 +103,22 @@ public class AzureMsiAuthentication implements ClientAuthentication { /** * Creates a {@link AuthenticationSteps} for Azure authentication given * {@link AzureMsiAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for Azure authentication. */ - public static AuthenticationSteps createAuthenticationSteps( - AzureMsiAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(AzureMsiAuthenticationOptions options) { Assert.notNull(options, "AzureMsiAuthenticationOptions must not be null"); return createAuthenticationSteps(options, options.getVmEnvironment()); } - protected static AuthenticationSteps createAuthenticationSteps( - AzureMsiAuthenticationOptions options, + protected static AuthenticationSteps createAuthenticationSteps(AzureMsiAuthenticationOptions options, @Nullable AzureVmEnvironment environment) { Node msiToken = AuthenticationSteps - .fromHttpRequest( - HttpRequestBuilder.get(options.getIdentityTokenServiceUri()) - .with(METADATA_HEADERS).as(Map.class)) // + .fromHttpRequest(HttpRequestBuilder.get(options.getIdentityTokenServiceUri()).with(METADATA_HEADERS) + .as(Map.class)) // .map(token -> (String) token.get("access_token")); Node environmentSteps; @@ -135,8 +126,7 @@ public class AzureMsiAuthentication implements ClientAuthentication { if (environment == null) { environmentSteps = AuthenticationSteps - .fromHttpRequest(HttpRequestBuilder - .get(options.getInstanceMetadataServiceUri()) + .fromHttpRequest(HttpRequestBuilder.get(options.getInstanceMetadataServiceUri()) .with(METADATA_HEADERS).as(Map.class)) // .map(AzureMsiAuthentication::toAzureVmEnvironment); } @@ -145,8 +135,7 @@ public class AzureMsiAuthentication implements ClientAuthentication { } return environmentSteps.zipWith(msiToken) - .map(tuple -> getAzureLogin(options.getRole(), tuple.getLeft(), - tuple.getRight())) // + .map(tuple -> getAzureLogin(options.getRole(), tuple.getLeft(), tuple.getRight())) // .login(AuthenticationUtil.getLoginPath(options.getPath())); } @@ -157,16 +146,14 @@ public class AzureMsiAuthentication implements ClientAuthentication { private VaultToken createTokenUsingAzureMsiCompute() { - Map login = getAzureLogin(options.getRole(), getVmEnvironment(), - getAccessToken()); + Map login = getAzureLogin(this.options.getRole(), getVmEnvironment(), getAccessToken()); try { - VaultResponse response = this.vaultRestOperations.postForObject( - AuthenticationUtil.getLoginPath(options.getPath()), login, VaultResponse.class); + VaultResponse response = this.vaultRestOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); if (logger.isDebugEnabled()) { logger.debug("Login successful using Azure authentication"); @@ -179,8 +166,7 @@ public class AzureMsiAuthentication implements ClientAuthentication { } } - private static Map getAzureLogin(String role, - AzureVmEnvironment vmEnvironment, String jwt) { + private static Map getAzureLogin(String role, AzureVmEnvironment vmEnvironment, String jwt) { Map loginBody = new LinkedHashMap<>(); loginBody.put("resource_group_name", vmEnvironment.getResourceGroupName()); @@ -194,32 +180,29 @@ public class AzureMsiAuthentication implements ClientAuthentication { private String getAccessToken() { - ResponseEntity response = this.azureMetadataRestOperations.exchange( - options.getIdentityTokenServiceUri(), HttpMethod.GET, METADATA_HEADERS, - Map.class); + ResponseEntity response = this.azureMetadataRestOperations + .exchange(this.options.getIdentityTokenServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class); return (String) response.getBody().get("access_token"); } private AzureVmEnvironment getVmEnvironment() { - AzureVmEnvironment vmEnvironment = options.getVmEnvironment(); + AzureVmEnvironment vmEnvironment = this.options.getVmEnvironment(); return vmEnvironment != null ? vmEnvironment : fetchAzureVmEnvironment(); } private AzureVmEnvironment fetchAzureVmEnvironment() { - ResponseEntity response = this.azureMetadataRestOperations.exchange( - options.getInstanceMetadataServiceUri(), HttpMethod.GET, METADATA_HEADERS, - Map.class); + ResponseEntity response = this.azureMetadataRestOperations + .exchange(this.options.getInstanceMetadataServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class); return toAzureVmEnvironment(response.getBody()); } @SuppressWarnings("unchecked") - private static AzureVmEnvironment toAzureVmEnvironment( - Map instanceMetadata) { + private static AzureVmEnvironment toAzureVmEnvironment(Map instanceMetadata) { Map compute = (Map) instanceMetadata.get("compute"); @@ -229,4 +212,5 @@ public class AzureMsiAuthentication implements ClientAuthentication { return new AzureVmEnvironment(subscriptionId, resourceGroupName, vmName); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthenticationOptions.java index 86879310..fd7b3834 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureMsiAuthenticationOptions.java @@ -69,9 +69,8 @@ public class AzureMsiAuthenticationOptions { @Nullable private final AzureVmEnvironment vmEnvironment; - private AzureMsiAuthenticationOptions(String path, String role, - URI instanceMetadataServiceUri, URI identityTokenServiceUri, - @Nullable AzureVmEnvironment vmEnvironment) { + private AzureMsiAuthenticationOptions(String path, String role, URI instanceMetadataServiceUri, + URI identityTokenServiceUri, @Nullable AzureVmEnvironment vmEnvironment) { this.path = path; this.role = role; @@ -91,14 +90,14 @@ public class AzureMsiAuthenticationOptions { * @return the path of the azure authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return the role against which the login is being attempted. */ public String getRole() { - return role; + return this.role; } /** @@ -108,21 +107,21 @@ public class AzureMsiAuthenticationOptions { */ @Nullable public AzureVmEnvironment getVmEnvironment() { - return vmEnvironment; + return this.vmEnvironment; } /** * @return {@link URI} to the instance metadata endpoint. */ public URI getInstanceMetadataServiceUri() { - return instanceMetadataServiceUri; + return this.instanceMetadataServiceUri; } /** * @return {@link URI} to the token service for the managed identity. */ public URI getIdentityTokenServiceUri() { - return identityTokenServiceUri; + return this.identityTokenServiceUri; } /** @@ -147,7 +146,6 @@ public class AzureMsiAuthenticationOptions { /** * Configure the mount path, defaults to {@literal azure}. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AzureMsiAuthenticationOptionsBuilder}. */ @@ -161,7 +159,6 @@ public class AzureMsiAuthenticationOptions { /** * Configure the name of the role against which the login is being attempted. - * * @param role must not be empty or {@literal null}. * @return {@code this} {@link AzureMsiAuthenticationOptionsBuilder}. */ @@ -178,12 +175,10 @@ public class AzureMsiAuthenticationOptions { * Environment details are passed to Vault as login body. If left unconfigured, * {@link AzureMsiAuthentication} looks up the details from the instance metadata * service. - * * @param vmEnvironment must not be {@literal null}. * @return {@code this} {@link AzureMsiAuthenticationOptionsBuilder}. */ - public AzureMsiAuthenticationOptionsBuilder vmEnvironment( - AzureVmEnvironment vmEnvironment) { + public AzureMsiAuthenticationOptionsBuilder vmEnvironment(AzureVmEnvironment vmEnvironment) { Assert.notNull(vmEnvironment, "AzureVmEnvironment must not be null"); @@ -193,16 +188,13 @@ public class AzureMsiAuthenticationOptions { /** * Configure the instance metadata {@link URI}. - * * @param instanceMetadataServiceUri must not be {@literal null}. * @return {@code this} {@link AzureMsiAuthenticationOptionsBuilder}. * @see #DEFAULT_IDENTITY_TOKEN_SERVICE_URI */ - public AzureMsiAuthenticationOptionsBuilder instanceMetadataUri( - URI instanceMetadataServiceUri) { + public AzureMsiAuthenticationOptionsBuilder instanceMetadataUri(URI instanceMetadataServiceUri) { - Assert.notNull(identityTokenServiceUri, - "Instance metadata service URI must not be null"); + Assert.notNull(this.identityTokenServiceUri, "Instance metadata service URI must not be null"); this.instanceMetadataServiceUri = instanceMetadataServiceUri; return this; @@ -210,16 +202,13 @@ public class AzureMsiAuthenticationOptions { /** * Configure the managed identity service token {@link URI}. - * * @param identityTokenServiceUri must not be {@literal null}. * @return {@code this} {@link AzureMsiAuthenticationOptionsBuilder}. * @see #DEFAULT_IDENTITY_TOKEN_SERVICE_URI */ - public AzureMsiAuthenticationOptionsBuilder identityTokenServiceUri( - URI identityTokenServiceUri) { + public AzureMsiAuthenticationOptionsBuilder identityTokenServiceUri(URI identityTokenServiceUri) { - Assert.notNull(identityTokenServiceUri, - "Identity token service URI must not be null"); + Assert.notNull(identityTokenServiceUri, "Identity token service URI must not be null"); this.identityTokenServiceUri = identityTokenServiceUri; return this; @@ -227,15 +216,16 @@ public class AzureMsiAuthenticationOptions { /** * Build a new {@link AzureMsiAuthenticationOptions} instance. - * * @return a new {@link AzureMsiAuthenticationOptions}. */ public AzureMsiAuthenticationOptions build() { - Assert.hasText(role, "Role must not be null or empty"); + Assert.hasText(this.role, "Role must not be null or empty"); - return new AzureMsiAuthenticationOptions(path, role, - instanceMetadataServiceUri, identityTokenServiceUri, vmEnvironment); + return new AzureMsiAuthenticationOptions(this.path, this.role, this.instanceMetadataServiceUri, + this.identityTokenServiceUri, this.vmEnvironment); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureVmEnvironment.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureVmEnvironment.java index 1a88e290..316607b3 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureVmEnvironment.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AzureVmEnvironment.java @@ -39,13 +39,11 @@ public class AzureVmEnvironment { /** * Creates a new {@link AzureVmEnvironment}. - * * @param subscriptionId must not be {@literal null}. * @param resourceGroupName must not be {@literal null}. * @param vmName must not be {@literal null}. */ - public AzureVmEnvironment(String subscriptionId, String resourceGroupName, - String vmName) { + public AzureVmEnvironment(String subscriptionId, String resourceGroupName, String vmName) { Assert.notNull(subscriptionId, "SubscriptionId must not be null"); Assert.notNull(resourceGroupName, "Resource group name must not be null"); @@ -57,14 +55,15 @@ public class AzureVmEnvironment { } public String getSubscriptionId() { - return subscriptionId; + return this.subscriptionId; } public String getResourceGroupName() { - return resourceGroupName; + return this.resourceGroupName; } public String getVmName() { - return vmName; + return this.vmName; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CachingVaultTokenSupplier.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CachingVaultTokenSupplier.java index 52ef3ed7..70ec6eae 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CachingVaultTokenSupplier.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CachingVaultTokenSupplier.java @@ -32,15 +32,13 @@ import org.springframework.vault.support.VaultToken; * @see VaultTokenSupplier * @see VaultToken */ -public class CachingVaultTokenSupplier - implements VaultTokenSupplier, ReactiveSessionManager { +public class CachingVaultTokenSupplier implements VaultTokenSupplier, ReactiveSessionManager { private static final Mono EMPTY = Mono.empty(); private final VaultTokenSupplier clientAuthentication; - private final AtomicReference> tokenRef = new AtomicReference<>( - EMPTY); + private final AtomicReference> tokenRef = new AtomicReference<>(EMPTY); private CachingVaultTokenSupplier(VaultTokenSupplier clientAuthentication) { this.clientAuthentication = clientAuthentication; @@ -49,7 +47,6 @@ public class CachingVaultTokenSupplier /** * Creates a new {@link CachingVaultTokenSupplier} given a {@link VaultTokenSupplier * delegate supplier}. - * * @param delegate must not be {@literal null}. * @return the {@link CachingVaultTokenSupplier} for a {@link VaultTokenSupplier * delegate supplier}. @@ -61,10 +58,11 @@ public class CachingVaultTokenSupplier @Override public Mono getVaultToken() throws VaultException { - if (Objects.equals(tokenRef.get(), EMPTY)) { - tokenRef.compareAndSet(EMPTY, clientAuthentication.getVaultToken().cache()); + if (Objects.equals(this.tokenRef.get(), EMPTY)) { + this.tokenRef.compareAndSet(EMPTY, this.clientAuthentication.getVaultToken().cache()); } - return tokenRef.get(); + return this.tokenRef.get(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java index 8d0e4ced..14c6fb41 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java @@ -31,8 +31,8 @@ public interface ClientAuthentication { /** * Return a {@link VaultToken}. This method can optionally log into Vault to obtain a * {@link VaultToken token}. - * * @return a {@link VaultToken}. */ VaultToken login() throws VaultException; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java index c04d404a..86507413 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java @@ -33,11 +33,9 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * * @author Mark Paluch */ -public class ClientCertificateAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class ClientCertificateAuthentication implements ClientAuthentication, AuthenticationStepsFactory { - private static final Log logger = LogFactory - .getLog(ClientCertificateAuthentication.class); + private static final Log logger = LogFactory.getLog(ClientCertificateAuthentication.class); private final ClientCertificateAuthenticationOptions options; @@ -45,7 +43,6 @@ public class ClientCertificateAuthentication /** * Create a {@link ClientCertificateAuthentication} using {@link RestOperations}. - * * @param restOperations must not be {@literal null}. */ public ClientCertificateAuthentication(RestOperations restOperations) { @@ -54,7 +51,6 @@ public class ClientCertificateAuthentication /** * Create a {@link ClientCertificateAuthentication} using {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. * @since 2.2.3 @@ -62,8 +58,7 @@ public class ClientCertificateAuthentication public ClientCertificateAuthentication(ClientCertificateAuthenticationOptions options, RestOperations restOperations) { - Assert.notNull(options, - "ClientCertificateAuthenticationOptions must not be null"); + Assert.notNull(options, "ClientCertificateAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); this.restOperations = restOperations; @@ -72,31 +67,25 @@ public class ClientCertificateAuthentication /** * Creates a {@link AuthenticationSteps} for client certificate authentication. - * * @return {@link AuthenticationSteps} for client certificate authentication. * @since 2.0 */ public static AuthenticationSteps createAuthenticationSteps() { - return createAuthenticationSteps( - ClientCertificateAuthenticationOptions.builder().build()); + return createAuthenticationSteps(ClientCertificateAuthenticationOptions.builder().build()); } /** * Creates a {@link AuthenticationSteps} for client certificate authentication. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for client certificate authentication. * @since 2.2.3 */ - public static AuthenticationSteps createAuthenticationSteps( - ClientCertificateAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(ClientCertificateAuthenticationOptions options) { - Assert.notNull(options, - "ClientCertificateAuthenticationOptions must not be null"); + Assert.notNull(options, "ClientCertificateAuthenticationOptions must not be null"); return AuthenticationSteps - .just(post(AuthenticationUtil.getLoginPath(options.getPath())) - .as(VaultResponse.class)); + .just(post(AuthenticationUtil.getLoginPath(options.getPath())).as(VaultResponse.class)); } @Override @@ -106,15 +95,15 @@ public class ClientCertificateAuthentication @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(options); + return createAuthenticationSteps(this.options); } private VaultToken createTokenUsingTlsCertAuthentication() { try { - VaultResponse response = restOperations.postForObject( - AuthenticationUtil.getLoginPath(options.getPath()), - Collections.emptyMap(), VaultResponse.class); + VaultResponse response = this.restOperations.postForObject( + AuthenticationUtil.getLoginPath(this.options.getPath()), Collections.emptyMap(), + VaultResponse.class); Assert.state(response.getAuth() != null, "Auth field must not be null"); @@ -126,4 +115,5 @@ public class ClientCertificateAuthentication throw VaultLoginException.create("TLS Certificates", e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOptions.java index dfb94f59..2f985e57 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOptions.java @@ -53,7 +53,7 @@ public class ClientCertificateAuthenticationOptions { * @return the path of the azure authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** @@ -68,7 +68,6 @@ public class ClientCertificateAuthenticationOptions { /** * Configure the mount path, defaults to {@literal azure}. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link ClientCertificateAuthenticationOptionsBuilder}. */ @@ -82,11 +81,12 @@ public class ClientCertificateAuthenticationOptions { /** * Build a new {@link ClientCertificateAuthenticationOptions} instance. - * * @return a new {@link ClientCertificateAuthenticationOptions}. */ public ClientCertificateAuthenticationOptions build() { - return new ClientCertificateAuthenticationOptions(path); + return new ClientCertificateAuthenticationOptions(this.path); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CredentialSupplier.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CredentialSupplier.java index 290a9a37..2a81b453 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CredentialSupplier.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CredentialSupplier.java @@ -31,7 +31,6 @@ public interface CredentialSupplier extends Supplier { /** * Get a credential to be used with an authentication mechanism. - * * @return the credential. */ @Override @@ -44,7 +43,6 @@ public interface CredentialSupplier extends Supplier { *

* Reusing a cached token can lead to authentication failures if the credential * expires. - * * @return a caching {@link CredentialSupplier}. */ default CredentialSupplier cached() { @@ -53,4 +51,5 @@ public interface CredentialSupplier extends Supplier { return () -> credential; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java index b8951865..e072433c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java @@ -56,8 +56,7 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * wrapping_token_ttl: 0h10m0s * wrapping_token_creation_time: 2016-09-18 20:29:48.652957077 +0200 CEST * wrapped_accessor: 46b6aebb-187f-932a-26d7-4f3d86a68319 - * - * + * * * Setup {@link CubbyholeAuthentication} * @@ -69,8 +68,7 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * .wrapped() * .build(); * CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restOperations); - * - * + * * *

Stored token response usage

Create a Token * @@ -96,8 +94,7 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * * $ export VAULT_TOKEN=895cb88b-aef4-0e33-ba65-d50007290780 * $ vault write cubbyhole/token token=f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819 - * - * + * * * Setup {@link CubbyholeAuthentication} * @@ -109,8 +106,7 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * .path("cubbyhole/token") * .build(); * CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restOperations); - * - * + * * * Remaining TTL/Renewability *

@@ -135,8 +131,7 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * "https://www.vaultproject.io/docs/concepts/response-wrapping.html">Response * Wrapping */ -public class CubbyholeAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class CubbyholeAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(CubbyholeAuthentication.class); @@ -147,12 +142,10 @@ public class CubbyholeAuthentication /** * Create a new {@link CubbyholeAuthentication} given * {@link CubbyholeAuthenticationOptions} and {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public CubbyholeAuthentication(CubbyholeAuthenticationOptions options, - RestOperations restOperations) { + public CubbyholeAuthentication(CubbyholeAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -164,13 +157,11 @@ public class CubbyholeAuthentication /** * Creates a {@link AuthenticationSteps} for cubbyhole authentication given * {@link CubbyholeAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for cubbyhole authentication. * @since 2.0 */ - public static AuthenticationSteps createAuthenticationSteps( - CubbyholeAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(CubbyholeAuthenticationOptions options) { Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null"); @@ -190,15 +181,14 @@ public class CubbyholeAuthentication @Override public VaultToken login() throws VaultException { - String url = getRequestPath(options); + String url = getRequestPath(this.options); VaultResponse data = lookupToken(url); VaultToken tokenToUse = getToken(this.options, data, url); if (shouldEnhanceTokenWithSelfLookup(tokenToUse)) { - LoginTokenAdapter adapter = new LoginTokenAdapter( - new TokenAuthentication(tokenToUse), restOperations); + LoginTokenAdapter adapter = new LoginTokenAdapter(new TokenAuthentication(tokenToUse), this.restOperations); tokenToUse = adapter.login(); } @@ -208,17 +198,17 @@ public class CubbyholeAuthentication @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(options); + return createAuthenticationSteps(this.options); } @Nullable private VaultResponse lookupToken(String url) { try { - HttpMethod unwrapMethod = getRequestMethod(options); - HttpEntity requestEntity = getRequestEntity(options); - ResponseEntity entity = restOperations.exchange(url, - unwrapMethod, requestEntity, VaultResponse.class); + HttpMethod unwrapMethod = getRequestMethod(this.options); + HttpEntity requestEntity = getRequestEntity(this.options); + ResponseEntity entity = this.restOperations.exchange(url, unwrapMethod, requestEntity, + VaultResponse.class); Assert.state(entity.getBody() != null, "Auth response must not be null"); @@ -231,7 +221,7 @@ public class CubbyholeAuthentication private boolean shouldEnhanceTokenWithSelfLookup(VaultToken token) { - if (!options.isSelfLookup()) { + if (!this.options.isSelfLookup()) { return false; } @@ -247,8 +237,7 @@ public class CubbyholeAuthentication return true; } - private static HttpEntity getRequestEntity( - CubbyholeAuthenticationOptions options) { + private static HttpEntity getRequestEntity(CubbyholeAuthenticationOptions options) { return new HttpEntity<>(VaultHttpHeaders.from(options.getInitialToken())); } @@ -270,13 +259,11 @@ public class CubbyholeAuthentication return options.getPath(); } - private static VaultToken getToken(CubbyholeAuthenticationOptions options, - VaultResponse response, String url) { + private static VaultToken getToken(CubbyholeAuthenticationOptions options, VaultResponse response, String url) { if (options.isWrappedToken()) { - VaultResponse responseToUse = options.getUnwrappingEndpoints() - .unwrap(response); + VaultResponse responseToUse = options.getUnwrappingEndpoints().unwrap(response); Assert.state(responseToUse.getAuth() != null, "Auth field must not be null"); @@ -285,9 +272,9 @@ public class CubbyholeAuthentication Map data = response.getData(); if (data == null || data.isEmpty()) { - throw new VaultLoginException(String.format( - "Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token", - options.getPath())); + throw new VaultLoginException( + String.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token", + options.getPath())); } if (data.size() == 1) { @@ -295,8 +282,8 @@ public class CubbyholeAuthentication return VaultToken.of(token); } - throw new VaultLoginException(String.format( - "Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", - url)); + throw new VaultLoginException(String + .format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", url)); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java index adf29ece..7f96c16c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java @@ -58,8 +58,7 @@ public class CubbyholeAuthenticationOptions { private final boolean selfLookup; private CubbyholeAuthenticationOptions(VaultToken initialToken, String path, - UnwrappingEndpoints unwrappingEndpoints, boolean wrappedToken, - boolean selfLookup) { + UnwrappingEndpoints unwrappingEndpoints, boolean wrappedToken, boolean selfLookup) { this.initialToken = initialToken; this.path = path; @@ -79,14 +78,14 @@ public class CubbyholeAuthenticationOptions { * @return the initial {@link VaultToken} to access Cubbyhole. */ public VaultToken getInitialToken() { - return initialToken; + return this.initialToken; } /** * @return the path of the Cubbyhole response path. */ public String getPath() { - return path; + return this.path; } /** @@ -94,7 +93,7 @@ public class CubbyholeAuthenticationOptions { * @since 2.2 */ public UnwrappingEndpoints getUnwrappingEndpoints() { - return unwrappingEndpoints; + return this.unwrappingEndpoints; } /** @@ -103,7 +102,7 @@ public class CubbyholeAuthenticationOptions { * response. */ public boolean isWrappedToken() { - return wrappedToken; + return this.wrappedToken; } /** @@ -114,7 +113,7 @@ public class CubbyholeAuthenticationOptions { * @since 1.0.1 */ public boolean isSelfLookup() { - return selfLookup; + return this.selfLookup; } /** @@ -139,12 +138,10 @@ public class CubbyholeAuthenticationOptions { /** * Configure the initial {@link VaultToken} to access Cubbyhole. - * * @param initialToken must not be {@literal null}. * @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder}. */ - public CubbyholeAuthenticationOptionsBuilder initialToken( - VaultToken initialToken) { + public CubbyholeAuthenticationOptionsBuilder initialToken(VaultToken initialToken) { Assert.notNull(initialToken, "Initial Vault Token must not be null"); @@ -155,7 +152,6 @@ public class CubbyholeAuthenticationOptions { /** * Configure the cubbyhole path, such as {@code cubbyhole/token}. Expects a token * in the {@code data} response. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder}. */ @@ -169,13 +165,11 @@ public class CubbyholeAuthenticationOptions { /** * Configure the {@link UnwrappingEndpoints} to use. - * * @param endpoints must not be {@literal null}. * @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder} * @since 2.2 */ - public CubbyholeAuthenticationOptionsBuilder unwrappingEndpoints( - UnwrappingEndpoints endpoints) { + public CubbyholeAuthenticationOptionsBuilder unwrappingEndpoints(UnwrappingEndpoints endpoints) { Assert.notNull(endpoints, "UnwrappingEndpoints must not be empty"); @@ -185,7 +179,6 @@ public class CubbyholeAuthenticationOptions { /** * Configure whether to use wrapped token responses. - * * @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder}. */ public CubbyholeAuthenticationOptionsBuilder wrapped() { @@ -198,9 +191,8 @@ public class CubbyholeAuthenticationOptions { /** * Configure whether to perform a self-lookup after token retrieval. Defaults to * {@literal true}. - * * @param selfLookup {@literal true} to perform a self-lookup or {@literal false} - * to disable it. + * to disable it. * @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder}. * @since 1.0.1 */ @@ -213,16 +205,17 @@ public class CubbyholeAuthenticationOptions { /** * Build a new {@link CubbyholeAuthenticationOptions} instance. Requires * {@link #path(String)} or {@link #wrapped()} to be configured. - * * @return a new {@link CubbyholeAuthenticationOptions}. */ public CubbyholeAuthenticationOptions build() { - Assert.notNull(initialToken, "Initial Vault Token must not be null"); - Assert.notNull(path, "Path must not be null"); + Assert.notNull(this.initialToken, "Initial Vault Token must not be null"); + Assert.notNull(this.path, "Path must not be null"); - return new CubbyholeAuthenticationOptions(initialToken, path, endpoints, - wrappedToken, selfLookup); + return new CubbyholeAuthenticationOptions(this.initialToken, this.path, this.endpoints, this.wrappedToken, + this.selfLookup); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/DefaultGcpCredentialAccessors.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/DefaultGcpCredentialAccessors.java index 244398dc..c4037124 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/DefaultGcpCredentialAccessors.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/DefaultGcpCredentialAccessors.java @@ -29,14 +29,12 @@ import org.springframework.util.StringUtils; * @since 2.1 * @see GcpIamAuthentication */ -enum DefaultGcpCredentialAccessors - implements GcpProjectIdAccessor, GcpServiceAccountIdAccessor { +enum DefaultGcpCredentialAccessors implements GcpProjectIdAccessor, GcpServiceAccountIdAccessor { INSTANCE; /** * Get a the service account id (email) to be placed in the signed JWT. - * * @param credential credential object to obtain the service account id from. * @return the service account id to use. */ @@ -52,7 +50,6 @@ enum DefaultGcpCredentialAccessors /** * Get a the GCP project id to used in Google Cloud IAM API calls. - * * @param credential the credential object to obtain the project id from. * @return the service account id to use. */ @@ -64,4 +61,5 @@ enum DefaultGcpCredentialAccessors return StringUtils.isEmpty(credential.getServiceAccountProjectId()) ? "-" : credential.getServiceAccountProjectId(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthentication.java index a16541dd..158e7a5e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthentication.java @@ -63,12 +63,10 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport * Create a new {@link GcpComputeAuthentication} instance given * {@link GcpComputeAuthenticationOptions} and {@link RestOperations} for Vault and * Google API use. - * * @param options must not be {@literal null}. * @param vaultRestOperations must not be {@literal null}. */ - public GcpComputeAuthentication(GcpComputeAuthenticationOptions options, - RestOperations vaultRestOperations) { + public GcpComputeAuthentication(GcpComputeAuthenticationOptions options, RestOperations vaultRestOperations) { this(options, vaultRestOperations, vaultRestOperations); } @@ -76,20 +74,17 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport * Create a new {@link GcpComputeAuthentication} instance given * {@link GcpComputeAuthenticationOptions} and {@link RestOperations} for Vault and * Google API use. - * * @param options must not be {@literal null}. * @param vaultRestOperations must not be {@literal null}. * @param googleMetadataRestOperations must not be {@literal null}. */ - public GcpComputeAuthentication(GcpComputeAuthenticationOptions options, - RestOperations vaultRestOperations, + public GcpComputeAuthentication(GcpComputeAuthenticationOptions options, RestOperations vaultRestOperations, RestOperations googleMetadataRestOperations) { super(vaultRestOperations); Assert.notNull(options, "GcpGceAuthenticationOptions must not be null"); - Assert.notNull(googleMetadataRestOperations, - "Google Metadata RestOperations must not be null"); + Assert.notNull(googleMetadataRestOperations, "Google Metadata RestOperations must not be null"); this.options = options; this.googleMetadataRestOperations = googleMetadataRestOperations; @@ -98,22 +93,19 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport /** * Creates a {@link AuthenticationSteps} for GCE authentication given * {@link GcpComputeAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for cubbyhole authentication. */ - public static AuthenticationSteps createAuthenticationSteps( - GcpComputeAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(GcpComputeAuthenticationOptions options) { Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null"); String serviceAccount = options.getServiceAccount(); String audience = getAudience(options.getRole()); - HttpRequest jwtRequest = get(COMPUTE_METADATA_URL_TEMPLATE, - serviceAccount, audience, "full") // - .with(getMetadataHttpHeaders()) // - .as(String.class); + HttpRequest jwtRequest = get(COMPUTE_METADATA_URL_TEMPLATE, serviceAccount, audience, "full") // + .with(getMetadataHttpHeaders()) // + .as(String.class); return AuthenticationSteps.fromHttpRequest(jwtRequest) // @@ -126,13 +118,12 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport String signedJwt = signJwt(); - return doLogin("GCP-GCE", signedJwt, this.options.getPath(), - this.options.getRole()); + return doLogin("GCP-GCE", signedJwt, this.options.getPath(), this.options.getRole()); } @Override public AuthenticationSteps getAuthenticationSteps() { - return createAuthenticationSteps(options); + return createAuthenticationSteps(this.options); } protected String signJwt() { @@ -146,9 +137,8 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport HttpHeaders headers = getMetadataHttpHeaders(); HttpEntity entity = new HttpEntity<>(headers); - ResponseEntity response = googleMetadataRestOperations.exchange( - COMPUTE_METADATA_URL_TEMPLATE, HttpMethod.GET, entity, String.class, - urlParameters); + ResponseEntity response = this.googleMetadataRestOperations.exchange(COMPUTE_METADATA_URL_TEMPLATE, + HttpMethod.GET, entity, String.class, urlParameters); return response.getBody(); } @@ -169,4 +159,5 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport private static String getAudience(String role) { return String.format("https://localhost:8200/vault/%s", role); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthenticationOptions.java index 9a840243..dbb81367 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpComputeAuthenticationOptions.java @@ -50,8 +50,7 @@ public class GcpComputeAuthenticationOptions { */ private final String role; - private GcpComputeAuthenticationOptions(String path, String serviceAccount, - String role) { + private GcpComputeAuthenticationOptions(String path, String serviceAccount, String role) { this.path = path; this.serviceAccount = serviceAccount; @@ -69,21 +68,21 @@ public class GcpComputeAuthenticationOptions { * @return the path of the gcp authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return the GCE service account identifier. */ public String getServiceAccount() { - return serviceAccount; + return this.serviceAccount; } /** * @return name of the role against which the login is being attempted. */ public String getRole() { - return role; + return this.role; } /** @@ -103,7 +102,6 @@ public class GcpComputeAuthenticationOptions { /** * Configure the mount path, defaults to {@literal aws}. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link GcpComputeAuthenticationOptionsBuilder}. */ @@ -118,12 +116,10 @@ public class GcpComputeAuthenticationOptions { /** * Configure the service account identifier. Uses the {@code default} service * account if left unconfigured. - * * @param serviceAccount must not be empty or {@literal null}. * @return {@code this} {@link GcpComputeAuthenticationOptionsBuilder}. */ - public GcpComputeAuthenticationOptionsBuilder serviceAccount( - String serviceAccount) { + public GcpComputeAuthenticationOptionsBuilder serviceAccount(String serviceAccount) { Assert.hasText(serviceAccount, "Service account must not be null"); @@ -133,7 +129,6 @@ public class GcpComputeAuthenticationOptions { /** * Configure the name of the role against which the login is being attempted. - * * @param role must not be empty or {@literal null}. * @return {@code this} {@link GcpComputeAuthenticationOptionsBuilder}. */ @@ -147,14 +142,15 @@ public class GcpComputeAuthenticationOptions { /** * Build a new {@link GcpComputeAuthenticationOptions} instance. - * * @return a new {@link GcpComputeAuthenticationOptions}. */ public GcpComputeAuthenticationOptions build() { - Assert.notNull(role, "Role must not be null"); + Assert.notNull(this.role, "Role must not be null"); - return new GcpComputeAuthenticationOptions(path, serviceAccount, role); + return new GcpComputeAuthenticationOptions(this.path, this.serviceAccount, this.role); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpCredentialSupplier.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpCredentialSupplier.java index bf7f8814..00a31f85 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpCredentialSupplier.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpCredentialSupplier.java @@ -33,7 +33,6 @@ public interface GcpCredentialSupplier extends Supplier { /** * Exception-safe helper to get {@link GoogleCredential} from {@link #getCredential}. - * * @return the GoogleCredential for JWT signing. */ @Override @@ -49,9 +48,9 @@ public interface GcpCredentialSupplier extends Supplier { /** * Get a {@link GoogleCredential} for GCP IAM authentication via JWT signing. - * * @return the {@link GoogleCredential}. * @throws IOException if the credential lookup fails. */ GoogleCredential getCredential() throws IOException; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthentication.java index 9240c717..ecf36069 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthentication.java @@ -63,8 +63,7 @@ import org.springframework.web.client.RestOperations; * "https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signJwt">GCP: * projects.serviceAccounts.signJwt */ -public class GcpIamAuthentication extends GcpJwtAuthenticationSupport - implements ClientAuthentication { +public class GcpIamAuthentication extends GcpJwtAuthenticationSupport implements ClientAuthentication { private static final JsonFactory JSON_FACTORY = new JacksonFactory(); @@ -78,12 +77,10 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport * Create a new instance of {@link GcpIamAuthentication} given * {@link GcpIamAuthenticationOptions} and {@link RestOperations}. This constructor * initializes {@link GoogleApacheHttpTransport} for Google API usage. - * * @param options must not be {@literal null}. * @param restOperations HTTP client for for Vault login, must not be {@literal null}. */ - public GcpIamAuthentication(GcpIamAuthenticationOptions options, - RestOperations restOperations) { + public GcpIamAuthentication(GcpIamAuthenticationOptions options, RestOperations restOperations) { this(options, restOperations, new NetHttpTransport()); } @@ -91,13 +88,12 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport * Create a new instance of {@link GcpIamAuthentication} given * {@link GcpIamAuthenticationOptions}, {@link RestOperations} and * {@link HttpTransport}. - * * @param options must not be {@literal null}. * @param restOperations HTTP client for for Vault login, must not be {@literal null}. * @param httpTransport HTTP client for Google API use, must not be {@literal null}. */ - public GcpIamAuthentication(GcpIamAuthenticationOptions options, - RestOperations restOperations, HttpTransport httpTransport) { + public GcpIamAuthentication(GcpIamAuthenticationOptions options, RestOperations restOperations, + HttpTransport httpTransport) { super(restOperations); @@ -115,17 +111,16 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport String signedJwt = signJwt(); - return doLogin("GCP-IAM", signedJwt, this.options.getPath(), - this.options.getRole()); + return doLogin("GCP-IAM", signedJwt, this.options.getPath(), this.options.getRole()); } protected String signJwt() { String projectId = getProjectId(); String serviceAccount = getServiceAccountId(); - Map jwtPayload = getJwtPayload(options, serviceAccount); + Map jwtPayload = getJwtPayload(this.options, serviceAccount); - Iam iam = new Builder(httpTransport, JSON_FACTORY, credential) + Iam iam = new Builder(this.httpTransport, JSON_FACTORY, this.credential) .setApplicationName("Spring Vault/" + getClass().getName()).build(); try { @@ -134,9 +129,8 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport SignJwtRequest request = new SignJwtRequest(); request.setPayload(payload); - SignJwt signJwt = iam.projects().serviceAccounts().signJwt(String - .format("projects/%s/serviceAccounts/%s", projectId, serviceAccount), - request); + SignJwt signJwt = iam.projects().serviceAccounts() + .signJwt(String.format("projects/%s/serviceAccounts/%s", projectId, serviceAccount), request); SignJwtResponse response = signJwt.execute(); @@ -148,15 +142,14 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport } private String getServiceAccountId() { - return options.getServiceAccountIdAccessor().getServiceAccountId(credential); + return this.options.getServiceAccountIdAccessor().getServiceAccountId(this.credential); } private String getProjectId() { - return options.getProjectIdAccessor().getProjectId(credential); + return this.options.getProjectIdAccessor().getProjectId(this.credential); } - private static Map getJwtPayload(GcpIamAuthenticationOptions options, - String serviceAccount) { + private static Map getJwtPayload(GcpIamAuthenticationOptions options, String serviceAccount) { Instant validUntil = options.getClock().instant().plus(options.getJwtValidity()); @@ -168,4 +161,5 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport return payload; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthenticationOptions.java index a88a53a7..049402f7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpIamAuthenticationOptions.java @@ -75,9 +75,8 @@ public class GcpIamAuthenticationOptions { */ private final GcpProjectIdAccessor projectIdAccessor; - private GcpIamAuthenticationOptions(String path, - GcpCredentialSupplier credentialSupplier, String role, Duration jwtValidity, - Clock clock, GcpServiceAccountIdAccessor serviceAccountIdSupplier, + private GcpIamAuthenticationOptions(String path, GcpCredentialSupplier credentialSupplier, String role, + Duration jwtValidity, Clock clock, GcpServiceAccountIdAccessor serviceAccountIdSupplier, GcpProjectIdAccessor projectIdAccessor) { this.path = path; @@ -100,35 +99,35 @@ public class GcpIamAuthenticationOptions { * @return the path of the gcp authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return the gcp {@link Credential} supplier. */ public GcpCredentialSupplier getCredentialSupplier() { - return credentialSupplier; + return this.credentialSupplier; } /** * @return name of the role against which the login is being attempted. */ public String getRole() { - return role; + return this.role; } /** * @return {@link Duration} of the JWT to generate. */ public Duration getJwtValidity() { - return jwtValidity; + return this.jwtValidity; } /** * @return {@link Clock} used to calculate epoch seconds until the JWT expires. */ public Clock getClock() { - return clock; + return this.clock; } /** @@ -136,7 +135,7 @@ public class GcpIamAuthenticationOptions { * @since 2.1 */ public GcpServiceAccountIdAccessor getServiceAccountIdAccessor() { - return serviceAccountIdAccessor; + return this.serviceAccountIdAccessor; } /** @@ -144,7 +143,7 @@ public class GcpIamAuthenticationOptions { * @since 2.1 */ public GcpProjectIdAccessor getProjectIdAccessor() { - return projectIdAccessor; + return this.projectIdAccessor; } /** @@ -173,7 +172,6 @@ public class GcpIamAuthenticationOptions { /** * Configure the mount path, defaults to {@literal aws}. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. */ @@ -189,13 +187,11 @@ public class GcpIamAuthenticationOptions { * Configure static Google credentials, required to create a signed JWT. Either * use static credentials or provide a * {@link #credentialSupplier(GcpCredentialSupplier) credentials provider}. - * * @param credential must not be {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @see #credentialSupplier(GcpCredentialSupplier) */ - public GcpIamAuthenticationOptionsBuilder credential( - GoogleCredential credential) { + public GcpIamAuthenticationOptionsBuilder credential(GoogleCredential credential) { Assert.notNull(credential, "Credential must not be null"); @@ -206,13 +202,11 @@ public class GcpIamAuthenticationOptions { * Configure a {@link GcpCredentialSupplier}, required to create a signed JWT. * Alternatively, configure static {@link #credential(GoogleCredential) * credentials}. - * * @param credentialSupplier must not be {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @see #credential(GoogleCredential) */ - public GcpIamAuthenticationOptionsBuilder credentialSupplier( - GcpCredentialSupplier credentialSupplier) { + public GcpIamAuthenticationOptionsBuilder credentialSupplier(GcpCredentialSupplier credentialSupplier) { Assert.notNull(credentialSupplier, "GcpCredentialSupplier must not be null"); @@ -223,25 +217,21 @@ public class GcpIamAuthenticationOptions { /** * Configure an explicit service account id to use in GCP IAM calls. If none is * configured, falls back to using {@link GoogleCredential#getServiceAccountId()}. - * * @param serviceAccountId the service account id (email) to use * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @since 2.1 */ - public GcpIamAuthenticationOptionsBuilder serviceAccountId( - String serviceAccountId) { + public GcpIamAuthenticationOptionsBuilder serviceAccountId(String serviceAccountId) { Assert.notNull(serviceAccountId, "Service account id may not be null"); - return serviceAccountIdAccessor( - (GoogleCredential credential) -> serviceAccountId); + return serviceAccountIdAccessor((GoogleCredential credential) -> serviceAccountId); } /** * Configure an {@link GcpServiceAccountIdAccessor} to obtain the service account * id used in GCP IAM calls. If none is configured, falls back to using * {@link GoogleCredential#getServiceAccountId()}. - * * @param serviceAccountIdAccessor the service account id provider to use * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @see GcpServiceAccountIdAccessor @@ -250,8 +240,7 @@ public class GcpIamAuthenticationOptions { GcpIamAuthenticationOptionsBuilder serviceAccountIdAccessor( GcpServiceAccountIdAccessor serviceAccountIdAccessor) { - Assert.notNull(serviceAccountIdAccessor, - "GcpServiceAccountIdAccessor must not be null"); + Assert.notNull(serviceAccountIdAccessor, "GcpServiceAccountIdAccessor must not be null"); this.serviceAccountIdAccessor = serviceAccountIdAccessor; return this; @@ -261,7 +250,6 @@ public class GcpIamAuthenticationOptions { * Configure an explicit GCP project id to use in GCP IAM API calls. If none is * configured, falls back using * {@link GoogleCredential#getServiceAccountProjectId()}. - * * @param projectId the GCP project id to use in GCP IAM API calls * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @since 2.1 @@ -277,14 +265,12 @@ public class GcpIamAuthenticationOptions { * Configure an {@link GcpProjectIdAccessor} to use in GCP IAM API calls. If none * is configured, falls back using * {@link GoogleCredential#getServiceAccountProjectId()}. - * * @param projectIdAccessor the GCP project id supplier to use in GCP IAM API - * calls + * calls * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. * @since 2.1 */ - GcpIamAuthenticationOptionsBuilder projectIdAccessor( - GcpProjectIdAccessor projectIdAccessor) { + GcpIamAuthenticationOptionsBuilder projectIdAccessor(GcpProjectIdAccessor projectIdAccessor) { Assert.notNull(projectIdAccessor, "GcpProjectIdAccessor must not be null"); @@ -294,7 +280,6 @@ public class GcpIamAuthenticationOptions { /** * Configure the name of the role against which the login is being attempted. - * * @param role must not be empty or {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. */ @@ -309,13 +294,12 @@ public class GcpIamAuthenticationOptions { /** * Configure the {@link Duration} for the JWT expiration. This defaults to 15 * minutes and cannot be more than a hour. - * * @param jwtValidity must not be {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. */ public GcpIamAuthenticationOptionsBuilder jwtValidity(Duration jwtValidity) { - Assert.hasText(role, "JWT validity duration must not be null"); + Assert.hasText(this.role, "JWT validity duration must not be null"); this.jwtValidity = jwtValidity; return this; @@ -324,13 +308,12 @@ public class GcpIamAuthenticationOptions { /** * Configure the {@link Clock} used to calculate epoch seconds until the JWT * expiration. - * * @param clock must not be {@literal null}. * @return {@code this} {@link GcpIamAuthenticationOptionsBuilder}. */ public GcpIamAuthenticationOptionsBuilder clock(Clock clock) { - Assert.hasText(role, "Clock must not be null"); + Assert.hasText(this.role, "Clock must not be null"); this.clock = clock; return this; @@ -338,16 +321,17 @@ public class GcpIamAuthenticationOptions { /** * Build a new {@link GcpIamAuthenticationOptions} instance. - * * @return a new {@link GcpIamAuthenticationOptions}. */ public GcpIamAuthenticationOptions build() { - Assert.notNull(credentialSupplier, "GcpCredentialSupplier must not be null"); - Assert.notNull(role, "Role must not be null"); + Assert.notNull(this.credentialSupplier, "GcpCredentialSupplier must not be null"); + Assert.notNull(this.role, "Role must not be null"); - return new GcpIamAuthenticationOptions(path, credentialSupplier, role, - jwtValidity, clock, serviceAccountIdAccessor, projectIdAccessor); + return new GcpIamAuthenticationOptions(this.path, this.credentialSupplier, this.role, this.jwtValidity, + this.clock, this.serviceAccountIdAccessor, this.projectIdAccessor); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpJwtAuthenticationSupport.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpJwtAuthenticationSupport.java index 6d62c2a5..0a11678f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpJwtAuthenticationSupport.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpJwtAuthenticationSupport.java @@ -35,8 +35,7 @@ import org.springframework.web.client.RestOperations; */ public abstract class GcpJwtAuthenticationSupport { - private static final Log logger = LogFactory - .getLog(GcpJwtAuthenticationSupport.class); + private static final Log logger = LogFactory.getLog(GcpJwtAuthenticationSupport.class); private final RestOperations restOperations; @@ -49,39 +48,33 @@ public abstract class GcpJwtAuthenticationSupport { /** * Perform the actual Vault login given {@code signedJwt}. - * * @param authenticationName authentication name for logging. * @param signedJwt the JSON web token. * @param path GCP authentication mount path. * @param role Vault role. * @return the {@link VaultToken}. */ - VaultToken doLogin(String authenticationName, String signedJwt, String path, - String role) { + VaultToken doLogin(String authenticationName, String signedJwt, String path, String role) { Map login = createRequestBody(role, signedJwt); try { - VaultResponse response = this.restOperations.postForObject( - AuthenticationUtil.getLoginPath(path), login, VaultResponse.class); + VaultResponse response = this.restOperations.postForObject(AuthenticationUtil.getLoginPath(path), login, + VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); if (logger.isDebugEnabled()) { if (response.getAuth().get("metadata") instanceof Map) { - Map metadata = (Map) response - .getAuth().get("metadata"); - logger.debug(String.format( - "Login successful using %s authentication for user id %s", + Map metadata = (Map) response.getAuth().get("metadata"); + logger.debug(String.format("Login successful using %s authentication for user id %s", authenticationName, metadata.get("service_account_email"))); } else { - logger.debug("Login successful using " + authenticationName - + " authentication"); + logger.debug("Login successful using " + authenticationName + " authentication"); } } @@ -101,4 +94,5 @@ public abstract class GcpJwtAuthenticationSupport { return login; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpProjectIdAccessor.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpProjectIdAccessor.java index 68f7b07e..5b80110b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpProjectIdAccessor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpProjectIdAccessor.java @@ -31,9 +31,9 @@ public interface GcpProjectIdAccessor { /** * Get a the GCP project id to used in Google Cloud IAM API calls. - * * @param credential the credential object to obtain the project id from. * @return the service account id to use. */ String getProjectId(GoogleCredential credential); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpServiceAccountIdAccessor.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpServiceAccountIdAccessor.java index 50289b84..789a4648 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpServiceAccountIdAccessor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/GcpServiceAccountIdAccessor.java @@ -30,9 +30,9 @@ public interface GcpServiceAccountIdAccessor { /** * Get a the service account id (email) to be placed in the signed JWT. - * * @param credential credential object to obtain the service account id from. * @return the service account id to use. */ String getServiceAccountId(GoogleCredential credential); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java index b937e3ad..516cb538 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java @@ -37,4 +37,5 @@ public class IpAddressUserId implements AppIdUserIdMechanism { throw new IllegalStateException(e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthentication.java index eed8df2d..184623df 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthentication.java @@ -42,8 +42,7 @@ import org.springframework.web.client.RestOperations; * @see Auth Backend: * Kubernetes */ -public class KubernetesAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class KubernetesAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(KubernetesAuthentication.class); @@ -54,12 +53,10 @@ public class KubernetesAuthentication /** * Create a {@link KubernetesAuthentication} using * {@link KubernetesAuthenticationOptions} and {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public KubernetesAuthentication(KubernetesAuthenticationOptions options, - RestOperations restOperations) { + public KubernetesAuthentication(KubernetesAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "KubernetesAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -71,33 +68,28 @@ public class KubernetesAuthentication /** * Creates a {@link AuthenticationSteps} for kubernetes authentication given * {@link KubernetesAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for kubernetes authentication. */ - public static AuthenticationSteps createAuthenticationSteps( - KubernetesAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(KubernetesAuthenticationOptions options) { Assert.notNull(options, "KubernetesAuthenticationOptions must not be null"); String token = options.getJwtSupplier().get(); - return AuthenticationSteps - .fromSupplier(() -> getKubernetesLogin(options.getRole(), token)) + return AuthenticationSteps.fromSupplier(() -> getKubernetesLogin(options.getRole(), token)) .login(AuthenticationUtil.getLoginPath(options.getPath())); } @Override public VaultToken login() throws VaultException { - Map login = getKubernetesLogin(options.getRole(), - options.getJwtSupplier().get()); + Map login = getKubernetesLogin(this.options.getRole(), this.options.getJwtSupplier().get()); try { - VaultResponse response = restOperations.postForObject(AuthenticationUtil.getLoginPath(options.getPath()), - login, VaultResponse.class); + VaultResponse response = this.restOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using Kubernetes authentication"); @@ -125,4 +117,5 @@ public class KubernetesAuthentication return login; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthenticationOptions.java index 5cb890cb..0e30205e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesAuthenticationOptions.java @@ -57,8 +57,7 @@ public class KubernetesAuthenticationOptions { */ private final Supplier jwtSupplier; - private KubernetesAuthenticationOptions(String path, String role, - Supplier jwtSupplier) { + private KubernetesAuthenticationOptions(String path, String role, Supplier jwtSupplier) { this.path = path; this.role = role; @@ -76,21 +75,21 @@ public class KubernetesAuthenticationOptions { * @return the path of the kubernetes authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return name of the role against which the login is being attempted. */ public String getRole() { - return role; + return this.role; } /** * @return JSON Web Token supplier. */ public Supplier getJwtSupplier() { - return jwtSupplier; + return this.jwtSupplier; } /** @@ -108,7 +107,6 @@ public class KubernetesAuthenticationOptions { /** * Configure the mount path. - * * @param path must not be {@literal null} or empty. * @return {@code this} {@link KubernetesAuthenticationOptionsBuilder}. */ @@ -122,9 +120,8 @@ public class KubernetesAuthenticationOptions { /** * Configure the role. - * * @param role name of the role against which the login is being attempted, must - * not be {@literal null} or empty. + * not be {@literal null} or empty. * @return {@code this} {@link KubernetesAuthenticationOptionsBuilder}. */ public KubernetesAuthenticationOptionsBuilder role(String role) { @@ -137,13 +134,11 @@ public class KubernetesAuthenticationOptions { /** * Configure the {@link Supplier} to obtain a Kubernetes authentication token. - * * @param jwtSupplier the supplier, must not be {@literal null}. * @return {@code this} {@link KubernetesAuthenticationOptionsBuilder}. * @see KubernetesJwtSupplier */ - public KubernetesAuthenticationOptionsBuilder jwtSupplier( - Supplier jwtSupplier) { + public KubernetesAuthenticationOptionsBuilder jwtSupplier(Supplier jwtSupplier) { Assert.notNull(jwtSupplier, "JwtSupplier must not be null"); @@ -153,16 +148,16 @@ public class KubernetesAuthenticationOptions { /** * Build a new {@link KubernetesAuthenticationOptions} instance. - * * @return a new {@link KubernetesAuthenticationOptions}. */ public KubernetesAuthenticationOptions build() { - Assert.notNull(role, "Role must not be null"); + Assert.notNull(this.role, "Role must not be null"); - return new KubernetesAuthenticationOptions(path, role, - jwtSupplier == null ? new KubernetesServiceAccountTokenFile().cached() - : jwtSupplier); + return new KubernetesAuthenticationOptions(this.path, this.role, + this.jwtSupplier == null ? new KubernetesServiceAccountTokenFile().cached() : this.jwtSupplier); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesServiceAccountTokenFile.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesServiceAccountTokenFile.java index 91912870..c38975e9 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesServiceAccountTokenFile.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/KubernetesServiceAccountTokenFile.java @@ -31,8 +31,7 @@ import org.springframework.core.io.Resource; * @since 2.0 * @see KubernetesJwtSupplier */ -public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplier - implements KubernetesJwtSupplier { +public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplier implements KubernetesJwtSupplier { /** * Default path to the service account token file. @@ -43,9 +42,8 @@ public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplie * Create a new {@link KubernetesServiceAccountTokenFile} pointing to the * {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE}. Construction fails with an * exception if the file does not exist. - * * @throws IllegalArgumentException if the - * {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE} does not exist. + * {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE} does not exist. */ public KubernetesServiceAccountTokenFile() { this(DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE); @@ -54,7 +52,6 @@ public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplie /** * Create a new {@link KubernetesServiceAccountTokenFile} * {@link KubernetesServiceAccountTokenFile} from a {@code path}. - * * @param path path to the service account token file. * @throws IllegalArgumentException if the{@code path} does not exist. */ @@ -65,7 +62,6 @@ public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplie /** * Create a new {@link KubernetesServiceAccountTokenFile} * {@link KubernetesServiceAccountTokenFile} from a {@link File} handle. - * * @param file path to the service account token file. * @throws IllegalArgumentException if the{@code path} does not exist. */ @@ -76,11 +72,11 @@ public class KubernetesServiceAccountTokenFile extends ResourceCredentialSupplie /** * Create a new {@link KubernetesServiceAccountTokenFile} * {@link KubernetesServiceAccountTokenFile} from a {@link Resource} handle. - * * @param resource resource pointing to the service account token file. * @throws IllegalArgumentException if the{@code path} does not exist. */ public KubernetesServiceAccountTokenFile(Resource resource) { super(resource); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java index 6ad54081..e1a8c06e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java @@ -102,14 +102,13 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu /** * Create a {@link LifecycleAwareSessionManager} given {@link ClientAuthentication}, * {@link TaskScheduler} and {@link RestOperations}. - * * @param clientAuthentication must not be {@literal null}. * @param taskScheduler must not be {@literal null}. * @param restOperations must not be {@literal null}. * @since 1.0.1 */ - public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication, - TaskScheduler taskScheduler, RestOperations restOperations) { + public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication, TaskScheduler taskScheduler, + RestOperations restOperations) { super(taskScheduler); @@ -124,16 +123,14 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu /** * Create a {@link LifecycleAwareSessionManager} given {@link ClientAuthentication}, * {@link TaskScheduler} and {@link RestOperations}. - * * @param clientAuthentication must not be {@literal null}. * @param taskScheduler must not be {@literal null}. * @param restOperations must not be {@literal null}. * @param refreshTrigger must not be {@literal null}. * @since 1.0.1 */ - public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication, - TaskScheduler taskScheduler, RestOperations restOperations, - RefreshTrigger refreshTrigger) { + public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication, TaskScheduler taskScheduler, + RestOperations restOperations, RefreshTrigger refreshTrigger) { super(taskScheduler, refreshTrigger); @@ -151,7 +148,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu * session. */ protected Optional getToken() { - return token; + return this.token; } protected void setToken(Optional token) { @@ -164,25 +161,23 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu Optional token = getToken(); setToken(Optional.empty()); - token.filter(TokenWrapper::isRevocable).map(TokenWrapper::getToken) - .ifPresent(this::revoke); + token.filter(TokenWrapper::isRevocable).map(TokenWrapper::getToken).ifPresent(this::revoke); } /** * Revoke a {@link VaultToken}. - * * @param token the token to revoke, must not be {@literal null}. */ protected void revoke(VaultToken token) { try { dispatch(new BeforeLoginTokenRevocationEvent(token)); - restOperations.postForObject("auth/token/revoke-self", - new HttpEntity<>(VaultHttpHeaders.from(token)), Map.class); + this.restOperations.postForObject("auth/token/revoke-self", new HttpEntity<>(VaultHttpHeaders.from(token)), + Map.class); dispatch(new AfterLoginTokenRevocationEvent(token)); } catch (RuntimeException e) { - logger.warn("Cannot revoke VaultToken: %s", e); + this.logger.warn("Cannot revoke VaultToken: %s", e); dispatch(new LoginTokenRevocationFailedEvent(token, e)); } } @@ -192,13 +187,12 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu * token was obtained before, it uses self-renewal to renew the current token. * Client-side errors (like permission denied) indicate the token cannot be renewed * because it's expired or simply not found. - * * @return {@literal true} if the refresh was successful. {@literal false} if a new * token was obtained or refresh failed. */ public boolean renewToken() { - logger.info("Renewing token"); + this.logger.info("Renewing token"); Optional token = getToken(); if (!token.isPresent()) { @@ -212,22 +206,20 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu } catch (RuntimeException e) { - VaultTokenRenewalException exception = new VaultTokenRenewalException( - format("Cannot renew token", e), e); + VaultTokenRenewalException exception = new VaultTokenRenewalException(format("Cannot renew token", e), e); if (getLeaseStrategy().shouldDrop(exception)) { setToken(Optional.empty()); } - if (logger.isDebugEnabled()) { - logger.debug(exception.getMessage(), exception); + if (this.logger.isDebugEnabled()) { + this.logger.debug(exception.getMessage(), exception); } else { - logger.warn(exception.getMessage()); + this.logger.warn(exception.getMessage()); } - dispatch( - new LoginTokenRenewalFailedEvent(tokenWrapper.getToken(), exception)); + dispatch(new LoginTokenRenewalFailedEvent(tokenWrapper.getToken(), exception)); return false; } } @@ -235,24 +227,20 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu private boolean doRenew(TokenWrapper wrapper) { dispatch(new BeforeLoginTokenRenewedEvent(wrapper.getToken())); - VaultResponse vaultResponse = restOperations.postForObject( - "auth/token/renew-self", - new HttpEntity<>(VaultHttpHeaders.from(wrapper.token)), - VaultResponse.class); + VaultResponse vaultResponse = this.restOperations.postForObject("auth/token/renew-self", + new HttpEntity<>(VaultHttpHeaders.from(wrapper.token)), VaultResponse.class); LoginToken renewed = LoginTokenUtil.from(vaultResponse.getRequiredAuth()); if (isExpired(renewed)) { - if (logger.isDebugEnabled()) { - Duration validTtlThreshold = getRefreshTrigger() - .getValidTtlThreshold(renewed); - logger.info(String.format( - "Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.", + if (this.logger.isDebugEnabled()) { + Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed); + this.logger.info(String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.", renewed.getLeaseDuration(), validTtlThreshold)); } else { - logger.info("Token TTL exceeded validity TTL threshold. Dropping token."); + this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token."); } setToken(Optional.empty()); @@ -271,7 +259,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu if (!getToken().isPresent()) { - synchronized (lock) { + synchronized (this.lock) { if (!getToken().isPresent()) { doGetSessionToken(); @@ -288,25 +276,22 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu VaultToken token; try { - token = clientAuthentication.login(); + token = this.clientAuthentication.login(); } catch (VaultException e) { - dispatch(new LoginFailedEvent(clientAuthentication, e)); + dispatch(new LoginFailedEvent(this.clientAuthentication, e)); throw e; } TokenWrapper wrapper = new TokenWrapper(token, token instanceof LoginToken); - if (isTokenSelfLookupEnabled() - && !ClassUtils.isAssignableValue(LoginToken.class, token)) { + if (isTokenSelfLookupEnabled() && !ClassUtils.isAssignableValue(LoginToken.class, token)) { try { - token = LoginTokenAdapter.augmentWithSelfLookup(this.restOperations, - token); + token = LoginTokenAdapter.augmentWithSelfLookup(this.restOperations, token); wrapper = new TokenWrapper(token, false); } catch (VaultTokenLookupException e) { - logger.warn(String.format("Cannot enhance VaultToken to a LoginToken: %s", - e.getMessage())); + this.logger.warn(String.format("Cannot enhance VaultToken to a LoginToken: %s", e.getMessage())); dispatch(new AuthenticationErrorEvent(token, e)); } } @@ -320,7 +305,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu } protected VaultToken login() { - return clientAuthentication.login(); + return this.clientAuthentication.login(); } /** @@ -333,14 +318,13 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu .filter(it -> { LoginToken loginToken = (LoginToken) it; - return !loginToken.getLeaseDuration().isZero() - && loginToken.isRenewable(); + return !loginToken.getLeaseDuration().isZero() && loginToken.isRenewable(); }).isPresent(); } private void scheduleRenewal() { - logger.info("Scheduling Token renewal"); + this.logger.info("Scheduling Token renewal"); Runnable task = () -> { Optional tokenWrapper = getToken(); @@ -359,21 +343,19 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu } } catch (Exception e) { - logger.error("Cannot renew VaultToken", e); + this.logger.error("Cannot renew VaultToken", e); dispatch(new LoginTokenRenewalFailedEvent(token, e)); } }; Optional token = getToken(); - token.ifPresent(tokenWrapper -> getTaskScheduler().schedule(task, - createTrigger(tokenWrapper))); + token.ifPresent(tokenWrapper -> getTaskScheduler().schedule(task, createTrigger(tokenWrapper))); } private OneShotTrigger createTrigger(TokenWrapper tokenWrapper) { - return new OneShotTrigger(getRefreshTrigger() - .nextExecutionTime((LoginToken) tokenWrapper.getToken())); + return new OneShotTrigger(getRefreshTrigger().nextExecutionTime((LoginToken) tokenWrapper.getToken())); } private static String format(String message, RuntimeException e) { @@ -381,8 +363,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu if (e instanceof HttpStatusCodeException) { HttpStatusCodeException hsce = (HttpStatusCodeException) e; - return String.format("%s: Status %s %s %s", message, hsce.getRawStatusCode(), - hsce.getStatusText(), + return String.format("%s: Status %s %s %s", message, hsce.getRawStatusCode(), hsce.getStatusText(), VaultResponses.getError(hsce.getResponseBodyAsString())); } @@ -398,6 +379,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu protected static class TokenWrapper { private final VaultToken token; + private final boolean revocable; TokenWrapper(VaultToken token, boolean revocable) { @@ -412,5 +394,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu public boolean isRevocable() { return this.revocable; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupport.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupport.java index eb81fdd5..4661fdb8 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupport.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupport.java @@ -41,16 +41,15 @@ import org.springframework.vault.support.VaultToken; * @author Mark Paluch * @since 2.0 */ -public abstract class LifecycleAwareSessionManagerSupport - extends AuthenticationEventPublisher { +public abstract class LifecycleAwareSessionManagerSupport extends AuthenticationEventPublisher { /** * Refresh 5 seconds before the token expires. */ public static final int REFRESH_PERIOD_BEFORE_EXPIRY = 5; - private static final RefreshTrigger DEFAULT_TRIGGER = new FixedTimeoutRefreshTrigger( - REFRESH_PERIOD_BEFORE_EXPIRY, TimeUnit.SECONDS); + private static final RefreshTrigger DEFAULT_TRIGGER = new FixedTimeoutRefreshTrigger(REFRESH_PERIOD_BEFORE_EXPIRY, + TimeUnit.SECONDS); /** * Logger available to subclasses. @@ -81,7 +80,6 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Create a {@link LifecycleAwareSessionManager} given {@link TaskScheduler}. Using * {@link #DEFAULT_TRIGGER} to trigger refresh. - * * @param taskScheduler must not be {@literal null}. */ public LifecycleAwareSessionManagerSupport(TaskScheduler taskScheduler) { @@ -91,12 +89,10 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Create a {@link LifecycleAwareSessionManager} given {@link TaskScheduler} and * {@link RefreshTrigger}. - * * @param taskScheduler must not be {@literal null}. * @param refreshTrigger must not be {@literal null}. */ - public LifecycleAwareSessionManagerSupport(TaskScheduler taskScheduler, - RefreshTrigger refreshTrigger) { + public LifecycleAwareSessionManagerSupport(TaskScheduler taskScheduler, RefreshTrigger refreshTrigger) { Assert.notNull(taskScheduler, "TaskScheduler must not be null"); Assert.notNull(refreshTrigger, "RefreshTrigger must not be null"); @@ -114,21 +110,19 @@ public abstract class LifecycleAwareSessionManagerSupport * Self-lookup for tokens without a permission to access * {@code auth/token/lookup-self} will fail gracefully and continue without token * renewal. - * * @return {@literal true} to enable self-lookup, {@literal false} to disable * self-lookup. Enabled by default. */ protected boolean isTokenSelfLookupEnabled() { - return tokenSelfLookupEnabled; + return this.tokenSelfLookupEnabled; } /** * Enables/disables token self-lookup. Self-lookup augments {@link VaultToken} * obtained from a {@link ClientAuthentication}. Self-lookup determines whether a * token is renewable and its TTL. - * * @param tokenSelfLookupEnabled {@literal true} to enable self-lookup, - * {@literal false} to disable self-lookup. Enabled by default. + * {@literal false} to disable self-lookup. Enabled by default. */ public void setTokenSelfLookupEnabled(boolean tokenSelfLookupEnabled) { this.tokenSelfLookupEnabled = tokenSelfLookupEnabled; @@ -136,7 +130,6 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Set the {@link LeaseStrategy} for lease renewal error handling. - * * @param leaseStrategy the {@link LeaseStrategy}, must not be {@literal null}. * @since 2.2 */ @@ -147,28 +140,27 @@ public abstract class LifecycleAwareSessionManagerSupport } LeaseStrategy getLeaseStrategy() { - return leaseStrategy; + return this.leaseStrategy; } /** * @return the underlying {@link TaskScheduler}. */ protected TaskScheduler getTaskScheduler() { - return taskScheduler; + return this.taskScheduler; } /** * @return the underlying {@link RefreshTrigger}. */ protected RefreshTrigger getRefreshTrigger() { - return refreshTrigger; + return this.refreshTrigger; } /** * Check whether the Token falls below its * {@link RefreshTrigger#getValidTtlThreshold(LoginToken) validity threshold}. * Typically used to discard a token. - * * @param loginToken must not be {@literal null}. * @return {@literal true} if token validity falls below validity threshold, * {@literal false} if still valid. @@ -196,12 +188,13 @@ public abstract class LifecycleAwareSessionManagerSupport @Nullable public Date nextExecutionTime(TriggerContext triggerContext) { - if (fired.compareAndSet(false, true)) { - return nextExecutionTime; + if (this.fired.compareAndSet(false, true)) { + return this.nextExecutionTime; } return null; } + } /** @@ -212,7 +205,6 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Determine the next execution time according to the given trigger context. - * * @param loginToken login token encapsulating renewability and lease duration. * @return the next execution time as defined by the trigger, or {@code null} if * the trigger won't fire anymore @@ -222,12 +214,12 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Returns the minimum TTL duration to consider a token valid after renewal. * Tokens with a shorter TTL are revoked and considered expired. - * * @param loginToken the login token after renewal. * @return minimum TTL {@link Duration} to consider a token valid. * @since 2.0 */ Duration getValidTtlThreshold(LoginToken loginToken); + } /** @@ -242,19 +234,18 @@ public abstract class LifecycleAwareSessionManagerSupport private static final Duration ONE_SECOND = Duration.ofSeconds(1); private final Duration duration; + private final Duration validTtlThreshold; /** * Create a new {@link FixedTimeoutRefreshTrigger} to calculate execution times of * {@code timeout} before the {@link LoginToken} expires - * * @param timeout timeout value, non-negative long value. * @param timeUnit must not be {@literal null}. */ public FixedTimeoutRefreshTrigger(long timeout, TimeUnit timeUnit) { - Assert.isTrue(timeout >= 0, - "Timeout duration must be greater or equal to zero"); + Assert.isTrue(timeout >= 0, "Timeout duration must be greater or equal to zero"); Assert.notNull(timeUnit, "TimeUnit must not be null"); this.duration = Duration.ofMillis(timeUnit.toMillis(timeout)); @@ -265,7 +256,6 @@ public abstract class LifecycleAwareSessionManagerSupport * Create a new {@link FixedTimeoutRefreshTrigger} to calculate execution times of * {@code timeout} before the {@link LoginToken} expires. Valid TTL threshold is * set to two seconds longer to compensate for timing issues during scheduling. - * * @param timeout timeout value. * @since 2.0 */ @@ -276,17 +266,15 @@ public abstract class LifecycleAwareSessionManagerSupport /** * Create a new {@link FixedTimeoutRefreshTrigger} to calculate execution times of * {@code timeout} before the {@link LoginToken} expires. - * * @param timeout timeout value. * @param validTtlThreshold minimum TTL duration to consider a Token as valid. - * Tokens with a shorter TTL are not used anymore. Should be greater than - * {@code timeout} to prevent token expiry. + * Tokens with a shorter TTL are not used anymore. Should be greater than + * {@code timeout} to prevent token expiry. * @since 2.0 */ public FixedTimeoutRefreshTrigger(Duration timeout, Duration validTtlThreshold) { - Assert.isTrue(timeout.toMillis() >= 0, - "Timeout duration must be greater or equal to zero"); + Assert.isTrue(timeout.toMillis() >= 0, "Timeout duration must be greater or equal to zero"); Assert.notNull(validTtlThreshold, "Valid TTL threshold must not be null"); @@ -298,14 +286,16 @@ public abstract class LifecycleAwareSessionManagerSupport public Date nextExecutionTime(LoginToken loginToken) { long milliseconds = Math.max(ONE_SECOND.toMillis(), - loginToken.getLeaseDuration().toMillis() - duration.toMillis()); + loginToken.getLeaseDuration().toMillis() - this.duration.toMillis()); return new Date(System.currentTimeMillis() + milliseconds); } @Override public Duration getValidTtlThreshold(LoginToken loginToken) { - return validTtlThreshold; + return this.validTtlThreshold; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java index c3d91e33..46777f4b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java @@ -44,7 +44,6 @@ public class LoginToken extends VaultToken { /** * Create a new {@link LoginToken}. - * * @param token must not be {@literal null}. * @return the created {@link VaultToken} */ @@ -57,7 +56,6 @@ public class LoginToken extends VaultToken { /** * Create a new {@link LoginToken}. - * * @param token must not be {@literal null}. * @return the created {@link VaultToken} * @since 1.1 @@ -68,7 +66,6 @@ public class LoginToken extends VaultToken { /** * Create a new {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDurationSeconds the lease duration in seconds, must not be negative. * @return the created {@link VaultToken} @@ -85,7 +82,6 @@ public class LoginToken extends VaultToken { /** * Create a new {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDurationSeconds the lease duration in seconds, must not be negative. * @return the created {@link VaultToken} @@ -104,11 +100,9 @@ public class LoginToken extends VaultToken { /** * Create a new {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. - * * @param leaseDuration the lease duration, must not be negative and not be - * {@literal null}. + * {@literal null}. * @return the created {@link VaultToken} * @since 2.0 */ @@ -124,7 +118,6 @@ public class LoginToken extends VaultToken { /** * Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDurationSeconds the lease duration in seconds, must not be negative. * @return the created {@link VaultToken} @@ -142,7 +135,6 @@ public class LoginToken extends VaultToken { /** * Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDurationSeconds the lease duration in seconds, must not be negative. * @return the created {@link VaultToken} @@ -162,7 +154,6 @@ public class LoginToken extends VaultToken { /** * Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDuration the lease duration, must not be {@literal null} or negative. * @return the created {@link VaultToken} @@ -177,7 +168,6 @@ public class LoginToken extends VaultToken { /** * Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}. - * * @param token must not be {@literal null}. * @param leaseDuration the lease duration, must not be {@literal null} or negative. * @return the created {@link VaultToken} @@ -197,23 +187,24 @@ public class LoginToken extends VaultToken { * @return the lease duration in seconds. May be {@literal 0} if none. */ public Duration getLeaseDuration() { - return leaseDuration; + return this.leaseDuration; } /** * @return {@literal true} if this token is renewable; {@literal false} otherwise. */ public boolean isRenewable() { - return renewable; + return this.renewable; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [renewable=").append(renewable); - sb.append(", leaseDuration=").append(leaseDuration); + sb.append(" [renewable=").append(this.renewable); + sb.append(", leaseDuration=").append(this.leaseDuration); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenAdapter.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenAdapter.java index 2bcd41f2..76d19f9c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenAdapter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenAdapter.java @@ -52,12 +52,10 @@ public class LoginTokenAdapter implements ClientAuthentication { /** * Create a new {@link LoginTokenAdapter} given {@link ClientAuthentication} to * decorate and {@link RestOperations}. - * * @param delegate must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public LoginTokenAdapter(ClientAuthentication delegate, - RestOperations restOperations) { + public LoginTokenAdapter(ClientAuthentication delegate, RestOperations restOperations) { Assert.notNull(delegate, "ClientAuthentication delegate must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -68,15 +66,14 @@ public class LoginTokenAdapter implements ClientAuthentication { @Override public LoginToken login() throws VaultException { - return augmentWithSelfLookup(delegate.login()); + return augmentWithSelfLookup(this.delegate.login()); } private LoginToken augmentWithSelfLookup(VaultToken token) { return augmentWithSelfLookup(this.restOperations, token); } - static LoginToken augmentWithSelfLookup(RestOperations restOperations, - VaultToken token) { + static LoginToken augmentWithSelfLookup(RestOperations restOperations, VaultToken token) { Map data = lookupSelf(restOperations, token); @@ -90,23 +87,19 @@ public class LoginTokenAdapter implements ClientAuthentication { return LoginToken.of(token.toCharArray(), getLeaseDuration(ttl)); } - private static Map lookupSelf(RestOperations restOperations, - VaultToken token) { + private static Map lookupSelf(RestOperations restOperations, VaultToken token) { try { - ResponseEntity entity = restOperations.exchange( - "auth/token/lookup-self", HttpMethod.GET, + ResponseEntity entity = restOperations.exchange("auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>(VaultHttpHeaders.from(token)), VaultResponse.class); - Assert.state(entity.getBody() != null && entity.getBody().getData() != null, - "Token response is null"); + Assert.state(entity.getBody() != null && entity.getBody().getData() != null, "Token response is null"); return entity.getBody().getData(); } catch (HttpStatusCodeException e) { - throw new VaultTokenLookupException( - String.format("Token self-lookup failed: %s %s", e.getRawStatusCode(), - VaultResponses.getError(e.getResponseBodyAsString()))); + throw new VaultTokenLookupException(String.format("Token self-lookup failed: %s %s", e.getRawStatusCode(), + VaultResponses.getError(e.getResponseBodyAsString()))); } catch (RestClientException e) { throw new VaultTokenLookupException("Token self-lookup failed", e); @@ -116,4 +109,5 @@ public class LoginTokenAdapter implements ClientAuthentication { static Duration getLeaseDuration(@Nullable Number ttl) { return ttl == null ? Duration.ZERO : Duration.ofSeconds(ttl.longValue()); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenUtil.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenUtil.java index 1c4c79a3..b0e9624e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenUtil.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginTokenUtil.java @@ -28,13 +28,11 @@ import org.springframework.util.Assert; final class LoginTokenUtil { private LoginTokenUtil() { - throw new UnsupportedOperationException( - "This is a utility class and cannot be instantiated"); + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); } /** * Construct a {@link LoginToken} from an auth response. - * * @param auth {@link Map} holding a login response. * @return the {@link LoginToken} */ @@ -49,7 +47,6 @@ final class LoginTokenUtil { /** * Construct a {@link LoginToken} from an auth response. - * * @param auth {@link Map} holding a login response. * @return the {@link LoginToken} * @since 2.0 @@ -66,8 +63,7 @@ final class LoginTokenUtil { } if (renewable != null && renewable) { - return LoginToken.renewable(token, - Duration.ofSeconds(leaseDuration.longValue())); + return LoginToken.renewable(token, Duration.ofSeconds(leaseDuration.longValue())); } if (leaseDuration != null) { @@ -76,4 +72,5 @@ final class LoginTokenUtil { return LoginToken.of(token); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java index 1543cec8..32a512d8 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java @@ -57,13 +57,11 @@ public class MacAddressUserId implements AppIdUserIdMechanism { * Create a new {@link MacAddressUserId} using a {@code networkInterfaceIndex}. The * index is applied to {@link NetworkInterface#getNetworkInterfaces()} to obtain the * desired network interface. - * * @param networkInterfaceIndex must be greater or equal to zero. */ public MacAddressUserId(int networkInterfaceIndex) { - Assert.isTrue(networkInterfaceIndex >= 0, - "NetworkInterfaceIndex must be greater or equal to 0"); + Assert.isTrue(networkInterfaceIndex >= 0, "NetworkInterfaceIndex must be greater or equal to 0"); this.networkInterfaceHint = "" + networkInterfaceIndex; } @@ -72,7 +70,6 @@ public class MacAddressUserId implements AppIdUserIdMechanism { * Create a new {@link MacAddressUserId} using a {@code networkInterfaceName}. This * name is compared with {@link NetworkInterface#getName()} and * {@link NetworkInterface#getDisplayName()} to obtain the desired network interface. - * * @param networkInterfaceName must not be {@literal null}. */ public MacAddressUserId(String networkInterfaceName) { @@ -88,35 +85,29 @@ public class MacAddressUserId implements AppIdUserIdMechanism { try { Optional networkInterface = Optional.empty(); - List interfaces = Collections - .list(NetworkInterface.getNetworkInterfaces()); + List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); - if (StringUtils.hasText(networkInterfaceHint)) { + if (StringUtils.hasText(this.networkInterfaceHint)) { try { - networkInterface = getNetworkInterface( - Integer.parseInt(networkInterfaceHint), interfaces); + networkInterface = getNetworkInterface(Integer.parseInt(this.networkInterfaceHint), interfaces); } catch (NumberFormatException e) { - networkInterface = getNetworkInterface((networkInterfaceHint), - interfaces); + networkInterface = getNetworkInterface((this.networkInterfaceHint), interfaces); } } if (!networkInterface.isPresent()) { - if (StringUtils.hasText(networkInterfaceHint)) { - log.warn(String.format( - "Did not find a NetworkInterface applying hint %s", - networkInterfaceHint)); + if (StringUtils.hasText(this.networkInterfaceHint)) { + this.log.warn(String.format("Did not find a NetworkInterface applying hint %s", + this.networkInterfaceHint)); } InetAddress localHost = InetAddress.getLocalHost(); - networkInterface = Optional - .ofNullable(NetworkInterface.getByInetAddress(localHost)); + networkInterface = Optional.ofNullable(NetworkInterface.getByInetAddress(localHost)); - if (!networkInterface.filter(MacAddressUserId::hasNetworkAddress) - .isPresent()) { + if (!networkInterface.filter(MacAddressUserId::hasNetworkAddress).isPresent()) { networkInterface = getNetworkInterfaceWithHardwareAddress(interfaces); } } @@ -124,8 +115,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism { return networkInterface.map(MacAddressUserId::getRequiredNetworkAddress) // .map(Sha256::toHexString) // .map(Sha256::toSha256) // - .orElseThrow(() -> new IllegalStateException( - "Cannot determine NetworkInterface")); + .orElseThrow(() -> new IllegalStateException("Cannot determine NetworkInterface")); } catch (IOException e) { throw new IllegalStateException(e); @@ -133,8 +123,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism { } - private static Optional getNetworkInterface(Number hint, - List interfaces) { + private static Optional getNetworkInterface(Number hint, List interfaces) { if (interfaces.size() > hint.intValue() && hint.intValue() >= 0) { return Optional.of(interfaces.get(hint.intValue())); @@ -143,8 +132,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism { return Optional.empty(); } - private static Optional getNetworkInterface(String hint, - List interfaces) { + private static Optional getNetworkInterface(String hint, List interfaces) { return interfaces.stream() // .filter(anInterface -> matchesHint(hint, anInterface)) // @@ -153,8 +141,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism { private static boolean matchesHint(String hint, NetworkInterface networkInterface) { - return hint.equals(networkInterface.getDisplayName()) - || hint.equals(networkInterface.getName()); + return hint.equals(networkInterface.getDisplayName()) || hint.equals(networkInterface.getName()); } private static Optional getNetworkInterfaceWithHardwareAddress( @@ -172,19 +159,19 @@ public class MacAddressUserId implements AppIdUserIdMechanism { return Optional.ofNullable(it.getHardwareAddress()); } catch (SocketException e) { - throw new IllegalStateException(String - .format("Cannot determine hardware address for %s", it.getName())); + throw new IllegalStateException(String.format("Cannot determine hardware address for %s", it.getName())); } } private static byte[] getRequiredNetworkAddress(NetworkInterface it) { return getNetworkAddress(it) // - .orElseThrow(() -> new IllegalStateException(String.format( - "Network interface %s has no hardware address", it.getName()))); + .orElseThrow(() -> new IllegalStateException( + String.format("Network interface %s has no hardware address", it.getName()))); } private static boolean hasNetworkAddress(NetworkInterface it) { return getNetworkAddress(it).isPresent(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthentication.java index 61bcd94f..21462d50 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthentication.java @@ -52,13 +52,11 @@ import org.springframework.web.client.RestOperations; * @see RestOperations * @see Auth Backend: PCF */ -public class PcfAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class PcfAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(PcfAuthentication.class); - private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter - .ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); // SHA256 hash and a salt length of 222 private static final int SALT_LENGTH = 222; @@ -70,12 +68,10 @@ public class PcfAuthentication /** * Create a {@link PcfAuthentication} using {@link PcfAuthenticationOptions} and * {@link RestOperations}. - * * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ - public PcfAuthentication(PcfAuthenticationOptions options, - RestOperations restOperations) { + public PcfAuthentication(PcfAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "PcfAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); @@ -87,36 +83,31 @@ public class PcfAuthentication /** * Creates a {@link AuthenticationSteps} for pcf authentication given * {@link PcfAuthenticationOptions}. - * * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for pcf authentication. */ - public static AuthenticationSteps createAuthenticationSteps( - PcfAuthenticationOptions options) { + public static AuthenticationSteps createAuthenticationSteps(PcfAuthenticationOptions options) { Assert.notNull(options, "PcfAuthenticationOptions must not be null"); String instanceCert = options.getInstanceCertSupplier().get(); String instanceKey = options.getInstanceKeySupplier().get(); return AuthenticationSteps - .fromSupplier(() -> getPcfLogin(options.getRole(), options.getClock(), - instanceCert, instanceKey)) // + .fromSupplier(() -> getPcfLogin(options.getRole(), options.getClock(), instanceCert, instanceKey)) // .login(AuthenticationUtil.getLoginPath(options.getPath())); } @Override public VaultToken login() throws VaultException { - Map login = getPcfLogin(options.getRole(), options.getClock(), - options.getInstanceCertSupplier().get(), - options.getInstanceKeySupplier().get()); + Map login = getPcfLogin(this.options.getRole(), this.options.getClock(), + this.options.getInstanceCertSupplier().get(), this.options.getInstanceKeySupplier().get()); try { - VaultResponse response = restOperations.postForObject(AuthenticationUtil.getLoginPath(options.getPath()), - login, VaultResponse.class); + VaultResponse response = this.restOperations + .postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class); - Assert.state(response != null && response.getAuth() != null, - "Auth field must not be null"); + Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using PCF authentication"); @@ -132,8 +123,7 @@ public class PcfAuthentication return createAuthenticationSteps(this.options); } - private static Map getPcfLogin(String role, Clock clock, - String instanceCert, String instanceKey) { + private static Map getPcfLogin(String role, Clock clock, String instanceCert, String instanceKey) { Assert.hasText(role, "Role must not be empty"); @@ -160,23 +150,20 @@ public class PcfAuthentication } } - private static String getMessage(String role, String signingTime, - String instanceCertPem) { + private static String getMessage(String role, String signingTime, String instanceCertPem) { return signingTime + instanceCertPem + role; } - private static String doSign(byte[] message, String instanceKeyPem) - throws CryptoException { + private static String doSign(byte[] message, String instanceKeyPem) throws CryptoException { RSAPrivateKeySpec privateKey = PemObject.fromKey(instanceKeyPem).getRSAKeySpec(); - PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), - SALT_LENGTH); + PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH); - signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), - privateKey.getPrivateExponent())); + signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent())); signer.update(message, 0, message.length); byte[] signature = signer.generateSignature(); return Base64Utils.encodeToUrlSafeString(signature); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthenticationOptions.java index 8b4810d1..cc4822fc 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthenticationOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/PcfAuthenticationOptions.java @@ -63,8 +63,8 @@ public class PcfAuthenticationOptions { */ private final Supplier instanceKeySupplier; - private PcfAuthenticationOptions(String path, String role, Clock clock, - Supplier instanceCertSupplier, Supplier instanceKeySupplier) { + private PcfAuthenticationOptions(String path, String role, Clock clock, Supplier instanceCertSupplier, + Supplier instanceKeySupplier) { this.path = path; this.role = role; this.clock = clock; @@ -83,35 +83,35 @@ public class PcfAuthenticationOptions { * @return the path of the pcf authentication backend mount. */ public String getPath() { - return path; + return this.path; } /** * @return name of the role against which the login is being attempted. */ public String getRole() { - return role; + return this.role; } /** * @return the {@link Clock}. */ public Clock getClock() { - return clock; + return this.clock; } /** * @return the instance certificate {@link Supplier}. */ public Supplier getInstanceCertSupplier() { - return instanceCertSupplier; + return this.instanceCertSupplier; } /** * @return the instance key {@link Supplier}. */ public Supplier getInstanceKeySupplier() { - return instanceKeySupplier; + return this.instanceKeySupplier; } /** @@ -137,7 +137,6 @@ public class PcfAuthenticationOptions { /** * Configure the mount path. - * * @param path must not be empty or {@literal null}. * @return {@code this} {@link PcfAuthenticationOptionsBuilder}. * @see #DEFAULT_PCF_AUTHENTICATION_PATH @@ -152,9 +151,8 @@ public class PcfAuthenticationOptions { /** * Configure the role. - * * @param role name of the role against which the login is being attempted, must - * not be {@literal null} or empty. + * not be {@literal null} or empty. * @return {@code this} {@link PcfAuthenticationOptionsBuilder}. */ public PcfAuthenticationOptionsBuilder role(String role) { @@ -167,7 +165,6 @@ public class PcfAuthenticationOptions { /** * Configure the {@link Clock}. - * * @param clock must not be {@literal null}. * @return {@code this} {@link PcfAuthenticationOptionsBuilder}. */ @@ -181,16 +178,13 @@ public class PcfAuthenticationOptions { /** * Configure the {@link Supplier} to obtain the instance certificate. - * * @param instanceCertSupplier the supplier, must not be {@literal null}. * @return {@code this} {@link PcfAuthenticationOptionsBuilder}. * @see ResourceCredentialSupplier */ - public PcfAuthenticationOptionsBuilder instanceCertificate( - Supplier instanceCertSupplier) { + public PcfAuthenticationOptionsBuilder instanceCertificate(Supplier instanceCertSupplier) { - Assert.notNull(instanceCertSupplier, - "Instance certificate supplier must not be null"); + Assert.notNull(instanceCertSupplier, "Instance certificate supplier must not be null"); this.instanceCertSupplier = instanceCertSupplier; return this; @@ -198,16 +192,13 @@ public class PcfAuthenticationOptions { /** * Configure the {@link Supplier} to obtain the instance key. - * * @param instanceKeySupplier the supplier, must not be {@literal null}. * @return {@code this} {@link PcfAuthenticationOptionsBuilder}. * @see ResourceCredentialSupplier */ - public PcfAuthenticationOptionsBuilder instanceKey( - Supplier instanceKeySupplier) { + public PcfAuthenticationOptionsBuilder instanceKey(Supplier instanceKeySupplier) { - Assert.notNull(instanceKeySupplier, - "Instance certificate supplier must not be null"); + Assert.notNull(instanceKeySupplier, "Instance certificate supplier must not be null"); this.instanceKeySupplier = instanceKeySupplier; return this; @@ -219,31 +210,28 @@ public class PcfAuthenticationOptions { * Falls back to the instance certificate at {@code CF_INSTANCE_CERT} if * {@link #instanceCertificate(Supplier)} is not configured respective * {@code CF_INSTANCE_KEY} if {@link #instanceKey(Supplier)} is not configured. - * * @return a new {@link PcfAuthenticationOptions}. * @throws IllegalStateException if {@link #instanceCertificate(Supplier)} or - * {@link #instanceKey(Supplier)} are not set and the corresponding - * environment variable {@code CF_INSTANCE_CERT} respective - * {@code CF_INSTANCE_KEY} is not set. + * {@link #instanceKey(Supplier)} are not set and the corresponding environment + * variable {@code CF_INSTANCE_CERT} respective {@code CF_INSTANCE_KEY} is not + * set. */ public PcfAuthenticationOptions build() { - Assert.notNull(role, "Role must not be null"); + Assert.notNull(this.role, "Role must not be null"); Supplier instanceCertSupplier = this.instanceCertSupplier; if (instanceCertSupplier == null) { - instanceCertSupplier = new ResourceCredentialSupplier( - resolveEnvVariable("CF_INSTANCE_CERT")).cached(); + instanceCertSupplier = new ResourceCredentialSupplier(resolveEnvVariable("CF_INSTANCE_CERT")).cached(); } Supplier instanceKeySupplier = this.instanceKeySupplier; if (instanceKeySupplier == null) { - instanceKeySupplier = new ResourceCredentialSupplier( - resolveEnvVariable("CF_INSTANCE_KEY")).cached(); + instanceKeySupplier = new ResourceCredentialSupplier(resolveEnvVariable("CF_INSTANCE_KEY")).cached(); } - return new PcfAuthenticationOptions(path, role, clock, instanceCertSupplier, + return new PcfAuthenticationOptions(this.path, this.role, this.clock, instanceCertSupplier, instanceKeySupplier); } @@ -252,11 +240,12 @@ public class PcfAuthenticationOptions { String value = System.getenv(name); if (StringUtils.isEmpty(value)) { - throw new IllegalStateException( - String.format("Environment variable %s not set", name)); + throw new IllegalStateException(String.format("Environment variable %s not set", name)); } return value; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManager.java index 1c34a840..b349fe2d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManager.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManager.java @@ -80,14 +80,13 @@ import org.springframework.web.reactive.function.client.WebClientResponseExcepti * @see TaskScheduler * @see AuthenticationEventPublisher */ -public class ReactiveLifecycleAwareSessionManager - extends LifecycleAwareSessionManagerSupport +public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionManagerSupport implements ReactiveSessionManager, DisposableBean { private static final Mono EMPTY = Mono.empty(); - private static final Mono TERMINATED = Mono - .error(new TerminatedException()); + private static final Mono TERMINATED = Mono.error(new TerminatedException()); + /** * Client authentication mechanism. Used to obtain a {@link VaultToken} or * {@link LoginToken}. @@ -103,19 +102,17 @@ public class ReactiveLifecycleAwareSessionManager * The token state: Contains the currently valid token that identifies the Vault * session. */ - private volatile AtomicReference> token = new AtomicReference<>( - EMPTY); + private volatile AtomicReference> token = new AtomicReference<>(EMPTY); /** * Create a {@link ReactiveLifecycleAwareSessionManager} given * {@link ClientAuthentication}, {@link TaskScheduler} and {@link WebClient}. - * * @param clientAuthentication must not be {@literal null}. * @param taskScheduler must not be {@literal null}. * @param webClient must not be {@literal null}. */ - public ReactiveLifecycleAwareSessionManager(VaultTokenSupplier clientAuthentication, - TaskScheduler taskScheduler, WebClient webClient) { + public ReactiveLifecycleAwareSessionManager(VaultTokenSupplier clientAuthentication, TaskScheduler taskScheduler, + WebClient webClient) { super(taskScheduler); @@ -130,15 +127,13 @@ public class ReactiveLifecycleAwareSessionManager /** * Create a {@link ReactiveLifecycleAwareSessionManager} given * {@link VaultTokenSupplier}, {@link TaskScheduler} and {@link WebClient}. - * * @param clientAuthentication must not be {@literal null}. * @param taskScheduler must not be {@literal null}. * @param webClient must not be {@literal null}. * @param refreshTrigger must not be {@literal null}. */ - public ReactiveLifecycleAwareSessionManager(VaultTokenSupplier clientAuthentication, - TaskScheduler taskScheduler, WebClient webClient, - RefreshTrigger refreshTrigger) { + public ReactiveLifecycleAwareSessionManager(VaultTokenSupplier clientAuthentication, TaskScheduler taskScheduler, + WebClient webClient, RefreshTrigger refreshTrigger) { super(taskScheduler, refreshTrigger); @@ -162,7 +157,6 @@ public class ReactiveLifecycleAwareSessionManager /** * Revoke a {@link VaultToken} now and block execution until revocation completes. - * * @param tokenMono */ protected void revokeNow(Mono tokenMono) { @@ -171,32 +165,29 @@ public class ReactiveLifecycleAwareSessionManager protected Mono doRevoke(Mono tokenMono) { - return tokenMono.filter(TokenWrapper::isRevocable).map(TokenWrapper::getToken) - .flatMap(this::revoke); + return tokenMono.filter(TokenWrapper::isRevocable).map(TokenWrapper::getToken).flatMap(this::revoke); } /** * Revoke a {@link VaultToken}. - * * @param token the token to revoke, must not be {@literal null}. */ protected Mono revoke(VaultToken token) { - return webClient.post().uri("auth/token/revoke-self").headers(httpHeaders -> { + return this.webClient.post().uri("auth/token/revoke-self").headers(httpHeaders -> { httpHeaders.addAll(VaultHttpHeaders.from(token)); }).retrieve().bodyToMono(String.class) - .doOnSubscribe( - ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token))) + .doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token))) .doOnNext(ignore -> dispatch(new AfterLoginTokenRevocationEvent(token))) .onErrorResume(WebClientResponseException.class, e -> { - logger.warn(format("Could not revoke token", e)); + this.logger.warn(format("Could not revoke token", e)); dispatch(new LoginTokenRevocationFailedEvent(token, e)); return Mono.empty(); }).onErrorResume(Exception.class, e -> { - logger.warn("Could not revoke token", e); + this.logger.warn("Could not revoke token", e); dispatch(new LoginTokenRevocationFailedEvent(token, e)); return Mono.empty(); @@ -208,14 +199,13 @@ public class ReactiveLifecycleAwareSessionManager * token was obtained before, it uses self-renewal to renew the current token. * Client-side errors (like permission denied) indicate the token cannot be renewed * because it's expired or simply not found. - * * @return the {@link VaultToken} if the refresh was successful or a new token was * obtained. {@link Mono#empty()} if a new the token expired or * {@link Mono#error(Throwable)} if refresh failed. */ public Mono renewToken() { - logger.info("Renewing token"); + this.logger.info("Renewing token"); Mono tokenWrapper = this.token.get(); @@ -234,38 +224,33 @@ public class ReactiveLifecycleAwareSessionManager return doRenew(wrapper).onErrorResume(RuntimeException.class, e -> { - VaultTokenRenewalException exception = new VaultTokenRenewalException( - format("Cannot renew token", e), e); + VaultTokenRenewalException exception = new VaultTokenRenewalException(format("Cannot renew token", e), e); if (getLeaseStrategy().shouldDrop(exception)) { dropCurrentToken(); } - if (logger.isDebugEnabled()) { - logger.debug(exception.getMessage(), exception); + if (this.logger.isDebugEnabled()) { + this.logger.debug(exception.getMessage(), exception); } else { - logger.warn(exception.getMessage()); + this.logger.warn(exception.getMessage()); } - dispatch(new LoginTokenRenewalFailedEvent(wrapper.getToken(), exception)); - return EMPTY; - } + return EMPTY; + } ); } private Mono doRenew(TokenWrapper tokenWrapper) { - Mono exchange = webClient.post().uri("auth/token/renew-self") - .headers(httpHeaders -> httpHeaders - .putAll(VaultHttpHeaders.from(tokenWrapper.token))) - .retrieve().bodyToMono(VaultResponse.class); + Mono exchange = this.webClient.post().uri("auth/token/renew-self") + .headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(tokenWrapper.token))).retrieve() + .bodyToMono(VaultResponse.class); - return exchange - .doOnSubscribe(ignore -> dispatch( - new BeforeLoginTokenRenewedEvent(tokenWrapper.getToken()))) + return exchange.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRenewedEvent(tokenWrapper.getToken()))) .handle((response, sink) -> { LoginToken renewed = LoginTokenUtil.from(response.getRequiredAuth()); @@ -276,17 +261,15 @@ public class ReactiveLifecycleAwareSessionManager return; } - if (logger.isDebugEnabled()) { + if (this.logger.isDebugEnabled()) { - Duration validTtlThreshold = getRefreshTrigger() - .getValidTtlThreshold(renewed); - logger.info(String.format( - "Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.", - renewed.getLeaseDuration(), validTtlThreshold)); + Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed); + this.logger.info( + String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.", + renewed.getLeaseDuration(), validTtlThreshold)); } else { - logger.info( - "Token TTL exceeded validity TTL threshold. Dropping token."); + this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token."); } dropCurrentToken(); @@ -310,10 +293,9 @@ public class ReactiveLifecycleAwareSessionManager if (tokenWrapper == EMPTY) { - Mono obtainToken = clientAuthentication.getVaultToken() - .flatMap(this::doSelfLookup) // + Mono obtainToken = this.clientAuthentication.getVaultToken().flatMap(this::doSelfLookup) // .onErrorMap(it -> { - dispatch(new LoginFailedEvent(clientAuthentication, it)); + dispatch(new LoginFailedEvent(this.clientAuthentication, it)); return it; }).doOnNext(it -> { @@ -334,16 +316,13 @@ public class ReactiveLifecycleAwareSessionManager TokenWrapper wrapper = new TokenWrapper(token, token instanceof LoginToken); - if (isTokenSelfLookupEnabled() - && !ClassUtils.isAssignableValue(LoginToken.class, token)) { + if (isTokenSelfLookupEnabled() && !ClassUtils.isAssignableValue(LoginToken.class, token)) { - Mono loginTokenMono = augmentWithSelfLookup(this.webClient, - token); + Mono loginTokenMono = augmentWithSelfLookup(this.webClient, token); return loginTokenMono.onErrorResume(e -> { - logger.warn(String.format("Cannot enhance VaultToken to a LoginToken: %s", - e.getMessage())); + this.logger.warn(String.format("Cannot enhance VaultToken to a LoginToken: %s", e.getMessage())); dispatch(new AuthenticationErrorEvent(token, e)); return Mono.just(token); }).map(it -> new TokenWrapper(it, false)); @@ -362,35 +341,32 @@ public class ReactiveLifecycleAwareSessionManager .filter(it -> { LoginToken loginToken = (LoginToken) it; - return !loginToken.getLeaseDuration().isZero() - && loginToken.isRenewable(); + return !loginToken.getLeaseDuration().isZero() && loginToken.isRenewable(); }).isPresent(); } private void scheduleRenewal(VaultToken token) { - logger.info("Scheduling Token renewal"); + this.logger.info("Scheduling Token renewal"); Runnable task = () -> { try { - Mono tokenWrapper = ReactiveLifecycleAwareSessionManager.this.token - .get(); + Mono tokenWrapper = ReactiveLifecycleAwareSessionManager.this.token.get(); - if (tokenWrapper == Mono. empty() - || tokenWrapper == TERMINATED) { + if (tokenWrapper == Mono.empty() || tokenWrapper == TERMINATED) { return; } if (isTokenRenewable(token)) { renewToken().subscribe(this::scheduleRenewal, e -> { - logger.error("Cannot renew VaultToken", e); + this.logger.error("Cannot renew VaultToken", e); dispatch(new LoginTokenRenewalFailedEvent(token, e)); }); } } catch (Exception e) { - logger.error("Cannot renew VaultToken", e); + this.logger.error("Cannot renew VaultToken", e); dispatch(new LoginTokenRenewalFailedEvent(token, e)); } }; @@ -400,12 +376,10 @@ public class ReactiveLifecycleAwareSessionManager private OneShotTrigger createTrigger(VaultToken token) { - return new OneShotTrigger( - getRefreshTrigger().nextExecutionTime((LoginToken) token)); + return new OneShotTrigger(getRefreshTrigger().nextExecutionTime((LoginToken) token)); } - private static Mono augmentWithSelfLookup(WebClient webClient, - VaultToken token) { + private static Mono augmentWithSelfLookup(WebClient webClient, VaultToken token) { Mono> data = lookupSelf(webClient, token); @@ -415,27 +389,23 @@ public class ReactiveLifecycleAwareSessionManager Number ttl = (Number) it.get("ttl"); if (renewable != null && renewable) { - return LoginToken.renewable(token.toCharArray(), - LoginTokenAdapter.getLeaseDuration(ttl)); + return LoginToken.renewable(token.toCharArray(), LoginTokenAdapter.getLeaseDuration(ttl)); } - return LoginToken.of(token.toCharArray(), - LoginTokenAdapter.getLeaseDuration(ttl)); + return LoginToken.of(token.toCharArray(), LoginTokenAdapter.getLeaseDuration(ttl)); }); } - private static Mono> lookupSelf(WebClient webClient, - VaultToken token) { + private static Mono> lookupSelf(WebClient webClient, VaultToken token) { return webClient.get().uri("auth/token/lookup-self") - .headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token))) - .retrieve().bodyToMono(VaultResponse.class).map(it -> { + .headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token))).retrieve() + .bodyToMono(VaultResponse.class).map(it -> { Assert.state(it.getData() != null, "Token response is null"); return it.getRequiredData(); }).onErrorMap(WebClientResponseException.class, e -> { - return new VaultTokenLookupException(format("Token self-lookup", e), - e); + return new VaultTokenLookupException(format("Token self-lookup", e), e); }); } @@ -444,8 +414,7 @@ public class ReactiveLifecycleAwareSessionManager if (e instanceof WebClientResponseException) { WebClientResponseException wce = (WebClientResponseException) e; - return String.format("%s: Status %s %s %s", message, wce.getRawStatusCode(), - wce.getStatusText(), + return String.format("%s: Status %s %s %s", message, wce.getRawStatusCode(), wce.getStatusText(), VaultResponses.getError(wce.getResponseBodyAsString())); } @@ -461,6 +430,7 @@ public class ReactiveLifecycleAwareSessionManager protected static class TokenWrapper { private final VaultToken token; + private final boolean revocable; public TokenWrapper(VaultToken token, boolean revocable) { @@ -475,6 +445,7 @@ public class ReactiveLifecycleAwareSessionManager public boolean isRevocable() { return this.revocable; } + } /** @@ -486,5 +457,7 @@ public class ReactiveLifecycleAwareSessionManager super("Session manager terminated"); setStackTrace(new StackTraceElement[0]); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveSessionManager.java index d3eac144..8147224e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveSessionManager.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ReactiveSessionManager.java @@ -37,10 +37,10 @@ public interface ReactiveSessionManager extends VaultTokenSupplier { /** * Obtain a session token. - * * @return a session token. */ default Mono getSessionToken() { return getVaultToken(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ResourceCredentialSupplier.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ResourceCredentialSupplier.java index 5a6d6b76..e725de5e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ResourceCredentialSupplier.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ResourceCredentialSupplier.java @@ -40,7 +40,6 @@ public class ResourceCredentialSupplier implements CredentialSupplier { /** * Create a new {@link ResourceCredentialSupplier} {@link ResourceCredentialSupplier} * from a {@code path}. - * * @param path path to the file holding the credential. * @throws IllegalArgumentException if the{@code path} does not exist. */ @@ -51,7 +50,6 @@ public class ResourceCredentialSupplier implements CredentialSupplier { /** * Create a new {@link ResourceCredentialSupplier} {@link ResourceCredentialSupplier} * from a {@link File} handle. - * * @param file path to the file holding the credential. * @throws IllegalArgumentException if the{@code path} does not exist. */ @@ -62,14 +60,12 @@ public class ResourceCredentialSupplier implements CredentialSupplier { /** * Create a new {@link ResourceCredentialSupplier} {@link ResourceCredentialSupplier} * from a {@link Resource} handle. - * * @param resource resource pointing to the resource holding the credential. * @throws IllegalArgumentException if the {@link Resource} does not exist. */ public ResourceCredentialSupplier(Resource resource) { - Assert.isTrue(resource.exists(), - () -> String.format("Resource %s does not exist", resource)); + Assert.isTrue(resource.exists(), () -> String.format("Resource %s does not exist", resource)); this.resource = resource; } @@ -81,15 +77,12 @@ public class ResourceCredentialSupplier implements CredentialSupplier { return new String(readToken(this.resource), StandardCharsets.US_ASCII); } catch (IOException e) { - throw new VaultException( - String.format("Credential retrieval from %s failed", this.resource), - e); + throw new VaultException(String.format("Credential retrieval from %s failed", this.resource), e); } } /** * Read the token from {@link Resource}. - * * @param resource the resource to read from, must not be {@literal null}. * @return the new byte array that has been copied to (possibly empty). * @throws IOException in case of I/O errors. @@ -102,4 +95,5 @@ public class ResourceCredentialSupplier implements CredentialSupplier { return StreamUtils.copyToByteArray(is); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java index d550af42..e94e460f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java @@ -34,8 +34,8 @@ public interface SessionManager { /** * Obtain a session token. - * * @return a session token. */ VaultToken getSessionToken(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java index 90e1f227..c1c60b6f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java @@ -34,7 +34,6 @@ class Sha256 { /** * Generates a hex-encoded SHA256 checksum from the supplied {@code content}. - * * @param content must not be {@literal null} and not empty. * @return hex-encoded SHA256 checksum */ @@ -50,12 +49,10 @@ class Sha256 { /** * Get a MessageDigest instance for the given algorithm. Throws an * IllegalArgumentException if algorithm is unknown - * * @return MessageDigest instance * @throws IllegalArgumentException if NoSuchAlgorithmException is thrown */ - private static MessageDigest getMessageDigest(String algorithm) - throws IllegalArgumentException { + private static MessageDigest getMessageDigest(String algorithm) throws IllegalArgumentException { try { return MessageDigest.getInstance(algorithm); } @@ -74,4 +71,5 @@ class Sha256 { return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java index bfb1b3f5..f4cd5078 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java @@ -40,7 +40,6 @@ public class SimpleSessionManager implements SessionManager { /** * Create a new {@link SimpleSessionManager} using a {@link ClientAuthentication}. - * * @param clientAuthentication must not be {@literal null}. */ public SimpleSessionManager(ClientAuthentication clientAuthentication) { @@ -53,15 +52,15 @@ public class SimpleSessionManager implements SessionManager { @Override public VaultToken getSessionToken() { - if (!token.isPresent()) { - synchronized (lock) { - if (!token.isPresent()) { - token = Optional.of(clientAuthentication.login()); + if (!this.token.isPresent()) { + synchronized (this.lock) { + if (!this.token.isPresent()) { + this.token = Optional.of(this.clientAuthentication.login()); } } } - return token - .orElseThrow(() -> new IllegalStateException("Cannot obtain VaultToken")); + return this.token.orElseThrow(() -> new IllegalStateException("Cannot obtain VaultToken")); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/StaticUserId.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/StaticUserId.java index 6e71c998..e00a3e12 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/StaticUserId.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/StaticUserId.java @@ -30,7 +30,6 @@ public class StaticUserId implements AppIdUserIdMechanism { /** * Create a new {@link StaticUserId} for a given {@code userId}. - * * @param userId must not be empty or {@literal null}. */ public StaticUserId(String userId) { @@ -41,6 +40,7 @@ public class StaticUserId implements AppIdUserIdMechanism { @Override public String createUserId() { - return userId; + return this.userId; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/TokenAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/TokenAuthentication.java index a6ec2b4c..e2fd80a6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/TokenAuthentication.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/TokenAuthentication.java @@ -30,14 +30,12 @@ import static org.springframework.vault.authentication.AuthenticationSteps.HttpR * @see VaultToken * @see Auth Backend: Token */ -public class TokenAuthentication - implements ClientAuthentication, AuthenticationStepsFactory { +public class TokenAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private final VaultToken token; /** * Create a new {@link TokenAuthentication} with a static {@code token}. - * * @param token the Vault token, must not be empty or {@literal null}. */ public TokenAuthentication(String token) { @@ -49,7 +47,6 @@ public class TokenAuthentication /** * Create a new {@link TokenAuthentication} with a static {@code token}. - * * @param token the Vault token, must not be {@literal null}. */ public TokenAuthentication(VaultToken token) { @@ -62,27 +59,24 @@ public class TokenAuthentication /** * Creates a {@link AuthenticationSteps} for token authentication given * {@link VaultToken}. - * * @param token must not be {@literal null}. * @param selfLookup {@literal true} to perform a self-lookup using the given - * {@link VaultToken}. Self-lookup will create a {@link LoginToken} and provide - * renewability and TTL. + * {@link VaultToken}. Self-lookup will create a {@link LoginToken} and provide + * renewability and TTL. * @return {@link AuthenticationSteps} for token authentication. * @since 2.0 */ - public static AuthenticationSteps createAuthenticationSteps(VaultToken token, - boolean selfLookup) { + public static AuthenticationSteps createAuthenticationSteps(VaultToken token, boolean selfLookup) { Assert.notNull(token, "VaultToken must not be null"); if (selfLookup) { - HttpRequest httpRequest = get("auth/token/lookup-self") - .with(VaultHttpHeaders.from(token)).as(VaultResponse.class); + HttpRequest httpRequest = get("auth/token/lookup-self").with(VaultHttpHeaders.from(token)) + .as(VaultResponse.class); return AuthenticationSteps.fromHttpRequest(httpRequest) - .login(response -> LoginTokenUtil.from(token.toCharArray(), - response.getRequiredData())); + .login(response -> LoginTokenUtil.from(token.toCharArray(), response.getRequiredData())); } return AuthenticationSteps.just(token); @@ -97,4 +91,5 @@ public class TokenAuthentication public AuthenticationSteps getAuthenticationSteps() { return createAuthenticationSteps(this.token, false); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/UnwrappingEndpoints.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/UnwrappingEndpoints.java index 8a5be0ac..b6d643ba 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/UnwrappingEndpoints.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/UnwrappingEndpoints.java @@ -40,9 +40,7 @@ public enum UnwrappingEndpoints { @Override VaultResponse unwrap(VaultResponse vaultResponse) { - return VaultResponses.unwrap( - (String) vaultResponse.getRequiredData().get("response"), - VaultResponse.class); + return VaultResponses.unwrap((String) vaultResponse.getRequiredData().get("response"), VaultResponse.class); } @Override @@ -75,14 +73,12 @@ public enum UnwrappingEndpoints { /** * Retrieve the path of the unwrapping endpoint. - * * @return the unwrapping endpoint path. */ abstract String getPath(); /** * Unwrap the response data from {@link VaultResponses}. - * * @param response the raw response entity. * @return unwrapped {@link VaultResponse}. */ @@ -90,8 +86,8 @@ public enum UnwrappingEndpoints { /** * Unwrapping request {@link HttpMethod method}. - * * @return the unwrapping request {@link HttpMethod method}. */ abstract HttpMethod getUnwrapRequestMethod(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultLoginException.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultLoginException.java index 33af3761..1ccc2296 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultLoginException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultLoginException.java @@ -29,7 +29,6 @@ public class VaultLoginException extends VaultException { /** * Create a {@code VaultLoginException} with the specified detail message. - * * @param msg the detail message. */ public VaultLoginException(String msg) { @@ -39,7 +38,6 @@ public class VaultLoginException extends VaultException { /** * Create a {@code VaultLoginException} with the specified detail message and nested * exception. - * * @param msg the detail message. * @param cause the nested exception. */ @@ -50,7 +48,6 @@ public class VaultLoginException extends VaultException { /** * Create a {@link VaultLoginException} given {@code authMethod} and a * {@link Throwable cause}. - * * @param authMethod must not be {@literal null}. * @param cause must not be {@literal null}. * @return the {@link VaultLoginException}. @@ -59,12 +56,12 @@ public class VaultLoginException extends VaultException { if (cause instanceof RestClientResponseException) { - String response = ((RestClientResponseException) cause) - .getResponseBodyAsString(); - return new VaultLoginException(String.format("Cannot login using %s: %s", - authMethod, VaultResponses.getError(response)), cause); + String response = ((RestClientResponseException) cause).getResponseBodyAsString(); + return new VaultLoginException( + String.format("Cannot login using %s: %s", authMethod, VaultResponses.getError(response)), cause); } return new VaultLoginException(String.format("Cannot login using %s", cause)); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultSessionManagerException.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultSessionManagerException.java index 03c53003..18be3d44 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultSessionManagerException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultSessionManagerException.java @@ -27,7 +27,6 @@ public abstract class VaultSessionManagerException extends VaultException { /** * Create a {@code VaultSessionManagerException} with the specified detail message. - * * @param msg the detail message. */ public VaultSessionManagerException(String msg) { @@ -37,11 +36,11 @@ public abstract class VaultSessionManagerException extends VaultException { /** * Create a {@code VaultSessionManagerException} with the specified detail message and * nested exception. - * * @param msg the detail message. * @param cause the nested exception. */ public VaultSessionManagerException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenLookupException.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenLookupException.java index 1b50949e..83465127 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenLookupException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenLookupException.java @@ -27,7 +27,6 @@ public class VaultTokenLookupException extends VaultException { /** * Create a {@code VaultTokenLookupException} with the specified detail message. - * * @param msg the detail message. */ public VaultTokenLookupException(String msg) { @@ -37,7 +36,6 @@ public class VaultTokenLookupException extends VaultException { /** * Create a {@code VaultTokenLookupException} with the specified detail message and * nested exception. - * * @param msg the detail message. * @param cause the nested exception. * @since 2.1 @@ -45,4 +43,5 @@ public class VaultTokenLookupException extends VaultException { public VaultTokenLookupException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenRenewalException.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenRenewalException.java index 2384a86b..36a8d83a 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenRenewalException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenRenewalException.java @@ -25,7 +25,6 @@ public class VaultTokenRenewalException extends VaultSessionManagerException { /** * Create a {@code VaultTokenRenewalException} with the specified detail message. - * * @param msg the detail message. */ public VaultTokenRenewalException(String msg) { @@ -35,11 +34,11 @@ public class VaultTokenRenewalException extends VaultSessionManagerException { /** * Create a {@code VaultTokenRenewalException} with the specified detail message and * nested exception. - * * @param msg the detail message. * @param cause the nested exception. */ public VaultTokenRenewalException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenSupplier.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenSupplier.java index 6d83d1f4..acc8ecb4 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenSupplier.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/VaultTokenSupplier.java @@ -33,8 +33,8 @@ public interface VaultTokenSupplier { /** * Return a {@link VaultToken}. This can declare a Vault login flow to obtain a * {@link VaultToken token}. - * * @return a {@link Mono} with the {@link VaultToken}. */ Mono getVaultToken(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginEvent.java index 6e7f1722..392a9ee3 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginEvent.java @@ -31,11 +31,11 @@ public class AfterLoginEvent extends AuthenticationEvent { /** * Create a new {@link AfterLoginEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public AfterLoginEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRenewedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRenewedEvent.java index 1bba05b5..fc81752b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRenewedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRenewedEvent.java @@ -31,11 +31,11 @@ public class AfterLoginTokenRenewedEvent extends AuthenticationEvent { /** * Create a new {@link AfterLoginTokenRenewedEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public AfterLoginTokenRenewedEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRevocationEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRevocationEvent.java index 3cd1067e..42810e69 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRevocationEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AfterLoginTokenRevocationEvent.java @@ -31,11 +31,11 @@ public class AfterLoginTokenRevocationEvent extends AuthenticationEvent { /** * Create a new {@link AfterLoginTokenRevocationEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public AfterLoginTokenRevocationEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorEvent.java index 721b938d..c6196581 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorEvent.java @@ -37,7 +37,6 @@ public class AuthenticationErrorEvent extends ApplicationEvent { /** * Create a new {@link AuthenticationErrorEvent} given {@code source} and * {@link Exception}. - * * @param source must not be {@literal null}. * @param exception must not be {@literal null}. */ @@ -47,6 +46,7 @@ public class AuthenticationErrorEvent extends ApplicationEvent { } public Throwable getException() { - return exception; + return this.exception; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorListener.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorListener.java index 680006c1..10b3eb99 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorListener.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationErrorListener.java @@ -28,8 +28,8 @@ public interface AuthenticationErrorListener { /** * Callback for a {@link AuthenticationErrorEvent}. - * * @param authenticationEvent the event object, must not be {@literal null}. */ void onAuthenticationError(AuthenticationErrorEvent authenticationEvent); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationEvent.java index 70c82a0d..1cea6410 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationEvent.java @@ -31,9 +31,8 @@ public abstract class AuthenticationEvent extends ApplicationEvent { /** * Create a new {@link AuthenticationEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ protected AuthenticationEvent(VaultToken source) { super(source); @@ -43,4 +42,5 @@ public abstract class AuthenticationEvent extends ApplicationEvent { public VaultToken getSource() { return (VaultToken) super.getSource(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationListener.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationListener.java index 20ea5380..e7527431 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationListener.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/AuthenticationListener.java @@ -27,8 +27,8 @@ public interface AuthenticationListener { /** * Callback for a {@link AuthenticationEvent} - * * @param leaseEvent the event object, must not be {@literal null}. */ void onAuthenticationEvent(AuthenticationEvent leaseEvent); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRenewedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRenewedEvent.java index c9eb26e3..47ff835d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRenewedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRenewedEvent.java @@ -31,11 +31,11 @@ public class BeforeLoginTokenRenewedEvent extends AuthenticationEvent { /** * Create a new {@link BeforeLoginTokenRenewedEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public BeforeLoginTokenRenewedEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRevocationEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRevocationEvent.java index e1531cff..1e9cf084 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRevocationEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/BeforeLoginTokenRevocationEvent.java @@ -31,11 +31,11 @@ public class BeforeLoginTokenRevocationEvent extends AuthenticationEvent { /** * Create a new {@link BeforeLoginTokenRevocationEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public BeforeLoginTokenRevocationEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginFailedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginFailedEvent.java index 19ce841c..6074dc25 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginFailedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginFailedEvent.java @@ -36,12 +36,12 @@ public class LoginFailedEvent extends AuthenticationErrorEvent { /** * Create a new {@link LoginFailedEvent} given {@link Exception}. - * * @param source the {@link ClientAuthentication} or {@link VaultTokenSupplier} - * associated with this event, must not be {@literal null}. + * associated with this event, must not be {@literal null}. * @param exception must not be {@literal null}. */ public LoginFailedEvent(Object source, Throwable exception) { super(source, exception); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenExpiredEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenExpiredEvent.java index de472604..5a226142 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenExpiredEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenExpiredEvent.java @@ -31,11 +31,11 @@ public class LoginTokenExpiredEvent extends AuthenticationEvent { /** * Create a new {@link LoginTokenExpiredEvent} given {@link VaultToken}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. */ public LoginTokenExpiredEvent(VaultToken source) { super(source); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRenewalFailedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRenewalFailedEvent.java index a0509aa9..8b2e0d40 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRenewalFailedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRenewalFailedEvent.java @@ -32,9 +32,8 @@ public class LoginTokenRenewalFailedEvent extends AuthenticationErrorEvent { /** * Create a new {@link LoginTokenRenewalFailedEvent} given {@link VaultToken} and * {@link Exception}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. * @param exception must not be {@literal null}. */ public LoginTokenRenewalFailedEvent(VaultToken source, Throwable exception) { @@ -44,4 +43,5 @@ public class LoginTokenRenewalFailedEvent extends AuthenticationErrorEvent { public VaultToken getSource() { return (VaultToken) super.getSource(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRevocationFailedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRevocationFailedEvent.java index 42efbc63..efa091de 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRevocationFailedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/event/LoginTokenRevocationFailedEvent.java @@ -32,9 +32,8 @@ public class LoginTokenRevocationFailedEvent extends AuthenticationErrorEvent { /** * Create a new {@link LoginTokenRevocationFailedEvent} given {@link VaultToken} and * {@link Exception}. - * * @param source the {@link VaultToken} associated with this event, must not be - * {@literal null}. + * {@literal null}. * @param exception must not be {@literal null}. */ public LoginTokenRevocationFailedEvent(VaultToken source, Throwable exception) { @@ -44,4 +43,5 @@ public class LoginTokenRevocationFailedEvent extends AuthenticationErrorEvent { public VaultToken getSource() { return (VaultToken) super.getSource(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpConnectorFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpConnectorFactory.java index 51ad406b..b69a0376 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpConnectorFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpConnectorFactory.java @@ -51,15 +51,12 @@ import static org.springframework.vault.client.ClientHttpRequestFactoryFactory.h */ public class ClientHttpConnectorFactory { - private static final boolean REACTOR_NETTY_PRESENT = isPresent( - "reactor.netty.http.client.HttpClient"); + private static final boolean REACTOR_NETTY_PRESENT = isPresent("reactor.netty.http.client.HttpClient"); - private static final boolean JETTY_PRESENT = isPresent( - "org.eclipse.jetty.client.HttpClient"); + private static final boolean JETTY_PRESENT = isPresent("org.eclipse.jetty.client.HttpClient"); /** * Checks for presence of all {@code classNames} using this class' classloader. - * * @param classNames * @return {@literal true} if all classes are present; {@literal false} if at least * one class cannot be found. @@ -67,8 +64,7 @@ public class ClientHttpConnectorFactory { private static boolean isPresent(String... classNames) { for (String className : classNames) { - if (!ClassUtils.isPresent(className, - ClientHttpConnectorFactory.class.getClassLoader())) { + if (!ClassUtils.isPresent(className, ClientHttpConnectorFactory.class.getClassLoader())) { return false; } } @@ -79,13 +75,11 @@ public class ClientHttpConnectorFactory { /** * Create a {@link ClientHttpConnector} for the given {@link ClientOptions} and * {@link SslConfiguration}. - * * @param options must not be {@literal null} * @param sslConfiguration must not be {@literal null} * @return a new {@link ClientHttpConnector}. */ - public static ClientHttpConnector create(ClientOptions options, - SslConfiguration sslConfiguration) { + public static ClientHttpConnector create(ClientOptions options, SslConfiguration sslConfiguration) { Assert.notNull(options, "ClientOptions must not be null"); Assert.notNull(sslConfiguration, "SslConfiguration must not be null"); @@ -98,23 +92,20 @@ public class ClientHttpConnectorFactory { return JettyClient.usingJetty(options, sslConfiguration); } - throw new IllegalStateException( - "No supported Reactive Http Client library available (Reactor Netty, Jetty)"); + throw new IllegalStateException("No supported Reactive Http Client library available (Reactor Netty, Jetty)"); } - private static void configureSsl(SslConfiguration sslConfiguration, - SslContextBuilder sslContextBuilder) { + private static void configureSsl(SslConfiguration sslConfiguration, SslContextBuilder sslContextBuilder) { try { if (sslConfiguration.getTrustStoreConfiguration().isPresent()) { - sslContextBuilder.trustManager(createTrustManagerFactory( - sslConfiguration.getTrustStoreConfiguration())); + sslContextBuilder + .trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration())); } if (sslConfiguration.getKeyStoreConfiguration().isPresent()) { - sslContextBuilder.keyManager(createKeyManagerFactory( - sslConfiguration.getKeyStoreConfiguration(), + sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(), sslConfiguration.getKeyConfiguration())); } } @@ -130,8 +121,7 @@ public class ClientHttpConnectorFactory { */ static class ReactorNetty { - static ClientHttpConnector usingReactorNetty(ClientOptions options, - SslConfiguration sslConfiguration) { + static ClientHttpConnector usingReactorNetty(ClientOptions options, SslConfiguration sslConfiguration) { HttpClient client = HttpClient.create(); if (hasSslConfiguration(sslConfiguration)) { @@ -144,21 +134,20 @@ public class ClientHttpConnectorFactory { }); } - client = client.tcpConfiguration( - it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, - Math.toIntExact(options.getConnectionTimeout().toMillis()))); + client = client.tcpConfiguration(it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, + Math.toIntExact(options.getConnectionTimeout().toMillis()))); return new ReactorClientHttpConnector(client); } + } static class JettyClient { - static ClientHttpConnector usingJetty(ClientOptions options, - SslConfiguration sslConfiguration) { + + static ClientHttpConnector usingJetty(ClientOptions options, SslConfiguration sslConfiguration) { try { - return new JettyClientHttpConnector( - configureClient(getHttpClient(sslConfiguration), options)); + return new JettyClientHttpConnector(configureClient(getHttpClient(sslConfiguration), options)); } catch (GeneralSecurityException | IOException e) { throw new IllegalStateException(e); @@ -169,15 +158,13 @@ public class ClientHttpConnectorFactory { org.eclipse.jetty.client.HttpClient httpClient, ClientOptions options) { httpClient.setConnectTimeout(options.getConnectionTimeout().toMillis()); - httpClient.setAddressResolutionTimeout( - options.getConnectionTimeout().toMillis()); + httpClient.setAddressResolutionTimeout(options.getConnectionTimeout().toMillis()); return httpClient; } - private static org.eclipse.jetty.client.HttpClient getHttpClient( - SslConfiguration sslConfiguration) throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException { + private static org.eclipse.jetty.client.HttpClient getHttpClient(SslConfiguration sslConfiguration) + throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (hasSslConfiguration(sslConfiguration)) { @@ -195,16 +182,14 @@ public class ClientHttpConnectorFactory { sslContextFactory.setTrustStore(keyStore); } - SslConfiguration.KeyConfiguration keyConfiguration = sslConfiguration - .getKeyConfiguration(); + SslConfiguration.KeyConfiguration keyConfiguration = sslConfiguration.getKeyConfiguration(); if (keyConfiguration.getKeyAlias() != null) { sslContextFactory.setCertAlias(keyConfiguration.getKeyAlias()); } if (keyConfiguration.getKeyPassword() != null) { - sslContextFactory.setKeyManagerPassword( - new String(keyConfiguration.getKeyPassword())); + sslContextFactory.setKeyManagerPassword(new String(keyConfiguration.getKeyPassword())); } return new org.eclipse.jetty.client.HttpClient(sslContextFactory); @@ -212,5 +197,7 @@ public class ClientHttpConnectorFactory { return new org.eclipse.jetty.client.HttpClient(); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpRequestFactoryFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpRequestFactoryFactory.java index da358371..361381bf 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpRequestFactoryFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/ClientHttpRequestFactoryFactory.java @@ -80,21 +80,17 @@ import static org.springframework.vault.support.SslConfiguration.KeyConfiguratio */ public class ClientHttpRequestFactoryFactory { - private static final Log logger = LogFactory - .getLog(ClientHttpRequestFactoryFactory.class); + private static final Log logger = LogFactory.getLog(ClientHttpRequestFactoryFactory.class); - private static final boolean HTTP_COMPONENTS_PRESENT = isPresent( - "org.apache.http.client.HttpClient"); + private static final boolean HTTP_COMPONENTS_PRESENT = isPresent("org.apache.http.client.HttpClient"); private static final boolean OKHTTP3_PRESENT = isPresent("okhttp3.OkHttpClient"); - private static final boolean NETTY_PRESENT = isPresent( - "io.netty.channel.nio.NioEventLoopGroup", "io.netty.handler.ssl.SslContext", - "io.netty.handler.codec.http.HttpClientCodec"); + private static final boolean NETTY_PRESENT = isPresent("io.netty.channel.nio.NioEventLoopGroup", + "io.netty.handler.ssl.SslContext", "io.netty.handler.codec.http.HttpClientCodec"); /** * Checks for presence of all {@code classNames} using this class' classloader. - * * @param classNames * @return {@literal true} if all classes are present; {@literal false} if at least * one class cannot be found. @@ -102,8 +98,7 @@ public class ClientHttpRequestFactoryFactory { private static boolean isPresent(String... classNames) { for (String className : classNames) { - if (!ClassUtils.isPresent(className, - ClientHttpRequestFactoryFactory.class.getClassLoader())) { + if (!ClassUtils.isPresent(className, ClientHttpRequestFactoryFactory.class.getClassLoader())) { return false; } } @@ -114,14 +109,12 @@ public class ClientHttpRequestFactoryFactory { /** * Create a {@link ClientHttpRequestFactory} for the given {@link ClientOptions} and * {@link SslConfiguration}. - * * @param options must not be {@literal null} * @param sslConfiguration must not be {@literal null} * @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized * after obtaining. */ - public static ClientHttpRequestFactory create(ClientOptions options, - SslConfiguration sslConfiguration) { + public static ClientHttpRequestFactory create(ClientOptions options, SslConfiguration sslConfiguration) { Assert.notNull(options, "ClientOptions must not be null"); Assert.notNull(sslConfiguration, "SslConfiguration must not be null"); @@ -155,13 +148,13 @@ public class ClientHttpRequestFactoryFactory { return new SimpleClientHttpRequestFactory(); } - static SSLContext getSSLContext(SslConfiguration sslConfiguration, - TrustManager[] trustManagers) throws GeneralSecurityException, IOException { + static SSLContext getSSLContext(SslConfiguration sslConfiguration, TrustManager[] trustManagers) + throws GeneralSecurityException, IOException { KeyConfiguration keyConfiguration = sslConfiguration.getKeyConfiguration(); KeyManager[] keyManagers = sslConfiguration.getKeyStoreConfiguration().isPresent() - ? createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(), - keyConfiguration).getKeyManagers() + ? createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(), keyConfiguration) + .getKeyManagers() : null; SSLContext sslContext = SSLContext.getInstance("TLS"); @@ -174,26 +167,20 @@ public class ClientHttpRequestFactoryFactory { throws GeneralSecurityException, IOException { return sslConfiguration.getTrustStoreConfiguration().isPresent() - ? createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()) - .getTrustManagers() - : null; + ? createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()).getTrustManagers() : null; } - static KeyManagerFactory createKeyManagerFactory( - KeyStoreConfiguration keyStoreConfiguration, - KeyConfiguration keyConfiguration) - throws GeneralSecurityException, IOException { + static KeyManagerFactory createKeyManagerFactory(KeyStoreConfiguration keyStoreConfiguration, + KeyConfiguration keyConfiguration) throws GeneralSecurityException, IOException { KeyStore keyStore = getKeyStore(keyStoreConfiguration); - KeyManagerFactory keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); char[] keyPasswordToUse = keyConfiguration.getKeyPassword(); if (keyPasswordToUse == null) { - keyPasswordToUse = keyStoreConfiguration.getStorePassword() == null - ? new char[0] + keyPasswordToUse = keyStoreConfiguration.getStorePassword() == null ? new char[0] : keyStoreConfiguration.getStorePassword(); } @@ -207,20 +194,16 @@ public class ClientHttpRequestFactoryFactory { } static KeyStore getKeyStore(KeyStoreConfiguration keyStoreConfiguration) - throws KeyStoreException, IOException, NoSuchAlgorithmException, - CertificateException { + throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { - KeyStore keyStore = KeyStore - .getInstance(StringUtils.hasText(keyStoreConfiguration.getStoreType()) - ? keyStoreConfiguration.getStoreType() - : KeyStore.getDefaultType()); + KeyStore keyStore = KeyStore.getInstance(StringUtils.hasText(keyStoreConfiguration.getStoreType()) + ? keyStoreConfiguration.getStoreType() : KeyStore.getDefaultType()); loadKeyStore(keyStoreConfiguration, keyStore); return keyStore; } - static TrustManagerFactory createTrustManagerFactory( - KeyStoreConfiguration keyStoreConfiguration) + static TrustManagerFactory createTrustManagerFactory(KeyStoreConfiguration keyStoreConfiguration) throws GeneralSecurityException, IOException { KeyStore trustStore = getKeyStore(keyStoreConfiguration); @@ -232,8 +215,7 @@ public class ClientHttpRequestFactoryFactory { return trustManagerFactory; } - private static void loadKeyStore(KeyStoreConfiguration keyStoreConfiguration, - KeyStore keyStore) + private static void loadKeyStore(KeyStoreConfiguration keyStoreConfiguration, KeyStore keyStore) throws IOException, NoSuchAlgorithmException, CertificateException { InputStream inputStream = null; @@ -260,31 +242,26 @@ public class ClientHttpRequestFactoryFactory { */ static class HttpComponents { - static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, - SslConfiguration sslConfiguration) + static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration) throws GeneralSecurityException, IOException { HttpClientBuilder httpClientBuilder = HttpClients.custom(); - httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner( - DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault())); + httpClientBuilder.setRoutePlanner( + new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault())); if (hasSslConfiguration(sslConfiguration)) { - SSLContext sslContext = getSSLContext(sslConfiguration, - getTrustManagers(sslConfiguration)); - SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( - sslContext); + SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration)); + SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setSSLContext(sslContext); } RequestConfig requestConfig = RequestConfig.custom() // - .setConnectTimeout( - Math.toIntExact(options.getConnectionTimeout().toMillis())) // - .setSocketTimeout( - Math.toIntExact(options.getReadTimeout().toMillis())) // + .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) // + .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) // .setAuthenticationEnabled(true) // .build(); @@ -295,6 +272,7 @@ public class ClientHttpRequestFactoryFactory { return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); } + } /** @@ -304,8 +282,7 @@ public class ClientHttpRequestFactoryFactory { */ static class OkHttp3 { - static ClientHttpRequestFactory usingOkHttp3(ClientOptions options, - SslConfiguration sslConfiguration) + static ClientHttpRequestFactory usingOkHttp3(ClientOptions options, SslConfiguration sslConfiguration) throws GeneralSecurityException, IOException { Builder builder = new Builder(); @@ -314,10 +291,9 @@ public class ClientHttpRequestFactoryFactory { TrustManager[] trustManagers = getTrustManagers(sslConfiguration); - if (trustManagers.length != 1 - || !(trustManagers[0] instanceof X509TrustManager)) { - throw new IllegalStateException("Unexpected default trust managers:" - + Arrays.toString(trustManagers)); + if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { + throw new IllegalStateException( + "Unexpected default trust managers:" + Arrays.toString(trustManagers)); } X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; @@ -326,12 +302,12 @@ public class ClientHttpRequestFactoryFactory { builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager); } - builder.connectTimeout(options.getConnectionTimeout().toMillis(), - TimeUnit.MILLISECONDS).readTimeout( - options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS); + builder.connectTimeout(options.getConnectionTimeout().toMillis(), TimeUnit.MILLISECONDS) + .readTimeout(options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS); return new OkHttp3ClientHttpRequestFactory(builder.build()); } + } /** @@ -341,8 +317,7 @@ public class ClientHttpRequestFactoryFactory { */ static class Netty { - static ClientHttpRequestFactory usingNetty(ClientOptions options, - SslConfiguration sslConfiguration) + static ClientHttpRequestFactory usingNetty(ClientOptions options, SslConfiguration sslConfiguration) throws GeneralSecurityException, IOException { Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory(); @@ -353,44 +328,38 @@ public class ClientHttpRequestFactoryFactory { .forClient(); if (sslConfiguration.getTrustStoreConfiguration().isPresent()) { - sslContextBuilder.trustManager(createTrustManagerFactory( - sslConfiguration.getTrustStoreConfiguration())); + sslContextBuilder + .trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration())); } if (sslConfiguration.getKeyStoreConfiguration().isPresent()) { - sslContextBuilder.keyManager(createKeyManagerFactory( - sslConfiguration.getKeyStoreConfiguration(), + sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(), sslConfiguration.getKeyConfiguration())); } - requestFactory.setSslContext( - sslContextBuilder.sslProvider(SslProvider.JDK).build()); + requestFactory.setSslContext(sslContextBuilder.sslProvider(SslProvider.JDK).build()); } - requestFactory.setConnectTimeout( - Math.toIntExact(options.getConnectionTimeout().toMillis())); - requestFactory - .setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis())); + requestFactory.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())); + requestFactory.setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis())); return requestFactory; } + } static class KeySelectingKeyManagerFactory extends KeyManagerFactory { - KeySelectingKeyManagerFactory(KeyManagerFactory factory, - KeyConfiguration keyConfiguration) { + KeySelectingKeyManagerFactory(KeyManagerFactory factory, KeyConfiguration keyConfiguration) { super(new KeyManagerFactorySpi() { @Override protected void engineInit(KeyStore keyStore, char[] chars) - throws KeyStoreException, NoSuchAlgorithmException, - UnrecoverableKeyException { + throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { factory.init(keyStore, chars); } @Override - protected void engineInit( - ManagerFactoryParameters managerFactoryParameters) + protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { factory.init(managerFactoryParameters); } @@ -400,66 +369,64 @@ public class ClientHttpRequestFactoryFactory { KeyManager[] keyManagers = factory.getKeyManagers(); - if (keyManagers.length == 1 - && keyManagers[0] instanceof X509ExtendedKeyManager) { + if (keyManagers.length == 1 && keyManagers[0] instanceof X509ExtendedKeyManager) { return new KeyManager[] { new KeySelectingX509KeyManager( - (X509ExtendedKeyManager) keyManagers[0], - keyConfiguration) }; + (X509ExtendedKeyManager) keyManagers[0], keyConfiguration) }; } return keyManagers; } }, factory.getProvider(), factory.getAlgorithm()); } + } private static class KeySelectingX509KeyManager extends X509ExtendedKeyManager { private final X509ExtendedKeyManager delegate; + private final KeyConfiguration keyConfiguration; - KeySelectingX509KeyManager(X509ExtendedKeyManager delegate, - KeyConfiguration keyConfiguration) { + KeySelectingX509KeyManager(X509ExtendedKeyManager delegate, KeyConfiguration keyConfiguration) { this.delegate = delegate; this.keyConfiguration = keyConfiguration; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { - return delegate.getClientAliases(keyType, issuers); + return this.delegate.getClientAliases(keyType, issuers); } @Override - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - return keyConfiguration.getKeyAlias(); + public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { + return this.keyConfiguration.getKeyAlias(); } - public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, - SSLEngine engine) { - return keyConfiguration.getKeyAlias(); + public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) { + return this.keyConfiguration.getKeyAlias(); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { - return delegate.getServerAliases(keyType, issuers); + return this.delegate.getServerAliases(keyType, issuers); } @Override - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - return delegate.chooseServerAlias(keyType, issuers, socket); + public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { + return this.delegate.chooseServerAlias(keyType, issuers, socket); } @Override public X509Certificate[] getCertificateChain(String alias) { - return delegate.getCertificateChain(alias); + return this.delegate.getCertificateChain(alias); } @Override public PrivateKey getPrivateKey(String alias) { - return delegate.getPrivateKey(alias); + return this.delegate.getPrivateKey(alias); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/ReactiveVaultClients.java b/spring-vault-core/src/main/java/org/springframework/vault/client/ReactiveVaultClients.java index d3dbcf5f..93848a87 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/ReactiveVaultClients.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/ReactiveVaultClients.java @@ -46,13 +46,11 @@ public class ReactiveVaultClients { * slash that are expanded to use {@link VaultEndpoint}. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @param endpoint must not be {@literal null}. * @param connector must not be {@literal null}. * @return the configured {@link WebClient}. */ - public static WebClient createWebClient(VaultEndpoint endpoint, - ClientHttpConnector connector) { + public static WebClient createWebClient(VaultEndpoint endpoint, ClientHttpConnector connector) { return createWebClient(SimpleVaultEndpointProvider.of(endpoint), connector); } @@ -62,13 +60,11 @@ public class ReactiveVaultClients { * slash that are expanded to use {@link VaultEndpoint}. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @return the configured {@link WebClient}. */ - public static WebClient createWebClient(VaultEndpointProvider endpointProvider, - ClientHttpConnector connector) { + public static WebClient createWebClient(VaultEndpointProvider endpointProvider, ClientHttpConnector connector) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); @@ -82,42 +78,38 @@ public class ReactiveVaultClients { * slash that are expanded to use {@link VaultEndpoint}. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @return the prepared {@link WebClient.Builder}. */ - static WebClient.Builder createWebClientBuilder( - VaultEndpointProvider endpointProvider, ClientHttpConnector connector) { + static WebClient.Builder createWebClientBuilder(VaultEndpointProvider endpointProvider, + ClientHttpConnector connector) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); - UriBuilderFactory uriBuilderFactory = VaultClients - .createUriBuilderFactory(endpointProvider); + UriBuilderFactory uriBuilderFactory = VaultClients.createUriBuilderFactory(endpointProvider); - ExchangeStrategies strategies = ExchangeStrategies.builder() - .codecs(configurer -> { + ExchangeStrategies strategies = ExchangeStrategies.builder().codecs(configurer -> { - CustomCodecs cc = configurer.customCodecs(); + CustomCodecs cc = configurer.customCodecs(); - cc.decoder(new ByteArrayDecoder()); - cc.decoder(new Jackson2JsonDecoder()); - cc.decoder(StringDecoder.allMimeTypes()); + cc.decoder(new ByteArrayDecoder()); + cc.decoder(new Jackson2JsonDecoder()); + cc.decoder(StringDecoder.allMimeTypes()); - cc.encoder(new ByteArrayEncoder()); - cc.encoder(new Jackson2JsonEncoder()); + cc.encoder(new ByteArrayEncoder()); + cc.encoder(new Jackson2JsonEncoder()); - }).build(); + }).build(); - return WebClient.builder().uriBuilderFactory(uriBuilderFactory) - .exchangeStrategies(strategies).clientConnector(connector); + return WebClient.builder().uriBuilderFactory(uriBuilderFactory).exchangeStrategies(strategies) + .clientConnector(connector); } /** * Create a {@link ExchangeFilterFunction} that associates each request with a * {@code X-Vault-Namespace} header if the header is not present. - * * @param namespace the Vault namespace to use. Must not be {@literal null} or empty. * @return the {@link ExchangeFilterFunction} to register with {@link WebClient}. * @see VaultHttpHeaders#VAULT_NAMESPACE @@ -140,4 +132,5 @@ public class ReactiveVaultClients { }); }); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateBuilder.java b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateBuilder.java index e5d8f9c0..760961ff 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateBuilder.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateBuilder.java @@ -73,7 +73,6 @@ public class RestTemplateBuilder { /** * Create a new {@link RestTemplateBuilder}. - * * @return a new {@link RestTemplateBuilder}. */ public static RestTemplateBuilder builder() { @@ -82,7 +81,6 @@ public class RestTemplateBuilder { /** * Set the {@link VaultEndpoint} that should be used with the {@link RestTemplate}. - * * @param endpoint the {@link VaultEndpoint} provider. * @return {@code this} {@link RestTemplateBuilder}. */ @@ -93,7 +91,6 @@ public class RestTemplateBuilder { /** * Set the {@link VaultEndpointProvider} that should be used with the * {@link RestTemplate}. - * * @param provider the {@link VaultEndpoint} provider. * @return {@code this} {@link RestTemplateBuilder}. */ @@ -109,7 +106,6 @@ public class RestTemplateBuilder { /** * Set the {@link ClientHttpRequestFactory} that should be used with the * {@link RestTemplate}. - * * @param requestFactory the request factory. * @return {@code this} {@link RestTemplateBuilder}. */ @@ -123,15 +119,12 @@ public class RestTemplateBuilder { /** * Set the {@link Supplier} of {@link ClientHttpRequestFactory} that should be called * each time we {@link #build()} a new {@link RestTemplate} instance. - * * @param requestFactory the supplier for the request factory. * @return {@code this} {@link RestTemplateBuilder}. */ - public RestTemplateBuilder requestFactory( - Supplier requestFactory) { + public RestTemplateBuilder requestFactory(Supplier requestFactory) { - Assert.notNull(requestFactory, - "Supplier of ClientHttpRequestFactory must not be null"); + Assert.notNull(requestFactory, "Supplier of ClientHttpRequestFactory must not be null"); this.requestFactory = requestFactory; return this; @@ -140,7 +133,6 @@ public class RestTemplateBuilder { /** * Set the {@link ResponseErrorHandler} that should be used with the * {@link RestTemplate}. - * * @param errorHandler the error handler to use. * @return {@code this} {@link RestTemplateBuilder}. */ @@ -155,7 +147,6 @@ public class RestTemplateBuilder { /** * Add a default header that will be set if not already present on the outgoing * {@link HttpRequest}. - * * @param name the name of the header. * @param value the header value. * @return {@code this} {@link RestTemplateBuilder}. @@ -173,7 +164,6 @@ public class RestTemplateBuilder { * Add the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be * applied to the {@link RestTemplate}. Customizers are applied in the order that they * were added. - * * @param customizer the template customizers to add. * @return {@code this} {@link RestTemplateBuilder}. */ @@ -188,13 +178,11 @@ public class RestTemplateBuilder { * Add the {@link RestTemplateRequestCustomizer RestTemplateRequestCustomizers} that * should be applied to the {@link ClientHttpRequest}. Customizers are applied in the * order that they were added. - * * @param requestCustomizers the request customizers to add. * @return {@code this} {@link RestTemplateBuilder}. */ @SuppressWarnings("unchecked") - public RestTemplateBuilder requestCustomizers( - RestTemplateRequestCustomizer... requestCustomizers) { + public RestTemplateBuilder requestCustomizers(RestTemplateRequestCustomizer... requestCustomizers) { Assert.notNull(requestCustomizers, "RequestCustomizers must not be null"); @@ -207,66 +195,58 @@ public class RestTemplateBuilder { * * Applies also {@link ResponseErrorHandler} and {@link RestTemplateCustomizer} if * configured. - * * @return a new {@link RestTemplate}. */ public RestTemplate build() { - Assert.state(this.endpointProvider != null, - "VaultEndpointProvider must not be null"); + Assert.state(this.endpointProvider != null, "VaultEndpointProvider must not be null"); RestTemplate restTemplate = createTemplate(); - if (errorHandler != null) { - restTemplate.setErrorHandler(errorHandler); + if (this.errorHandler != null) { + restTemplate.setErrorHandler(this.errorHandler); } - customizers.forEach(customizer -> customizer.customize(restTemplate)); + this.customizers.forEach(customizer -> customizer.customize(restTemplate)); return restTemplate; } /** * Create the {@link RestTemplate} to use. - * * @return the {@link RestTemplate} to use. */ protected RestTemplate createTemplate() { ClientHttpRequestFactory requestFactory = this.requestFactory.get(); - LinkedHashMap defaultHeaders = new LinkedHashMap<>( - this.defaultHeaders); + LinkedHashMap defaultHeaders = new LinkedHashMap<>(this.defaultHeaders); LinkedHashSet> requestCustomizers = new LinkedHashSet<>( this.requestCustomizers); RestTemplate restTemplate = VaultClients.createRestTemplate(this.endpointProvider, - new RestTemplateBuilderClientHttpRequestFactoryWrapper(requestFactory, - requestCustomizers)); + new RestTemplateBuilderClientHttpRequestFactoryWrapper(requestFactory, requestCustomizers)); - restTemplate.getInterceptors() - .add((httpRequest, bytes, clientHttpRequestExecution) -> { + restTemplate.getInterceptors().add((httpRequest, bytes, clientHttpRequestExecution) -> { - HttpHeaders headers = httpRequest.getHeaders(); - defaultHeaders.forEach((key, value) -> { - if (!headers.containsKey(key)) { - headers.add(key, value); - } - }); + HttpHeaders headers = httpRequest.getHeaders(); + defaultHeaders.forEach((key, value) -> { + if (!headers.containsKey(key)) { + headers.add(key, value); + } + }); - return clientHttpRequestExecution.execute(httpRequest, bytes); - }); + return clientHttpRequestExecution.execute(httpRequest, bytes); + }); return restTemplate; } - static class RestTemplateBuilderClientHttpRequestFactoryWrapper - extends AbstractClientHttpRequestFactoryWrapper { + static class RestTemplateBuilderClientHttpRequestFactoryWrapper extends AbstractClientHttpRequestFactoryWrapper { private final Set> requestCustomizers; - RestTemplateBuilderClientHttpRequestFactoryWrapper( - ClientHttpRequestFactory requestFactory, + RestTemplateBuilderClientHttpRequestFactoryWrapper(ClientHttpRequestFactory requestFactory, Set> requestCustomizers) { super(requestFactory); @@ -283,5 +263,7 @@ public class RestTemplateBuilder { return request; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateCustomizer.java b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateCustomizer.java index ac62e167..1f2d4514 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateCustomizer.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateCustomizer.java @@ -29,8 +29,8 @@ public interface RestTemplateCustomizer { /** * Callback to customize a {@link RestTemplate} instance. - * * @param restTemplate the template to customize. */ void customize(RestTemplate restTemplate); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateRequestCustomizer.java b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateRequestCustomizer.java index f8ea1ffe..0e6fa8fc 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateRequestCustomizer.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/RestTemplateRequestCustomizer.java @@ -31,8 +31,8 @@ public interface RestTemplateRequestCustomizer { /** * Customize the specified {@link ClientHttpRequest}. - * * @param request the request to customize. */ void customize(T request); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/SimpleVaultEndpointProvider.java b/spring-vault-core/src/main/java/org/springframework/vault/client/SimpleVaultEndpointProvider.java index 04498ec1..0e835312 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/SimpleVaultEndpointProvider.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/SimpleVaultEndpointProvider.java @@ -33,7 +33,6 @@ public class SimpleVaultEndpointProvider implements VaultEndpointProvider { /** * Creates a new {@link VaultEndpointProvider} given {@link VaultEndpoint}. - * * @param endpoint must not be {@literal null}. */ public static VaultEndpointProvider of(VaultEndpoint endpoint) { @@ -45,6 +44,7 @@ public class SimpleVaultEndpointProvider implements VaultEndpointProvider { @Override public VaultEndpoint getVaultEndpoint() { - return endpoint; + return this.endpoint; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClients.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClients.java index ad222fa5..5ccadf79 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClients.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClients.java @@ -58,17 +58,14 @@ public class VaultClients { * Otherwise, Vault will deny body processing. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @param endpoint must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @return the {@link RestTemplate}. * @see org.springframework.http.client.Netty4ClientHttpRequestFactory * @see MappingJackson2HttpMessageConverter */ - public static RestTemplate createRestTemplate(VaultEndpoint endpoint, - ClientHttpRequestFactory requestFactory) { - return createRestTemplate(SimpleVaultEndpointProvider.of(endpoint), - requestFactory); + public static RestTemplate createRestTemplate(VaultEndpoint endpoint, ClientHttpRequestFactory requestFactory) { + return createRestTemplate(SimpleVaultEndpointProvider.of(endpoint), requestFactory); } /** @@ -82,7 +79,6 @@ public class VaultClients { * Otherwise, Vault will deny body processing. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @param endpointProvider must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @return the {@link RestTemplate}. @@ -110,7 +106,6 @@ public class VaultClients { * Otherwise, Vault will deny body processing. *

* Requires Jackson 2 for Object-to-JSON mapping. - * * @return the {@link RestTemplate}. * @see org.springframework.http.client.Netty4ClientHttpRequestFactory * @see MappingJackson2HttpMessageConverter @@ -124,8 +119,7 @@ public class VaultClients { RestTemplate restTemplate = new RestTemplate(messageConverters); - restTemplate.getInterceptors() - .add((request, body, execution) -> execution.execute(request, body)); + restTemplate.getInterceptors().add((request, body, execution) -> execution.execute(request, body)); return restTemplate; } @@ -133,15 +127,13 @@ public class VaultClients { /** * Create a {@link ClientHttpRequestInterceptor} that associates each request with a * {@code X-Vault-Namespace} header if the header is not present. - * * @param namespace the Vault namespace to use. Must not be {@literal null} or empty. * @return the {@link ClientHttpRequestInterceptor} to register with * {@link RestTemplate}. * @see VaultHttpHeaders#VAULT_NAMESPACE * @since 2.2 */ - public static ClientHttpRequestInterceptor createNamespaceInterceptor( - String namespace) { + public static ClientHttpRequestInterceptor createNamespaceInterceptor(String namespace) { Assert.hasText(namespace, "Vault Namespace must not be empty!"); @@ -157,8 +149,7 @@ public class VaultClients { }; } - public static UriBuilderFactory createUriBuilderFactory( - VaultEndpointProvider endpointProvider) { + public static UriBuilderFactory createUriBuilderFactory(VaultEndpointProvider endpointProvider) { return new PrefixAwareUriBuilderFactory(endpointProvider); } @@ -177,27 +168,26 @@ public class VaultClients { @Override protected URI expandInternal(String uriTemplate, Map uriVariables) { - return super.expandInternal(prepareUriTemplate(getBaseUrl(), uriTemplate), - uriVariables); + return super.expandInternal(prepareUriTemplate(getBaseUrl(), uriTemplate), uriVariables); } @Override protected URI expandInternal(String uriTemplate, Object... uriVariables) { - return super.expandInternal(prepareUriTemplate(getBaseUrl(), uriTemplate), - uriVariables); + return super.expandInternal(prepareUriTemplate(getBaseUrl(), uriTemplate), uriVariables); } @Override public String getBaseUrl() { - if (endpointProvider != null) { + if (this.endpointProvider != null) { - VaultEndpoint endpoint = endpointProvider.getVaultEndpoint(); + VaultEndpoint endpoint = this.endpointProvider.getVaultEndpoint(); return toBaseUri(endpoint); } return super.getBaseUrl(); } + } /** @@ -218,27 +208,26 @@ public class VaultClients { return UriComponentsBuilder.fromUriString(uriTemplate); } - VaultEndpoint endpoint = endpointProvider.getVaultEndpoint(); + VaultEndpoint endpoint = this.endpointProvider.getVaultEndpoint(); String baseUri = toBaseUri(endpoint); - UriComponents uriComponents = UriComponentsBuilder - .fromUriString(prepareUriTemplate(baseUri, uriTemplate)).build(); + UriComponents uriComponents = UriComponentsBuilder.fromUriString(prepareUriTemplate(baseUri, uriTemplate)) + .build(); - return UriComponentsBuilder.fromUriString(baseUri) - .uriComponents(uriComponents); + return UriComponentsBuilder.fromUriString(baseUri).uriComponents(uriComponents); } + } private static String toBaseUri(VaultEndpoint endpoint) { - return String.format("%s://%s:%s/%s", endpoint.getScheme(), endpoint.getHost(), - endpoint.getPort(), endpoint.getPath()); + return String.format("%s://%s:%s/%s", endpoint.getScheme(), endpoint.getHost(), endpoint.getPort(), + endpoint.getPath()); } /** * Strip/add leading slashes from {@code uriTemplate} depending on whether the base * url has a trailing slash. - * * @param uriTemplate * @return */ @@ -277,4 +266,5 @@ public class VaultClients { return uriTemplate; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java index d5457050..1474805b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java @@ -59,7 +59,6 @@ public class VaultEndpoint implements Serializable { /** * Create a secure {@link VaultEndpoint} given a {@code host} and {@code port} using * {@code https}. - * * @param host must not be empty or {@literal null}. * @param port must be a valid port in the range of 1-65535 * @return a new {@link VaultEndpoint}. @@ -78,9 +77,8 @@ public class VaultEndpoint implements Serializable { /** * Create a {@link VaultEndpoint} given a {@link URI}. - * * @param uri must contain hostname, port and scheme, must not be empty or - * {@literal null}. + * {@literal null}. * @return a new {@link VaultEndpoint}. */ public static VaultEndpoint from(URI uri) { @@ -93,12 +91,10 @@ public class VaultEndpoint implements Serializable { vaultEndpoint.setHost(uri.getHost()); try { - vaultEndpoint.setPort( - uri.getPort() == -1 ? uri.toURL().getDefaultPort() : uri.getPort()); + vaultEndpoint.setPort(uri.getPort() == -1 ? uri.toURL().getDefaultPort() : uri.getPort()); } catch (MalformedURLException e) { - throw new IllegalArgumentException( - String.format("Can't retrieve default port from %s", uri), e); + throw new IllegalArgumentException(String.format("Can't retrieve default port from %s", uri), e); } vaultEndpoint.setScheme(uri.getScheme()); @@ -122,12 +118,11 @@ public class VaultEndpoint implements Serializable { * @return the hostname. */ public String getHost() { - return host; + return this.host; } /** * Sets the hostname. - * * @param host must not be empty or {@literal null}. */ public void setHost(String host) { @@ -138,7 +133,7 @@ public class VaultEndpoint implements Serializable { * @return the port. */ public int getPort() { - return port; + return this.port; } /** @@ -146,8 +141,7 @@ public class VaultEndpoint implements Serializable { */ public void setPort(int port) { - Assert.isTrue(port >= 1 && port <= 65535, - "Port must be a valid port in the range between 1 and 65535"); + Assert.isTrue(port >= 1 && port <= 65535, "Port must be a valid port in the range between 1 and 65535"); this.port = port; } @@ -156,7 +150,7 @@ public class VaultEndpoint implements Serializable { * @return the protocol scheme. */ public String getScheme() { - return scheme; + return this.scheme; } /** @@ -164,8 +158,7 @@ public class VaultEndpoint implements Serializable { */ public void setScheme(String scheme) { - Assert.isTrue("http".equals(scheme) || "https".equals(scheme), - "Scheme must be http or https"); + Assert.isTrue("http".equals(scheme) || "https".equals(scheme), "Scheme must be http or https"); this.scheme = scheme; } @@ -175,26 +168,24 @@ public class VaultEndpoint implements Serializable { * @since 2.1 */ public String getPath() { - return path; + return this.path; } /** * @param path context path prefix. Must not be {@literal null} or empty and must not - * start with a leading slash. + * start with a leading slash. * @since 2.1 */ public void setPath(String path) { Assert.hasText(path, "Path must not be null or empty"); - Assert.isTrue(!path.startsWith("/"), - () -> String.format("Path %s must not start with a leading slash", path)); + Assert.isTrue(!path.startsWith("/"), () -> String.format("Path %s must not start with a leading slash", path)); this.path = path; } /** * Build the Vault {@link URI} based on the given {@code path}. - * * @param path must not be empty or {@literal null}. * @return constructed {@link URI}. */ @@ -204,7 +195,6 @@ public class VaultEndpoint implements Serializable { /** * Build the Vault URI string based on the given {@code path}. - * * @param path must not be empty or {@literal null}. * @return constructed URI String. */ @@ -212,8 +202,7 @@ public class VaultEndpoint implements Serializable { Assert.hasText(path, "Path must not be empty"); - return String.format("%s://%s:%s/%s/%s", getScheme(), getHost(), getPort(), - getPath(), path); + return String.format("%s://%s:%s/%s/%s", getScheme(), getHost(), getPort(), getPath(), path); } @Override @@ -223,17 +212,18 @@ public class VaultEndpoint implements Serializable { if (!(o instanceof VaultEndpoint)) return false; VaultEndpoint that = (VaultEndpoint) o; - return port == that.port && host.equals(that.host) && scheme.equals(that.scheme) - && path.equals(that.path); + return this.port == that.port && this.host.equals(that.host) && this.scheme.equals(that.scheme) + && this.path.equals(that.path); } @Override public int hashCode() { - return Objects.hash(host, port, scheme, path); + return Objects.hash(this.host, this.port, this.scheme, this.path); } @Override public String toString() { - return String.format("%s://%s:%d", scheme, host, port); + return String.format("%s://%s:%d", this.scheme, this.host, this.port); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpointProvider.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpointProvider.java index 022caa03..cf1f00ad 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpointProvider.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpointProvider.java @@ -27,8 +27,8 @@ public interface VaultEndpointProvider { /** * Provides access to {@link VaultEndpoint}. - * * @return the {@link VaultEndpoint}. */ VaultEndpoint getVaultEndpoint(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultHttpHeaders.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultHttpHeaders.java index 8e499f7f..69950e79 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultHttpHeaders.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultHttpHeaders.java @@ -56,4 +56,5 @@ public abstract class VaultHttpHeaders { return headers; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponses.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponses.java index 79d4c8c4..e716a8d9 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponses.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponses.java @@ -60,13 +60,11 @@ public abstract class VaultResponses { String message = VaultResponses.getError(e.getResponseBodyAsString()); if (StringUtils.hasText(message)) { - return new VaultException(String.format("Status %s %s: %s", - e.getRawStatusCode(), e.getStatusText(), message), e); + return new VaultException( + String.format("Status %s %s: %s", e.getRawStatusCode(), e.getStatusText(), message), e); } - return new VaultException( - String.format("Status %s %s", e.getRawStatusCode(), e.getStatusText()), - e); + return new VaultException(String.format("Status %s %s", e.getRawStatusCode(), e.getStatusText()), e); } /** @@ -83,20 +81,17 @@ public abstract class VaultResponses { String message = VaultResponses.getError(e.getResponseBodyAsString()); if (StringUtils.hasText(message)) { - return new VaultException(String.format("Status %s %s [%s]: %s", - e.getRawStatusCode(), e.getStatusText(), path, message), e); + return new VaultException( + String.format("Status %s %s [%s]: %s", e.getRawStatusCode(), e.getStatusText(), path, message), e); } - return new VaultException(String.format("Status %s %s [%s]", e.getRawStatusCode(), - e.getStatusText(), path), e); + return new VaultException(String.format("Status %s %s [%s]", e.getRawStatusCode(), e.getStatusText(), path), e); } - public static VaultException buildException(HttpStatus statusCode, String path, - String message) { + public static VaultException buildException(HttpStatus statusCode, String path, String message) { if (StringUtils.hasText(message)) { - return new VaultException( - String.format("Status %s [%s]: %s", statusCode, path, message)); + return new VaultException(String.format("Status %s [%s]: %s", statusCode, path, message)); } return new VaultException(String.format("Status %s [%s]", statusCode, path)); @@ -140,7 +135,6 @@ public abstract class VaultResponses { /** * Obtain the error message from a JSON response. - * * @param json must not be {@literal null}. * @return extracted error string. */ @@ -152,8 +146,7 @@ public abstract class VaultResponses { if (json.contains("\"errors\":")) { try { - Map map = OBJECT_MAPPER.readValue(json.getBytes(), - Map.class); + Map map = OBJECT_MAPPER.readValue(json.getBytes(), Map.class); if (map.containsKey("errors")) { Collection errors = (Collection) map.get("errors"); @@ -173,7 +166,6 @@ public abstract class VaultResponses { /** * Unwrap a wrapped response created by Vault Response Wrapping - * * @param wrappedResponse the wrapped response , must not be empty or {@literal null}. * @param responseType the type of the return value. * @return the unwrapped response. @@ -200,4 +192,5 @@ public abstract class VaultResponses { throw new IllegalStateException(e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientBuilder.java b/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientBuilder.java index 5908226d..da0b9d02 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientBuilder.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientBuilder.java @@ -51,8 +51,8 @@ public class WebClientBuilder { private @Nullable VaultEndpointProvider endpointProvider; - private Supplier httpConnector = () -> ClientHttpConnectorFactory - .create(new ClientOptions(), SslConfiguration.unconfigured()); + private Supplier httpConnector = () -> ClientHttpConnectorFactory.create(new ClientOptions(), + SslConfiguration.unconfigured()); private final Map defaultHeaders = new LinkedHashMap<>(); @@ -65,7 +65,6 @@ public class WebClientBuilder { /** * Create a new {@link WebClientBuilder}. - * * @return a new {@link WebClientBuilder}. */ public static WebClientBuilder builder() { @@ -74,7 +73,6 @@ public class WebClientBuilder { /** * Set the {@link VaultEndpoint} that should be used with the {@link WebClient}. - * * @param endpoint the {@link VaultEndpoint} provider. * @return {@code this} {@link WebClientBuilder}. */ @@ -85,7 +83,6 @@ public class WebClientBuilder { /** * Set the {@link VaultEndpointProvider} that should be used with the * {@link WebClient}. - * * @param provider the {@link VaultEndpoint} provider. * @return {@code this} {@link WebClientBuilder}. */ @@ -100,7 +97,6 @@ public class WebClientBuilder { /** * Set the {@link ClientHttpConnector} that should be used with the {@link WebClient}. - * * @param httpConnector the HTTP connector. * @return {@code this} {@link WebClientBuilder}. */ @@ -114,13 +110,11 @@ public class WebClientBuilder { /** * Set the {@link Supplier} of {@link ClientHttpConnector} that should be called each * time we {@link #build()} a new {@link WebClient} instance. - * * @param httpConnector the supplier for the HTTP connector. * @return {@code this} {@link WebClientBuilder}. * @since 2.2.1 */ - public WebClientBuilder httpConnectorFactory( - Supplier httpConnector) { + public WebClientBuilder httpConnectorFactory(Supplier httpConnector) { Assert.notNull(httpConnector, "Supplier of ClientHttpConnector must not be null"); @@ -131,7 +125,6 @@ public class WebClientBuilder { /** * Set the {@link Supplier} of {@link ClientHttpConnector} that should be called each * time we {@link #build()} a new {@link WebClient} instance. - * * @param httpConnector the supplier for the HTTP connector. * @return {@code this} {@link WebClientBuilder}. * @deprecated since 2.2.1 as the name is wrong, use @@ -145,7 +138,6 @@ public class WebClientBuilder { /** * Add a default header that will be set if not already present on the outgoing * {@link HttpRequest}. - * * @param name the name of the header. * @param value the header value. * @return {@code this} {@link WebClientBuilder}. @@ -162,7 +154,6 @@ public class WebClientBuilder { /** * Add the {@link WebClientCustomizer WebClientCustomizers} that should be applied to * the {@link WebClient}. Customizers are applied in the order that they were added. - * * @param customizer the client customizers to add. * @return {@code this} {@link WebClientBuilder}. */ @@ -177,7 +168,6 @@ public class WebClientBuilder { * Add the {@link ExchangeFilterFunction ExchangeFilterFunctions} that should be * applied to the {@link ClientRequest}. {@link ExchangeFilterFunction}s are applied * in the order that they were added. - * * @param filterFunctions the request customizers to add. * @return {@code this} {@link WebClientBuilder}. */ @@ -194,23 +184,21 @@ public class WebClientBuilder { * * Applies also {@link ExchangeFilterFunction} and {@link WebClientCustomizer} if * configured. - * * @return a new {@link WebClient}. */ public WebClient build() { - Assert.state(this.endpointProvider != null, - "VaultEndpointProvider must not be null"); + Assert.state(this.endpointProvider != null, "VaultEndpointProvider must not be null"); WebClient.Builder builder = createWebClientBuilder(); - if (!defaultHeaders.isEmpty()) { + if (!this.defaultHeaders.isEmpty()) { Map defaultHeaders = this.defaultHeaders; builder.filter((request, next) -> { - return next.exchange(ClientRequest.from(request) - .headers(headers -> defaultHeaders.forEach((key, value) -> { + return next.exchange( + ClientRequest.from(request).headers(headers -> defaultHeaders.forEach((key, value) -> { if (!headers.containsKey(key)) { headers.add(key, value); } @@ -219,23 +207,22 @@ public class WebClientBuilder { }); } - builder.filters(exchangeFilterFunctions -> exchangeFilterFunctions - .addAll(this.filterFunctions)); + builder.filters(exchangeFilterFunctions -> exchangeFilterFunctions.addAll(this.filterFunctions)); - customizers.forEach(customizer -> customizer.customize(builder)); + this.customizers.forEach(customizer -> customizer.customize(builder)); return builder.build(); } /** * Create the {@link WebClient.Builder} to use. - * * @return the {@link WebClient.Builder} to use. */ protected WebClient.Builder createWebClientBuilder() { ClientHttpConnector connector = this.httpConnector.get(); - return ReactiveVaultClients.createWebClientBuilder(endpointProvider, connector); + return ReactiveVaultClients.createWebClientBuilder(this.endpointProvider, connector); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientCustomizer.java b/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientCustomizer.java index 0e1e3db1..75f5ddab 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientCustomizer.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/client/WebClientCustomizer.java @@ -29,8 +29,8 @@ public interface WebClientCustomizer { /** * Callback to customize a {@link WebClient.Builder} instance. - * * @param webClientBuilder the client builder to customize. */ void customize(WebClient.Builder webClientBuilder); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractReactiveVaultConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractReactiveVaultConfiguration.java index 1a0fd40b..46d40083 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractReactiveVaultConfiguration.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractReactiveVaultConfiguration.java @@ -61,13 +61,11 @@ import org.springframework.web.reactive.function.client.WebClient; * @since 2.0 */ @Configuration(proxyBeanMethods = false) -public abstract class AbstractReactiveVaultConfiguration - extends AbstractVaultConfiguration { +public abstract class AbstractReactiveVaultConfiguration extends AbstractVaultConfiguration { /** * Create a {@link WebClientBuilder} initialized with {@link VaultEndpointProvider} * and {@link ClientHttpConnector}. May be overridden by subclasses. - * * @return the {@link WebClientBuilder}. * @see #vaultEndpointProvider() * @see #clientHttpConnector() @@ -75,13 +73,11 @@ public abstract class AbstractReactiveVaultConfiguration */ protected WebClientBuilder webClientBuilder(VaultEndpointProvider endpointProvider, ClientHttpConnector httpConnector) { - return WebClientBuilder.builder().endpointProvider(endpointProvider) - .httpConnector(httpConnector); + return WebClientBuilder.builder().endpointProvider(endpointProvider).httpConnector(httpConnector); } /** * Create a {@link ReactiveVaultTemplate}. - * * @return the {@link ReactiveVaultTemplate}. * @see #vaultEndpoint() * @see #clientHttpConnector() @@ -89,15 +85,13 @@ public abstract class AbstractReactiveVaultConfiguration */ @Bean public ReactiveVaultTemplate reactiveVaultTemplate() { - return new ReactiveVaultTemplate( - webClientBuilder(vaultEndpointProvider(), clientHttpConnector()), + return new ReactiveVaultTemplate(webClientBuilder(vaultEndpointProvider(), clientHttpConnector()), getReactiveSessionManager()); } /** * Construct a session manager adapter wrapping {@link #reactiveSessionManager()} and * exposing imperative {@link SessionManager} on top of a reactive API. - * * @return the {@link SessionManager} adapter. */ @Bean @@ -110,7 +104,6 @@ public abstract class AbstractReactiveVaultConfiguration * Construct a {@link ReactiveSessionManager} using {@link #vaultTokenSupplier()}. * This {@link org.springframework.vault.authentication.ReactiveSessionManager} uses * {@link #threadPoolTaskScheduler()}. - * * @return the {@link VaultTokenSupplier} for Vault session token management. * @see VaultTokenSupplier * @see #clientAuthentication() @@ -118,15 +111,13 @@ public abstract class AbstractReactiveVaultConfiguration @Bean public ReactiveSessionManager reactiveSessionManager() { - WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint(), - clientHttpConnector()); - return new ReactiveLifecycleAwareSessionManager(vaultTokenSupplier(), - getVaultThreadPoolTaskScheduler(), webClient); + WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint(), clientHttpConnector()); + return new ReactiveLifecycleAwareSessionManager(vaultTokenSupplier(), getVaultThreadPoolTaskScheduler(), + webClient); } /** * Construct a {@link VaultTokenSupplier} using {@link #clientAuthentication()}. - * * @return the {@link VaultTokenSupplier} for Vault session token management. * @see VaultTokenSupplier * @see #clientAuthentication() @@ -147,8 +138,7 @@ public abstract class AbstractReactiveVaultConfiguration AuthenticationStepsFactory factory = (AuthenticationStepsFactory) clientAuthentication; - WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint(), - clientHttpConnector()); + WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint(), clientHttpConnector()); AuthenticationStepsOperator stepsOperator = new AuthenticationStepsOperator( factory.getAuthenticationSteps(), webClient); @@ -164,7 +154,6 @@ public abstract class AbstractReactiveVaultConfiguration /** * Create a {@link ClientHttpConnector} configured with {@link ClientOptions} and * {@link org.springframework.vault.support.SslConfiguration}. - * * @return the {@link ClientHttpConnector} instance. * @see #clientOptions() * @see #sslConfiguration() @@ -174,8 +163,7 @@ public abstract class AbstractReactiveVaultConfiguration } private ReactiveSessionManager getReactiveSessionManager() { - return getBeanFactory().getBean("reactiveSessionManager", - ReactiveSessionManager.class); + return getBeanFactory().getBean("reactiveSessionManager", ReactiveSessionManager.class); } /** @@ -192,7 +180,9 @@ public abstract class AbstractReactiveVaultConfiguration @Override public VaultToken getSessionToken() { - return sessionManager.getSessionToken().block(Duration.ofSeconds(30)); + return this.sessionManager.getSessionToken().block(Duration.ofSeconds(30)); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java index 722eab73..a9754325 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java @@ -72,7 +72,6 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * Annotate with {@link Bean} in case you want to expose a * {@link ClientAuthentication} instance to the * {@link org.springframework.context.ApplicationContext}. - * * @return the {@link ClientAuthentication} to use. Must not be {@literal null}. */ public abstract ClientAuthentication clientAuthentication(); @@ -80,22 +79,18 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw /** * Create a {@link RestTemplateBuilder} initialized with {@link VaultEndpointProvider} * and {@link ClientHttpRequestFactory}. May be overridden by subclasses. - * * @return the {@link RestTemplateBuilder}. * @see #vaultEndpointProvider() * @see #clientHttpRequestFactoryWrapper() * @since 2.2 */ - protected RestTemplateBuilder restTemplateBuilder( - VaultEndpointProvider endpointProvider, + protected RestTemplateBuilder restTemplateBuilder(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) { - return RestTemplateBuilder.builder().endpointProvider(endpointProvider) - .requestFactory(requestFactory); + return RestTemplateBuilder.builder().endpointProvider(endpointProvider).requestFactory(requestFactory); } /** * Create a {@link VaultTemplate}. - * * @return the {@link VaultTemplate}. * @see #vaultEndpointProvider() * @see #clientHttpRequestFactoryWrapper() @@ -104,8 +99,7 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw @Bean public VaultTemplate vaultTemplate() { return new VaultTemplate( - restTemplateBuilder(vaultEndpointProvider(), - getClientFactoryWrapper().getClientHttpRequestFactory()), + restTemplateBuilder(vaultEndpointProvider(), getClientFactoryWrapper().getClientHttpRequestFactory()), getBeanFactory().getBean("sessionManager", SessionManager.class)); } @@ -113,7 +107,6 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * Construct a {@link LifecycleAwareSessionManager} using * {@link #clientAuthentication()}. This {@link SessionManager} uses * {@link #threadPoolTaskScheduler()}. - * * @return the {@link SessionManager} for Vault session management. * @see SessionManager * @see LifecycleAwareSessionManager @@ -128,14 +121,13 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw Assert.notNull(clientAuthentication, "ClientAuthentication must not be null"); - return new LifecycleAwareSessionManager(clientAuthentication, - getVaultThreadPoolTaskScheduler(), restOperations()); + return new LifecycleAwareSessionManager(clientAuthentication, getVaultThreadPoolTaskScheduler(), + restOperations()); } /** * Construct a {@link SecretLeaseContainer} using {@link #vaultTemplate()} and * {@link #threadPoolTaskScheduler()}. - * * @return the {@link SecretLeaseContainer} to allocate, renew and rotate secrets and * their leases. * @see #vaultTemplate() @@ -145,8 +137,7 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw public SecretLeaseContainer secretLeaseContainer() throws Exception { SecretLeaseContainer secretLeaseContainer = new SecretLeaseContainer( - getBeanFactory().getBean("vaultTemplate", VaultTemplate.class), - getVaultThreadPoolTaskScheduler()); + getBeanFactory().getBean("vaultTemplate", VaultTemplate.class), getVaultThreadPoolTaskScheduler()); secretLeaseContainer.afterPropertiesSet(); secretLeaseContainer.start(); @@ -162,7 +153,6 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * to the {@link org.springframework.context.ApplicationContext}. This might be useful * to supply managed executor instances or {@link ThreadPoolTaskScheduler}s using a * queue/pooled threads. - * * @return the {@link ThreadPoolTaskScheduler} to use. Must not be {@literal null}. */ @Bean("vaultThreadPoolTaskScheduler") @@ -170,8 +160,7 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); - threadPoolTaskScheduler - .setThreadNamePrefix("spring-vault-ThreadPoolTaskScheduler-"); + threadPoolTaskScheduler.setThreadNamePrefix("spring-vault-ThreadPoolTaskScheduler-"); threadPoolTaskScheduler.setDaemon(true); return threadPoolTaskScheduler; @@ -181,14 +170,13 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * Construct a {@link RestOperations} object configured for Vault session management * and authentication usage. Can be customized by overriding * {@link #restTemplateBuilder(VaultEndpointProvider, ClientHttpRequestFactory)}. - * * @return the {@link RestOperations} to be used for Vault access. * @see #vaultEndpointProvider() * @see #clientHttpRequestFactoryWrapper() */ public RestOperations restOperations() { - return restTemplateBuilder(vaultEndpointProvider(), - getClientFactoryWrapper().getClientHttpRequestFactory()).build(); + return restTemplateBuilder(vaultEndpointProvider(), getClientFactoryWrapper().getClientHttpRequestFactory()) + .build(); } /** @@ -197,7 +185,6 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * {@link ClientHttpRequestFactory} is configured with {@link ClientOptions} and * {@link SslConfiguration} which are not necessarily applicable for the whole * application. - * * @return the {@link ClientFactoryWrapper} to wrap a {@link ClientHttpRequestFactory} * instance. * @see #clientOptions() @@ -205,8 +192,7 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw */ @Bean public ClientFactoryWrapper clientHttpRequestFactoryWrapper() { - return new ClientFactoryWrapper(ClientHttpRequestFactoryFactory - .create(clientOptions(), sslConfiguration())); + return new ClientFactoryWrapper(ClientHttpRequestFactoryFactory.create(clientOptions(), sslConfiguration())); } /** @@ -231,40 +217,36 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw * Return the {@link Environment} to access property sources during Spring Vault * bootstrapping. Requires {@link #setApplicationContext(ApplicationContext) * ApplicationContext} to be set. - * * @return the {@link Environment} to access property sources during Spring Vault * bootstrapping. */ protected Environment getEnvironment() { - Assert.state(applicationContext != null, + Assert.state(this.applicationContext != null, "ApplicationContext must be set before accessing getEnvironment()"); - return applicationContext.getEnvironment(); + return this.applicationContext.getEnvironment(); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } BeanFactory getBeanFactory() { - Assert.state(applicationContext != null, + Assert.state(this.applicationContext != null, "ApplicationContext must be set before accessing getBeanFactory()"); - return applicationContext; + return this.applicationContext; } ThreadPoolTaskScheduler getVaultThreadPoolTaskScheduler() { - return getBeanFactory().getBean("vaultThreadPoolTaskScheduler", - ThreadPoolTaskScheduler.class); + return getBeanFactory().getBean("vaultThreadPoolTaskScheduler", ThreadPoolTaskScheduler.class); } private ClientFactoryWrapper getClientFactoryWrapper() { - return getBeanFactory().getBean("clientHttpRequestFactoryWrapper", - ClientFactoryWrapper.class); + return getBeanFactory().getBean("clientHttpRequestFactoryWrapper", ClientFactoryWrapper.class); } /** @@ -280,21 +262,23 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw @Override public void destroy() throws Exception { - if (clientHttpRequestFactory instanceof DisposableBean) { - ((DisposableBean) clientHttpRequestFactory).destroy(); + if (this.clientHttpRequestFactory instanceof DisposableBean) { + ((DisposableBean) this.clientHttpRequestFactory).destroy(); } } @Override public void afterPropertiesSet() throws Exception { - if (clientHttpRequestFactory instanceof InitializingBean) { - ((InitializingBean) clientHttpRequestFactory).afterPropertiesSet(); + if (this.clientHttpRequestFactory instanceof InitializingBean) { + ((InitializingBean) this.clientHttpRequestFactory).afterPropertiesSet(); } } public ClientHttpRequestFactory getClientHttpRequestFactory() { - return clientHttpRequestFactory; + return this.clientHttpRequestFactory; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpConnectorFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpConnectorFactory.java index 6150ee30..926a638e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpConnectorFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpConnectorFactory.java @@ -36,14 +36,12 @@ public class ClientHttpConnectorFactory { /** * Create a {@link ClientHttpConnector} for the given {@link ClientOptions} and * {@link SslConfiguration}. - * * @param options must not be {@literal null} * @param sslConfiguration must not be {@literal null} * @return a new {@link ClientHttpConnector}. */ - public static ClientHttpConnector create(ClientOptions options, - SslConfiguration sslConfiguration) { - return org.springframework.vault.client.ClientHttpConnectorFactory.create(options, - sslConfiguration); + public static ClientHttpConnector create(ClientOptions options, SslConfiguration sslConfiguration) { + return org.springframework.vault.client.ClientHttpConnectorFactory.create(options, sslConfiguration); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java index 92c6c627..c0e4bac5 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java @@ -35,15 +35,13 @@ public class ClientHttpRequestFactoryFactory { /** * Create a {@link ClientHttpRequestFactory} for the given {@link ClientOptions} and * {@link SslConfiguration}. - * * @param options must not be {@literal null} * @param sslConfiguration must not be {@literal null} * @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized * after obtaining. */ - public static ClientHttpRequestFactory create(ClientOptions options, - SslConfiguration sslConfiguration) { - return org.springframework.vault.client.ClientHttpRequestFactoryFactory - .create(options, sslConfiguration); + public static ClientHttpRequestFactory create(ClientOptions options, SslConfiguration sslConfiguration) { + return org.springframework.vault.client.ClientHttpRequestFactoryFactory.create(options, sslConfiguration); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/EnvironmentVaultConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/config/EnvironmentVaultConfiguration.java index 0400c165..3bb39a43 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/config/EnvironmentVaultConfiguration.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/config/EnvironmentVaultConfiguration.java @@ -80,8 +80,7 @@ import org.springframework.web.client.RestOperations; * @Import(EnvironmentVaultConfiguration.class) * public class MyConfiguration { * } - * - * + * * * Supplied properties: * @@ -89,8 +88,7 @@ import org.springframework.web.client.RestOperations; * * vault.uri=https://localhost:8200 * vault.token=00000000-0000-0000-0000-000000000000 - * - * + * * *

Property keys

* @@ -185,13 +183,12 @@ import org.springframework.web.client.RestOperations; * @see KubernetesAuthentication */ @Configuration -public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration - implements ApplicationContextAware { +public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration implements ApplicationContextAware { - private static final Log logger = LogFactory - .getLog(EnvironmentVaultConfiguration.class); + private static final Log logger = LogFactory.getLog(EnvironmentVaultConfiguration.class); private @Nullable RestOperations cachedRestOperations; + private @Nullable ApplicationContext applicationContext; @Override @@ -206,8 +203,7 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; super.setApplicationContext(applicationContext); @@ -227,17 +223,16 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration @Override public SslConfiguration sslConfiguration() { - KeyStoreConfiguration keyStoreConfiguration = getKeyStoreConfiguration( - "vault.ssl.key-store", "vault.ssl.key-store-password"); + KeyStoreConfiguration keyStoreConfiguration = getKeyStoreConfiguration("vault.ssl.key-store", + "vault.ssl.key-store-password"); - KeyStoreConfiguration trustStoreConfiguration = getKeyStoreConfiguration( - "vault.ssl.trust-store", "vault.ssl.trust-store-password"); + KeyStoreConfiguration trustStoreConfiguration = getKeyStoreConfiguration("vault.ssl.trust-store", + "vault.ssl.trust-store-password"); return new SslConfiguration(keyStoreConfiguration, trustStoreConfiguration); } - private KeyStoreConfiguration getKeyStoreConfiguration(String resourceProperty, - String passwordProperty) { + private KeyStoreConfiguration getKeyStoreConfiguration(String resourceProperty, String passwordProperty) { Resource keyStore = getResource(resourceProperty); String keyStorePassword = getProperty(passwordProperty); @@ -256,11 +251,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration @Override public ClientAuthentication clientAuthentication() { - String authentication = getProperty("vault.authentication", - AuthenticationMethod.TOKEN.name()).toUpperCase().replace('-', '_'); + String authentication = getProperty("vault.authentication", AuthenticationMethod.TOKEN.name()).toUpperCase() + .replace('-', '_'); - AuthenticationMethod authenticationMethod = AuthenticationMethod - .valueOf(authentication); + AuthenticationMethod authenticationMethod = AuthenticationMethod.valueOf(authentication); switch (authenticationMethod) { @@ -281,8 +275,7 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration case KUBERNETES: return kubeAuthentication(); default: - throw new IllegalStateException(String.format( - "Vault authentication method %s is not supported with %s", + throw new IllegalStateException(String.format("Vault authentication method %s is not supported with %s", authenticationMethod, getClass().getSimpleName())); } } @@ -294,27 +287,23 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration protected ClientAuthentication tokenAuthentication() { String token = getProperty("vault.token"); - Assert.hasText(token, - "Vault Token authentication: Token (vault.token) must not be empty"); + Assert.hasText(token, "Vault Token authentication: Token (vault.token) must not be empty"); return new TokenAuthentication(token); } protected ClientAuthentication appIdAuthentication() { - String appId = getProperty("vault.app-id.app-id", - getProperty("spring.application.name")); + String appId = getProperty("vault.app-id.app-id", getProperty("spring.application.name")); String userId = getProperty("vault.app-id.user-id"); String path = getProperty("vault.app-id.app-id-path", AppIdAuthenticationOptions.DEFAULT_APPID_AUTHENTICATION_PATH); - Assert.hasText(appId, - "Vault AppId authentication: AppId (vault.app-id.app-id) must not be empty"); - Assert.hasText(userId, - "Vault AppId authentication: UserId (vault.app-id.user-id) must not be empty"); + Assert.hasText(appId, "Vault AppId authentication: AppId (vault.app-id.app-id) must not be empty"); + Assert.hasText(userId, "Vault AppId authentication: UserId (vault.app-id.user-id) must not be empty"); - AppIdAuthenticationOptionsBuilder builder = AppIdAuthenticationOptions.builder() - .appId(appId).userIdMechanism(getAppIdUserIdMechanism(userId)).path(path); + AppIdAuthenticationOptionsBuilder builder = AppIdAuthenticationOptions.builder().appId(appId) + .userIdMechanism(getAppIdUserIdMechanism(userId)).path(path); return new AppIdAuthentication(builder.build(), restOperations()); } @@ -326,11 +315,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration String path = getProperty("vault.app-role.app-role-path", AppRoleAuthenticationOptions.DEFAULT_APPROLE_AUTHENTICATION_PATH); - Assert.hasText(roleId, - "Vault AppRole authentication: RoleId (vault.app-role.role-id) must not be empty"); + Assert.hasText(roleId, "Vault AppRole authentication: RoleId (vault.app-role.role-id) must not be empty"); - AppRoleAuthenticationOptionsBuilder builder = AppRoleAuthenticationOptions - .builder().roleId(RoleId.provided(roleId)).path(path); + AppRoleAuthenticationOptionsBuilder builder = AppRoleAuthenticationOptions.builder() + .roleId(RoleId.provided(roleId)).path(path); if (StringUtils.hasText(secretId)) { builder = builder.secretId(SecretId.provided(secretId)); @@ -364,9 +352,8 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration "Vault AWS-EC2 authentication: Role (vault.aws-ec2.role) must not be empty"); if (StringUtils.hasText(roleId) && StringUtils.hasText(role)) { - throw new IllegalStateException( - "AWS-EC2 Authentication: Only one of Role (vault.aws-ec2.role) or" - + " RoleId (deprecated, vault.aws-ec2.roleId) must be provided"); + throw new IllegalStateException("AWS-EC2 Authentication: Only one of Role (vault.aws-ec2.role) or" + + " RoleId (deprecated, vault.aws-ec2.roleId) must be provided"); } if (StringUtils.hasText(roleId)) { @@ -381,8 +368,7 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration builder.identityDocumentUri(URI.create(identityDocument)); } - return new AwsEc2Authentication(builder.build(), restOperations(), - restOperations()); + return new AwsEc2Authentication(builder.build(), restOperations(), restOperations()); } protected ClientAuthentication azureMsiAuthentication() { @@ -394,12 +380,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI); URI identityTokenServiceUri = getUri("vault.azure-msi.identity-token-service", AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI); - Assert.hasText(role, - "Vault Azure MSI authentication: Role (vault.azure-msi.role) must not be empty"); + Assert.hasText(role, "Vault Azure MSI authentication: Role (vault.azure-msi.role) must not be empty"); - AzureMsiAuthenticationOptionsBuilder builder = AzureMsiAuthenticationOptions - .builder().role(role).path(path).instanceMetadataUri(metadataServiceUri) - .identityTokenServiceUri(identityTokenServiceUri); + AzureMsiAuthenticationOptionsBuilder builder = AzureMsiAuthenticationOptions.builder().role(role).path(path) + .instanceMetadataUri(metadataServiceUri).identityTokenServiceUri(identityTokenServiceUri); return new AzureMsiAuthentication(builder.build(), restOperations()); } @@ -407,11 +391,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration protected ClientAuthentication cubbyholeAuthentication() { String token = getProperty("vault.token"); - Assert.hasText(token, - "Vault Cubbyhole authentication: Initial token (vault.token) must not be empty"); + Assert.hasText(token, "Vault Cubbyhole authentication: Initial token (vault.token) must not be empty"); - CubbyholeAuthenticationOptionsBuilder builder = CubbyholeAuthenticationOptions - .builder().wrapped().initialToken(VaultToken.of(token)); + CubbyholeAuthenticationOptionsBuilder builder = CubbyholeAuthenticationOptions.builder().wrapped() + .initialToken(VaultToken.of(token)); return new CubbyholeAuthentication(builder.build(), restOperations()); } @@ -426,11 +409,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration Assert.hasText(role, "Vault Kubernetes authentication: role must not be empty"); - KubernetesJwtSupplier jwtSupplier = new KubernetesServiceAccountTokenFile( - tokenFile); + KubernetesJwtSupplier jwtSupplier = new KubernetesServiceAccountTokenFile(tokenFile); - KubernetesAuthenticationOptionsBuilder builder = KubernetesAuthenticationOptions - .builder().role(role).jwtSupplier(jwtSupplier).path(path); + KubernetesAuthenticationOptionsBuilder builder = KubernetesAuthenticationOptions.builder().role(role) + .jwtSupplier(jwtSupplier).path(path); return new KubernetesAuthentication(builder.build(), restOperations()); } @@ -452,14 +434,19 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration private Resource getResource(String key) { String value = getProperty(key); - return value != null ? applicationContext.getResource(value) : null; + return value != null ? this.applicationContext.getResource(value) : null; } enum AppIdUserId { + IP_ADDRESS, MAC_ADDRESS; + } enum AuthenticationMethod { + TOKEN, APPID, APPROLE, AWS_EC2, AZURE, CERT, CUBBYHOLE, KUBERNETES; + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultOperations.java index 30669113..8e86db42 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultOperations.java @@ -52,7 +52,6 @@ public interface ReactiveVaultOperations { /** * Read from a Vault path. Reading data using this method is suitable for API * calls/secret backends that do not require a request body. - * * @param path must not be {@literal null}. * @return the data. May be empty if the path does not exist. */ @@ -61,7 +60,6 @@ public interface ReactiveVaultOperations { /** * Read from a Vault path. Reading data using this method is suitable for API * calls/secret backends that do not require a request body. - * * @param path must not be {@literal null}. * @param responseType must not be {@literal null}. * @return the data. May be empty if the path does not exist. @@ -70,7 +68,6 @@ public interface ReactiveVaultOperations { /** * Enumerate keys from a Vault path. - * * @param path must not be {@literal null}. * @return the data. May be empty if the path does not exist. */ @@ -78,7 +75,6 @@ public interface ReactiveVaultOperations { /** * Write to a Vault path. - * * @param path must not be {@literal null}. * @return the response. May be empty if the response has no body. */ @@ -88,7 +84,6 @@ public interface ReactiveVaultOperations { /** * Write to a Vault path. - * * @param path must not be {@literal null}. * @param body the body, may be {@literal null} if absent. * @return the response. May be empty if the response has no body. @@ -97,7 +92,6 @@ public interface ReactiveVaultOperations { /** * Delete a path. - * * @param path must not be {@literal null}. */ Mono delete(String path); @@ -106,30 +100,27 @@ public interface ReactiveVaultOperations { * Executes a Vault {@link RestOperationsCallback}. Allows to interact with Vault * using {@link org.springframework.web.client.RestOperations} without requiring a * session. - * * @param clientCallback the request. * @return the {@link RestOperationsCallback} return value. * @throws VaultException when a - * {@link org.springframework.web.client.HttpStatusCodeException} occurs. + * {@link org.springframework.web.client.HttpStatusCodeException} occurs. * @throws WebClientException exceptions from - * {@link org.springframework.web.reactive.function.client.WebClient}. + * {@link org.springframework.web.reactive.function.client.WebClient}. */ - > T doWithVault( - Function clientCallback) + > T doWithVault(Function clientCallback) throws VaultException, WebClientException; /** * Executes a Vault {@link RestOperationsCallback}. Allows to interact with Vault in * an authenticated session. - * * @param sessionCallback the request. * @return the {@link RestOperationsCallback} return value. * @throws VaultException when a - * {@link org.springframework.web.client.HttpStatusCodeException} occurs. + * {@link org.springframework.web.client.HttpStatusCodeException} occurs. * @throws WebClientException exceptions from - * {@link org.springframework.web.reactive.function.client.WebClient}. + * {@link org.springframework.web.reactive.function.client.WebClient}. */ - > T doWithSession( - Function sessionCallback) + > T doWithSession(Function sessionCallback) throws VaultException, WebClientException; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultTemplate.java index 84de9f40..3bd75e05 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/ReactiveVaultTemplate.java @@ -75,28 +75,24 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { * {@link VaultTokenSupplier}. It is intended for usage with Vault Agent to inherit * Vault Agent's authentication without using the {@link VaultHttpHeaders#VAULT_TOKEN * authentication token header}. - * * @param vaultEndpoint must not be {@literal null}. * @param connector must not be {@literal null}. * @since 2.2.1 */ - public ReactiveVaultTemplate(VaultEndpoint vaultEndpoint, - ClientHttpConnector connector) { + public ReactiveVaultTemplate(VaultEndpoint vaultEndpoint, ClientHttpConnector connector) { this(SimpleVaultEndpointProvider.of(vaultEndpoint), connector); } /** * Create a new {@link ReactiveVaultTemplate} with a {@link VaultEndpoint}, * {@link ClientHttpConnector} and {@link VaultTokenSupplier}. - * * @param vaultEndpoint must not be {@literal null}. * @param connector must not be {@literal null}. * @param vaultTokenSupplier must not be {@literal null}. */ - public ReactiveVaultTemplate(VaultEndpoint vaultEndpoint, - ClientHttpConnector connector, VaultTokenSupplier vaultTokenSupplier) { - this(SimpleVaultEndpointProvider.of(vaultEndpoint), connector, - vaultTokenSupplier); + public ReactiveVaultTemplate(VaultEndpoint vaultEndpoint, ClientHttpConnector connector, + VaultTokenSupplier vaultTokenSupplier) { + this(SimpleVaultEndpointProvider.of(vaultEndpoint), connector, vaultTokenSupplier); } /** @@ -105,13 +101,11 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { * {@link VaultTokenSupplier}. It is intended for usage with Vault Agent to inherit * Vault Agent's authentication without using the {@link VaultHttpHeaders#VAULT_TOKEN * authentication token header}. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @since 2.2.1 */ - public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, - ClientHttpConnector connector) { + public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpConnector connector) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); @@ -126,13 +120,12 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { /** * Create a new {@link ReactiveVaultTemplate} with a {@link VaultEndpointProvider}, * {@link ClientHttpConnector} and {@link VaultTokenSupplier}. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @param vaultTokenSupplier must not be {@literal null}. */ - public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, - ClientHttpConnector connector, VaultTokenSupplier vaultTokenSupplier) { + public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpConnector connector, + VaultTokenSupplier vaultTokenSupplier) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); @@ -148,7 +141,6 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { * constructor does not use a {@link VaultTokenSupplier}. It is intended for usage * with Vault Agent to inherit Vault Agent's authentication without using the * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}. - * * @param webClientBuilder must not be {@literal null}. * @since 2.2.1 */ @@ -166,21 +158,18 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { /** * Create a new {@link ReactiveVaultTemplate} through a {@link WebClientBuilder}, and * {@link VaultTokenSupplier}. - * * @param webClientBuilder must not be {@literal null}. * @param vaultTokenSupplier must not be {@literal null} * @since 2.2 */ - public ReactiveVaultTemplate(WebClientBuilder webClientBuilder, - VaultTokenSupplier vaultTokenSupplier) { + public ReactiveVaultTemplate(WebClientBuilder webClientBuilder, VaultTokenSupplier vaultTokenSupplier) { Assert.notNull(webClientBuilder, "WebClientBuilder must not be null"); Assert.notNull(vaultTokenSupplier, "VaultTokenSupplier must not be null"); this.vaultTokenSupplier = vaultTokenSupplier; this.statelessClient = webClientBuilder.build(); - this.sessionClient = webClientBuilder.build().mutate().filter(getSessionFilter()) - .build(); + this.sessionClient = webClientBuilder.build().mutate().filter(getSessionFilter()).build(); } /** @@ -189,20 +178,17 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { * {@link VaultEndpointProvider} is used to contribute host and port details for * relative URLs typically used by the Template API. Subclasses may override this * method to customize the {@link WebClient}. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @return the {@link WebClient} used for Vault communication. * @since 2.1 */ - protected WebClient doCreateWebClient(VaultEndpointProvider endpointProvider, - ClientHttpConnector connector) { + protected WebClient doCreateWebClient(VaultEndpointProvider endpointProvider, ClientHttpConnector connector) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); - return WebClientBuilder.builder().httpConnector(connector) - .endpointProvider(endpointProvider).build(); + return WebClientBuilder.builder().httpConnector(connector).endpointProvider(endpointProvider).build(); } /** @@ -212,7 +198,6 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { * {@link VaultEndpointProvider} is used to contribute host and port details for * relative URLs typically used by the Template API. Subclasses may override this * method to customize the {@link WebClient}. - * * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @return the {@link WebClient} used for Vault communication. @@ -226,19 +211,18 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { ExchangeFilterFunction filter = getSessionFilter(); - return WebClientBuilder.builder().httpConnector(connector) - .endpointProvider(endpointProvider).filter(filter).build(); + return WebClientBuilder.builder().httpConnector(connector).endpointProvider(endpointProvider).filter(filter) + .build(); } private ExchangeFilterFunction getSessionFilter() { - return ofRequestProcessor( - request -> vaultTokenSupplier.getVaultToken().map(token -> { + return ofRequestProcessor(request -> this.vaultTokenSupplier.getVaultToken().map(token -> { - return ClientRequest.from(request).headers(headers -> { - headers.set(VaultHttpHeaders.VAULT_TOKEN, token.getToken()); - }).build(); - })); + return ClientRequest.from(request).headers(headers -> { + headers.set(VaultHttpHeaders.VAULT_TOKEN, token.getToken()); + }).build(); + })); } @Override @@ -254,11 +238,9 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { return doWithSession(webClient -> { - ParameterizedTypeReference> ref = VaultResponses - .getTypeReference(responseType); + ParameterizedTypeReference> ref = VaultResponses.getTypeReference(responseType); - return webClient.get().uri(path).exchange() - .flatMap(mapResponse(ref, path, HttpMethod.GET)); + return webClient.get().uri(path).exchange().flatMap(mapResponse(ref, path, HttpMethod.GET)); }); } @@ -268,15 +250,11 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { Assert.hasText(path, "Path must not be empty"); - Mono read = doRead( - String.format("%s?list=true", path.endsWith("/") ? path : (path + "/")), + Mono read = doRead(String.format("%s?list=true", path.endsWith("/") ? path : (path + "/")), VaultListResponse.class); - return read - .filter(response -> response.getData() != null - && response.getData().containsKey("keys")) - .flatMapIterable(response -> (List) response.getRequiredData() - .get("keys")); + return read.filter(response -> response.getData() != null && response.getData().containsKey("keys")) + .flatMapIterable(response -> (List) response.getRequiredData().get("keys")); } @Override @@ -294,8 +272,7 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { else { exchange = uri.exchange(); } - return exchange - .flatMap(mapResponse(VaultResponse.class, path, HttpMethod.POST)); + return exchange.flatMap(mapResponse(VaultResponse.class, path, HttpMethod.POST)); }); } @@ -309,14 +286,13 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { } @Override - public > T doWithVault( - Function clientCallback) + public > T doWithVault(Function clientCallback) throws VaultException, WebClientException { Assert.notNull(clientCallback, "Client callback must not be null"); try { - return (T) clientCallback.apply(statelessClient); + return (T) clientCallback.apply(this.statelessClient); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); @@ -324,14 +300,13 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { } @Override - public > T doWithSession( - Function sessionCallback) + public > T doWithSession(Function sessionCallback) throws VaultException, WebClientException { Assert.notNull(sessionCallback, "Session callback must not be null"); try { - return (T) sessionCallback.apply(sessionClient); + return (T) sessionCallback.apply(this.sessionClient); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); @@ -341,21 +316,18 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { private Mono doRead(String path, Class responseType) { return doWithSession(client -> client.get() // - .uri(path).exchange() - .flatMap(mapResponse(responseType, path, HttpMethod.GET))); + .uri(path).exchange().flatMap(mapResponse(responseType, path, HttpMethod.GET))); } - private static Function> mapResponse( - Class bodyType, String path, HttpMethod method) { - return response -> isSuccess(response) ? response.bodyToMono(bodyType) - : mapOtherwise(response, path, method); + private static Function> mapResponse(Class bodyType, String path, + HttpMethod method) { + return response -> isSuccess(response) ? response.bodyToMono(bodyType) : mapOtherwise(response, path, method); } private static Function> mapResponse( ParameterizedTypeReference typeReference, String path, HttpMethod method) { - return response -> isSuccess(response) - ? response.body(BodyExtractors.toMono(typeReference)) + return response -> isSuccess(response) ? response.body(BodyExtractors.toMono(typeReference)) : mapOtherwise(response, path, method); } @@ -363,8 +335,7 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { return response.statusCode().is2xxSuccessful(); } - private static Mono mapOtherwise(ClientResponse response, - String path, HttpMethod method) { + private static Mono mapOtherwise(ClientResponse response, String path, HttpMethod method) { if (response.statusCode() == HttpStatus.NOT_FOUND && method == HttpMethod.GET) { return Mono.empty(); @@ -374,22 +345,23 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations { String error = VaultResponses.getError(body); - return Mono.error( - VaultResponses.buildException(response.statusCode(), path, error)); + return Mono.error(VaultResponses.buildException(response.statusCode(), path, error)); }); } - private static class VaultListResponse - extends VaultResponseSupport> { + private static class VaultListResponse extends VaultResponseSupport> { + } private enum NoTokenSupplier implements VaultTokenSupplier { + INSTANCE; @Override public Mono getVaultToken() { - return Mono - .error(new UnsupportedOperationException("Token retrieval disabled")); + return Mono.error(new UnsupportedOperationException("Token retrieval disabled")); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/RestOperationsCallback.java b/spring-vault-core/src/main/java/org/springframework/vault/core/RestOperationsCallback.java index febe86c9..225bfcc1 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/RestOperationsCallback.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/RestOperationsCallback.java @@ -28,10 +28,10 @@ public interface RestOperationsCallback { /** * Callback method. - * * @param restOperations restOperations to use, must not be {@literal null}. * @return a result object or null if none. */ @Nullable T doWithRestOperations(RestOperations restOperations); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue1Template.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue1Template.java index b5a3578c..e6fd22b2 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue1Template.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue1Template.java @@ -33,16 +33,15 @@ import org.springframework.vault.support.VaultResponseSupport; * @since 2.1 * @see KeyValueBackend#KV_1 */ -class VaultKeyValue1Template extends VaultKeyValueAccessor - implements VaultKeyValueOperations { +class VaultKeyValue1Template extends VaultKeyValueAccessor implements VaultKeyValueOperations { private final VaultOperations vaultOperations; + private final String path; /** * Create a new {@link VaultKeyValue1Template} given {@link VaultOperations} and the * mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -57,7 +56,7 @@ class VaultKeyValue1Template extends VaultKeyValueAccessor @Nullable @Override public List list(String path) { - return vaultOperations.list(createDataPath(path)); + return this.vaultOperations.list(createDataPath(path)); } @Nullable @@ -121,4 +120,5 @@ class VaultKeyValue1Template extends VaultKeyValueAccessor String createDataPath(String path) { return String.format("%s/%s", this.path, path); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Accessor.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Accessor.java index 07e29b79..bf8ca678 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Accessor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Accessor.java @@ -38,7 +38,6 @@ abstract class VaultKeyValue2Accessor extends VaultKeyValueAccessor { /** * Create a new {@link VaultKeyValue2Accessor} given {@link VaultOperations} and the * mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -54,13 +53,10 @@ abstract class VaultKeyValue2Accessor extends VaultKeyValueAccessor { @SuppressWarnings("unchecked") public List list(String path) { - String pathToUse = path.equals("/") ? "" - : path.endsWith("/") ? path : (path + "/"); + String pathToUse = path.equals("/") ? "" : path.endsWith("/") ? path : (path + "/"); VaultListResponse read = doRead(restOperations -> { - return restOperations.exchange( - String.format("%s?list=true", - createBackendPath("metadata", pathToUse)), + return restOperations.exchange(String.format("%s?list=true", createBackendPath("metadata", pathToUse)), HttpMethod.GET, null, VaultListResponse.class); }); @@ -87,4 +83,5 @@ abstract class VaultKeyValue2Accessor extends VaultKeyValueAccessor { String createBackendPath(String segment, String path) { return String.format("%s/%s/%s", this.path, segment, path); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Template.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Template.java index 65874366..d4448e45 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Template.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValue2Template.java @@ -30,13 +30,11 @@ import org.springframework.vault.support.VaultResponseSupport; * @author Mark Paluch * @since 2.1 */ -class VaultKeyValue2Template extends VaultKeyValue2Accessor - implements VaultKeyValueOperations { +class VaultKeyValue2Template extends VaultKeyValue2Accessor implements VaultKeyValueOperations { /** * Create a new {@link VaultKeyValue2Template} given {@link VaultOperations} and the * mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -90,4 +88,5 @@ class VaultKeyValue2Template extends VaultKeyValue2Accessor doWrite(createDataPath(path), Collections.singletonMap("data", body)); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueAccessor.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueAccessor.java index 12a9c268..dc24c372 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueAccessor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueAccessor.java @@ -60,7 +60,6 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { /** * Create a new {@link VaultKeyValueAccessor} given {@link VaultOperations} and the * mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -79,9 +78,8 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { Assert.hasText(path, "Path must not be empty"); - vaultOperations.doWithSession((restOperations -> { - restOperations.exchange(createDataPath(path), HttpMethod.DELETE, null, - Void.class); + this.vaultOperations.doWithSession((restOperations -> { + restOperations.exchange(createDataPath(path), HttpMethod.DELETE, null, Void.class); return null; })); @@ -90,18 +88,16 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { /** * Read a secret at {@code path} and deserialize the {@literal data} element to the * given {@link Class type}. - * * @param path must not be {@literal null}. * @param deserializeAs must not be {@literal null}. * @param mappingFunction Mapping function to convert from the intermediate to the - * target data type. Must not be {@literal null}. + * target data type. Must not be {@literal null}. * @param intermediate data type for {@literal data} deserialization. * @param return type. Value is created by the {@code mappingFunction}. * @return mapped value. */ @Nullable - T doRead(String path, Class deserializeAs, - BiFunction, I, T> mappingFunction) { + T doRead(String path, Class deserializeAs, BiFunction, I, T> mappingFunction) { ParameterizedTypeReference> ref = VaultResponses .getTypeReference(JsonNode.class); @@ -121,7 +117,6 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { /** * Read a secret at {@code path} and deserialize the {@literal data} element to the * given {@link ParameterizedTypeReference type}. - * * @param path must not be {@literal null} or empty. * @param typeReference must not be {@literal null} * @return mapped value. @@ -136,7 +131,6 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { /** * Deserialize a {@link JsonNode} to the requested {@link Class type}. - * * @param jsonNode must not be {@literal null}. * @param type must not be {@literal null}. * @return the deserialized object. @@ -144,7 +138,7 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { T deserialize(JsonNode jsonNode, Class type) { try { - return mapper.reader().readValue(jsonNode.traverse(), type); + return this.mapper.reader().readValue(jsonNode.traverse(), type); } catch (IOException e) { throw new VaultException("Cannot deserialize response", e); @@ -155,14 +149,13 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { * Perform a read action within a callback that gets access to a session-bound * {@link RestOperations} object. {@link HttpStatusCodeException} with * {@link HttpStatus#NOT_FOUND} are translated to a {@literal null} response. - * * @param callback must not be {@literal null}. * @return can be {@literal null}. */ @Nullable T doRead(Function> callback) { - return vaultOperations.doWithSession((restOperations) -> { + return this.vaultOperations.doWithSession((restOperations) -> { try { return callback.apply(restOperations).getBody(); @@ -173,14 +166,13 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { return null; } - throw VaultResponses.buildException(e, path); + throw VaultResponses.buildException(e, this.path); } }); } /** * Write the {@code body} to the given Vault {@code path}. - * * @param path must not be {@literal null} or empty. * @param body * @return the response of this write action. @@ -192,9 +184,9 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { try { - return vaultOperations.doWithSession((restOperations) -> { - return restOperations.exchange(path, HttpMethod.POST, - new HttpEntity<>(body), VaultResponse.class).getBody(); + return this.vaultOperations.doWithSession((restOperations) -> { + return restOperations.exchange(path, HttpMethod.POST, new HttpEntity<>(body), VaultResponse.class) + .getBody(); }); } catch (HttpStatusCodeException e) { @@ -204,7 +196,6 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { /** * Return the {@link JsonNode} that contains the actual response body. - * * @param response * @return */ @@ -224,14 +215,12 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { RestTemplate template = (RestTemplate) operations; - Optional jackson2Converter = template - .getMessageConverters().stream() - .filter(AbstractJackson2HttpMessageConverter.class::isInstance) // + Optional jackson2Converter = template.getMessageConverters() + .stream().filter(AbstractJackson2HttpMessageConverter.class::isInstance) // .map(AbstractJackson2HttpMessageConverter.class::cast) // .findFirst(); - return jackson2Converter - .map(AbstractJackson2HttpMessageConverter::getObjectMapper); + return jackson2Converter.map(AbstractJackson2HttpMessageConverter::getObjectMapper); } return Optional.empty(); @@ -239,4 +228,5 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport { return mapper.orElseGet(ObjectMapper::new); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperations.java index f2be3de5..6aefa861 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperations.java @@ -37,7 +37,6 @@ public interface VaultKeyValueOperations extends VaultKeyValueOperationsSupport /** * Read the secret at {@code path}. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -46,7 +45,6 @@ public interface VaultKeyValueOperations extends VaultKeyValueOperationsSupport /** * Read the secret at {@code path}. - * * @param path must not be {@literal null}. * @param responseType must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. @@ -56,9 +54,9 @@ public interface VaultKeyValueOperations extends VaultKeyValueOperationsSupport /** * Write the secret at {@code path}. - * * @param path must not be {@literal null}. * @param body must not be {@literal null}. */ void put(String path, Object body); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperationsSupport.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperationsSupport.java index e2b7d97a..37f0566c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperationsSupport.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultKeyValueOperationsSupport.java @@ -32,7 +32,6 @@ public interface VaultKeyValueOperationsSupport { /** * Enumerate keys from a Vault path. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -41,7 +40,6 @@ public interface VaultKeyValueOperationsSupport { /** * Read the secret at {@code path}. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -50,7 +48,6 @@ public interface VaultKeyValueOperationsSupport { /** * Delete the secret at {@code path}. - * * @param path must not be {@literal null}. */ void delete(String path); @@ -88,5 +85,7 @@ public interface VaultKeyValueOperationsSupport { public static KeyValueBackend versioned() { return KV_2; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultListResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultListResponse.java index 2fbc6d8e..b56a1b9b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultListResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultListResponse.java @@ -25,4 +25,5 @@ import org.springframework.vault.support.VaultResponseSupport; * @author Mark Paluch */ class VaultListResponse extends VaultResponseSupport> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java index f78bd847..ac170c41 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java @@ -46,7 +46,6 @@ public interface VaultOperations { /** * Return {@link VaultKeyValueOperations}. - * * @param path the mount path, must not be empty or {@literal null}. * @param apiVersion API version to use, must not be {@literal null}. * @return the operations interface to interact with the Vault Key/Value backend. @@ -56,7 +55,6 @@ public interface VaultOperations { /** * Return {@link VaultVersionedKeyValueOperations}. - * * @param path the mount path * @return the operations interface to interact with the versioned Vault Key/Value * (version 2) backend. @@ -72,7 +70,6 @@ public interface VaultOperations { /** * Return {@link VaultPkiOperations} if the PKI backend is mounted on a different path * than {@code pki}. - * * @param path the mount path * @return the operations interface to interact with the Vault PKI backend. */ @@ -96,7 +93,6 @@ public interface VaultOperations { /** * Return {@link VaultTransitOperations} if the transit backend is mounted on a * different path than {@code transit}. - * * @param path the mount path * @return the operations interface to interact with the Vault transit backend. */ @@ -112,7 +108,6 @@ public interface VaultOperations { /** * Read from a Vault path. Reading data using this method is suitable for API * calls/secret backends that do not require a request body. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -122,7 +117,6 @@ public interface VaultOperations { /** * Read from a secret backend. Reading data using this method is suitable for secret * backends that do not require a request body. - * * @param path must not be {@literal null}. * @param responseType must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. @@ -132,7 +126,6 @@ public interface VaultOperations { /** * Enumerate keys from a Vault path. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -141,7 +134,6 @@ public interface VaultOperations { /** * Write to a Vault path. - * * @param path must not be {@literal null}. * @return the response, may be {@literal null}. * @since 2.0 @@ -153,7 +145,6 @@ public interface VaultOperations { /** * Write to a Vault path. - * * @param path must not be {@literal null}. * @param body the body, may be {@literal null} if absent. * @return the response, may be {@literal null}. @@ -163,7 +154,6 @@ public interface VaultOperations { /** * Delete a path. - * * @param path must not be {@literal null}. */ void delete(String path); @@ -172,31 +162,27 @@ public interface VaultOperations { * Executes a Vault {@link RestOperationsCallback}. Allows to interact with Vault * using {@link org.springframework.web.client.RestOperations} without requiring a * session. - * * @param clientCallback the request. * @return the {@link RestOperationsCallback} return value. * @throws VaultException when a - * {@link org.springframework.web.client.HttpStatusCodeException} occurs. + * {@link org.springframework.web.client.HttpStatusCodeException} occurs. * @throws RestClientException exceptions from - * {@link org.springframework.web.client.RestOperations}. + * {@link org.springframework.web.client.RestOperations}. */ @Nullable - T doWithVault(RestOperationsCallback clientCallback) - throws VaultException, RestClientException; + T doWithVault(RestOperationsCallback clientCallback) throws VaultException, RestClientException; /** * Executes a Vault {@link RestOperationsCallback}. Allows to interact with Vault in * an authenticated session. - * * @param sessionCallback the request. * @return the {@link RestOperationsCallback} return value. * @throws VaultException when a - * {@link org.springframework.web.client.HttpStatusCodeException} occurs. + * {@link org.springframework.web.client.HttpStatusCodeException} occurs. * @throws RestClientException exceptions from - * {@link org.springframework.web.client.RestOperations}. + * {@link org.springframework.web.client.RestOperations}. */ @Nullable - T doWithSession(RestOperationsCallback sessionCallback) - throws VaultException, RestClientException; + T doWithSession(RestOperationsCallback sessionCallback) throws VaultException, RestClientException; } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java index d7adc213..1ca51e20 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java @@ -45,7 +45,6 @@ public interface VaultPkiOperations { * backend given a {@code roleName} and {@link VaultCertificateRequest}. The issuing * CA certificate is returned as well, so that only the root CA need be in a client's * trust store. Certificates use DER format and are base64 encoded. - * * @param roleName must not be empty or {@literal null}. * @param certificateRequest must not be {@literal null}. * @return the {@link VaultCertificateResponse} containing a {@link CertificateBundle} @@ -54,15 +53,14 @@ public interface VaultPkiOperations { * "https://www.vaultproject.io/docs/secrets/pki/index.html#pki-issue">POST * /pki/issue/[role name] */ - VaultCertificateResponse issueCertificate(String roleName, - VaultCertificateRequest certificateRequest) throws VaultException; + VaultCertificateResponse issueCertificate(String roleName, VaultCertificateRequest certificateRequest) + throws VaultException; /** * Signs a CSR using Vault's PKI backend given a {@code roleName}, {@code csr} and * {@link VaultCertificateRequest}. The issuing CA certificate is returned as well, so * that only the root CA need be in a client's trust store. Certificates use DER * format and are base64 encoded. - * * @param roleName must not be empty or {@literal null}. * @param csr must not be empty or {@literal null}. * @param certificateRequest must not be {@literal null}. @@ -73,14 +71,13 @@ public interface VaultPkiOperations { * "https://www.vaultproject.io/docs/secrets/pki/index.html#pki-issue">POST * /pki/sign/[role name] */ - VaultSignCertificateRequestResponse signCertificateRequest(String roleName, - String csr, VaultCertificateRequest certificateRequest) throws VaultException; + VaultSignCertificateRequestResponse signCertificateRequest(String roleName, String csr, + VaultCertificateRequest certificateRequest) throws VaultException; /** * Revokes a certificate using its serial number. This is an alternative option to the * standard method of revoking using Vault lease IDs. A successful revocation will * rotate the CRL - * * @param serialNumber must not be empty or {@literal null}. * @since 2.0 * @see * If Vault reports no content under the CRL URL, then the result of this method call * is {@literal null}. - * * @return {@link java.io.InputStream} containing the encoded CRL or {@literal null} * if Vault responds with 204 No Content. * @since 2.0 @@ -108,6 +104,9 @@ public interface VaultPkiOperations { InputStream getCrl(Encoding encoding) throws VaultException; enum Encoding { + DER, PEM, + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java index 8f41bdfb..d7047c9b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java @@ -48,7 +48,6 @@ public class VaultPkiTemplate implements VaultPkiOperations { /** * Create a new {@link VaultPkiTemplate} given {@link VaultOperations} and the mount * {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -62,20 +61,19 @@ public class VaultPkiTemplate implements VaultPkiOperations { } @Override - public VaultCertificateResponse issueCertificate(String roleName, - VaultCertificateRequest certificateRequest) throws VaultException { + public VaultCertificateResponse issueCertificate(String roleName, VaultCertificateRequest certificateRequest) + throws VaultException { Assert.hasText(roleName, "Role name must not be empty"); Assert.notNull(certificateRequest, "Certificate request must not be null"); - return requestCertificate(roleName, "{path}/issue/{roleName}", - createIssueRequest(certificateRequest), VaultCertificateResponse.class); + return requestCertificate(roleName, "{path}/issue/{roleName}", createIssueRequest(certificateRequest), + VaultCertificateResponse.class); } @Override - public VaultSignCertificateRequestResponse signCertificateRequest(String roleName, - String csr, VaultCertificateRequest certificateRequest) - throws VaultException { + public VaultSignCertificateRequestResponse signCertificateRequest(String roleName, String csr, + VaultCertificateRequest certificateRequest) throws VaultException { Assert.hasText(roleName, "Role name must not be empty"); Assert.hasText(csr, "CSR name must not be empty"); @@ -84,20 +82,18 @@ public class VaultPkiTemplate implements VaultPkiOperations { Map body = createIssueRequest(certificateRequest); body.put("csr", csr); - return requestCertificate(roleName, "{path}/sign/{roleName}", body, - VaultSignCertificateRequestResponse.class); + return requestCertificate(roleName, "{path}/sign/{roleName}", body, VaultSignCertificateRequestResponse.class); } - private T requestCertificate(String roleName, String requestPath, - Map request, Class responseType) { + private T requestCertificate(String roleName, String requestPath, Map request, + Class responseType) { request.put("format", "der"); - T response = vaultOperations.doWithSession(restOperations -> { + T response = this.vaultOperations.doWithSession(restOperations -> { try { - return restOperations.postForObject(requestPath, request, responseType, - path, roleName); + return restOperations.postForObject(requestPath, request, responseType, this.path, roleName); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); @@ -114,12 +110,11 @@ public class VaultPkiTemplate implements VaultPkiOperations { Assert.hasText(serialNumber, "Serial number must not be null or empty"); - vaultOperations.doWithSession(restOperations -> { + this.vaultOperations.doWithSession(restOperations -> { try { - restOperations.postForObject("{path}/revoke", - Collections.singletonMap("serial_number", serialNumber), - Map.class, path); + restOperations.postForObject("{path}/revoke", Collections.singletonMap("serial_number", serialNumber), + Map.class, this.path); return null; } @@ -134,13 +129,11 @@ public class VaultPkiTemplate implements VaultPkiOperations { Assert.notNull(encoding, "Encoding must not be null"); - return vaultOperations.doWithSession(restOperations -> { + return this.vaultOperations.doWithSession(restOperations -> { - String requestPath = encoding == Encoding.DER ? "{path}/crl" - : "{path}/crl/pem"; + String requestPath = encoding == Encoding.DER ? "{path}/crl" : "{path}/crl/pem"; try { - ResponseEntity response = restOperations.getForEntity(requestPath, - byte[].class, path); + ResponseEntity response = restOperations.getForEntity(requestPath, byte[].class, this.path); if (response.getStatusCode() == HttpStatus.OK) { return new ByteArrayInputStream(response.getBody()); @@ -157,12 +150,10 @@ public class VaultPkiTemplate implements VaultPkiOperations { /** * Create a request body stub for {@code pki/issue} and {@code pki/sign} from * {@link VaultCertificateRequest}. - * * @param certificateRequest must not be {@literal null}. * @return the body as {@link Map}. */ - private static Map createIssueRequest( - VaultCertificateRequest certificateRequest) { + private static Map createIssueRequest(VaultCertificateRequest certificateRequest) { Assert.notNull(certificateRequest, "Certificate request must not be null"); @@ -170,18 +161,17 @@ public class VaultPkiTemplate implements VaultPkiOperations { request.put("common_name", certificateRequest.getCommonName()); if (!certificateRequest.getAltNames().isEmpty()) { - request.put("alt_names", StringUtils - .collectionToDelimitedString(certificateRequest.getAltNames(), ",")); + request.put("alt_names", StringUtils.collectionToDelimitedString(certificateRequest.getAltNames(), ",")); } if (!certificateRequest.getIpSubjectAltNames().isEmpty()) { - request.put("ip_sans", StringUtils.collectionToDelimitedString( - certificateRequest.getIpSubjectAltNames(), ",")); + request.put("ip_sans", + StringUtils.collectionToDelimitedString(certificateRequest.getIpSubjectAltNames(), ",")); } if (!certificateRequest.getUriSubjectAltNames().isEmpty()) { - request.put("uri_sans", StringUtils.collectionToDelimitedString( - certificateRequest.getUriSubjectAltNames(), ",")); + request.put("uri_sans", + StringUtils.collectionToDelimitedString(certificateRequest.getUriSubjectAltNames(), ",")); } if (certificateRequest.getTtl() != null) { @@ -193,4 +183,5 @@ public class VaultPkiTemplate implements VaultPkiOperations { } return request; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java index 4a72a5c5..1a3efb20 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java @@ -43,14 +43,12 @@ public interface VaultSysOperations { /** * Initialize Vault with a {@link VaultInitializationRequest}. - * * @param vaultInitializationRequest must not be {@literal null}. * @return the {@link VaultInitializationResponse}. * @see PUT * /sys/init */ - VaultInitializationResponse initialize( - VaultInitializationRequest vaultInitializationRequest) throws VaultException; + VaultInitializationResponse initialize(VaultInitializationRequest vaultInitializationRequest) throws VaultException; /** * Seal vault. @@ -62,7 +60,6 @@ public interface VaultSysOperations { /** * Unseal vault. See {@link VaultUnsealStatus#getProgress()} for progress. - * * @param keyShare must not be empty and not {@literal null}. * @return the {@link VaultUnsealStatus}. * @see PUT @@ -79,7 +76,6 @@ public interface VaultSysOperations { /** * Mounts a secret backend {@link VaultMount} to {@code path}. - * * @param path must not be empty or {@literal null}. * @param vaultMount must not be {@literal null}. * @see POST @@ -96,7 +92,6 @@ public interface VaultSysOperations { /** * Unmounts the secret backend mount at {@code path}. - * * @param path must not be empty or {@literal null}. * @see DELETE * /sys/mounts/{mount} @@ -105,7 +100,6 @@ public interface VaultSysOperations { /** * Mounts an auth backend {@link VaultMount} to {@code path}. - * * @param path must not be empty or {@literal null}. * @param vaultMount must not be {@literal null}. * @see POST @@ -122,7 +116,6 @@ public interface VaultSysOperations { /** * Unmounts the auth backend mount at {@code path}. - * * @param path must not be empty or {@literal null}. * @see DELETE * /sys/auth/{mount} @@ -131,7 +124,6 @@ public interface VaultSysOperations { /** * Lists policy names stored in Vault. - * * @return policy names. * @since 2.0 * @see GET @@ -143,7 +135,6 @@ public interface VaultSysOperations { * Read a {@link Policy} by its {@literal name}. Policies are either represented as * HCL (HashiCorp configuration language) or JSON. Retrieving policies is only * possible if the policy is represented as JSON. - * * @return the {@link Policy} or {@literal null}, if the policy was not found. * @since 2.0 * @throws UnsupportedOperationException if the policy is represented as HCL. @@ -155,7 +146,6 @@ public interface VaultSysOperations { /** * Create or update a {@link Policy}. - * * @param name the policy name, must not be {@literal null} or empty. * @since 2.0 * @see PUT @@ -165,7 +155,6 @@ public interface VaultSysOperations { /** * Delete a {@link Policy} by its {@literal name}. - * * @param name the policy name, must not be {@literal null} or empty. * @since 2.0 * @see DELETE @@ -175,10 +164,10 @@ public interface VaultSysOperations { /** * Return the health status of Vault. - * * @return the {@link VaultHealth}. * @see GET * /sys/health */ VaultHealth health() throws VaultException; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java index 86305d0a..0b3d1505 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java @@ -86,7 +86,6 @@ public class VaultSysTemplate implements VaultSysOperations { /** * Create a new {@link VaultSysTemplate} with the given {@link VaultOperations}. - * * @param vaultOperations must not be {@literal null}. */ public VaultSysTemplate(VaultOperations vaultOperations) { @@ -101,15 +100,13 @@ public class VaultSysTemplate implements VaultSysOperations { @SuppressWarnings("unchecked") public boolean isInitialized() { - return requireResponse(vaultOperations.doWithSession(restOperations -> { + return requireResponse(this.vaultOperations.doWithSession(restOperations -> { try { - ResponseEntity> body = (ResponseEntity) restOperations - .exchange("sys/init", HttpMethod.GET, emptyNamespace(null), - Map.class); + ResponseEntity> body = (ResponseEntity) restOperations.exchange("sys/init", + HttpMethod.GET, emptyNamespace(null), Map.class); - Assert.state(body.getBody() != null, - "Initialization response must not be null"); + Assert.state(body.getBody() != null, "Initialization response must not be null"); return body.getBody().get("initialized"); } @@ -120,22 +117,18 @@ public class VaultSysTemplate implements VaultSysOperations { } @Override - public VaultInitializationResponse initialize( - VaultInitializationRequest vaultInitializationRequest) { + public VaultInitializationResponse initialize(VaultInitializationRequest vaultInitializationRequest) { - Assert.notNull(vaultInitializationRequest, - "VaultInitialization must not be null"); + Assert.notNull(vaultInitializationRequest, "VaultInitialization must not be null"); - return requireResponse(vaultOperations.doWithVault(restOperations -> { + return requireResponse(this.vaultOperations.doWithVault(restOperations -> { try { - ResponseEntity exchange = restOperations - .exchange("sys/init", HttpMethod.PUT, - emptyNamespace(vaultInitializationRequest), - VaultInitializationResponseImpl.class); + ResponseEntity exchange = restOperations.exchange("sys/init", + HttpMethod.PUT, emptyNamespace(vaultInitializationRequest), + VaultInitializationResponseImpl.class); - Assert.state(exchange.getBody() != null, - "Initialization response must not be null"); + Assert.state(exchange.getBody() != null, "Initialization response must not be null"); return exchange.getBody(); } @@ -147,18 +140,16 @@ public class VaultSysTemplate implements VaultSysOperations { @Override public void seal() { - vaultOperations.doWithSession(SEAL); + this.vaultOperations.doWithSession(SEAL); } @Override public VaultUnsealStatus unseal(String keyShare) { - return requireResponse(vaultOperations.doWithVault(restOperations -> { + return requireResponse(this.vaultOperations.doWithVault(restOperations -> { - ResponseEntity response = restOperations.exchange( - "sys/unseal", HttpMethod.PUT, - new HttpEntity(Collections.singletonMap("key", keyShare)), - VaultUnsealStatusImpl.class); + ResponseEntity response = restOperations.exchange("sys/unseal", HttpMethod.PUT, + new HttpEntity(Collections.singletonMap("key", keyShare)), VaultUnsealStatusImpl.class); Assert.state(response.getBody() != null, "Unseal response must not be null"); @@ -168,7 +159,7 @@ public class VaultSysTemplate implements VaultSysOperations { @Override public VaultUnsealStatus getUnsealStatus() { - return requireResponse(vaultOperations.doWithVault(GET_UNSEAL_STATUS)); + return requireResponse(this.vaultOperations.doWithVault(GET_UNSEAL_STATUS)); } @Override @@ -177,12 +168,12 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(path, "Path must not be empty"); Assert.notNull(vaultMount, "VaultMount must not be null"); - vaultOperations.write(String.format("sys/mounts/%s", path), vaultMount); + this.vaultOperations.write(String.format("sys/mounts/%s", path), vaultMount); } @Override public Map getMounts() { - return requireResponse(vaultOperations.doWithSession(GET_MOUNTS)); + return requireResponse(this.vaultOperations.doWithSession(GET_MOUNTS)); } @Override @@ -190,7 +181,7 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(path, "Path must not be empty"); - vaultOperations.delete(String.format("sys/mounts/%s", path)); + this.vaultOperations.delete(String.format("sys/mounts/%s", path)); } @Override @@ -199,12 +190,12 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(path, "Path must not be empty"); Assert.notNull(vaultMount, "VaultMount must not be null"); - vaultOperations.write(String.format("sys/auth/%s", path), vaultMount); + this.vaultOperations.write(String.format("sys/auth/%s", path), vaultMount); } @Override public Map getAuthMounts() throws VaultException { - return requireResponse(vaultOperations.doWithSession(GET_AUTH_MOUNTS)); + return requireResponse(this.vaultOperations.doWithSession(GET_AUTH_MOUNTS)); } @Override @@ -212,14 +203,14 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(path, "Path must not be empty"); - vaultOperations.delete(String.format("sys/auth/%s", path)); + this.vaultOperations.delete(String.format("sys/auth/%s", path)); } @Override @SuppressWarnings("unchecked") public List getPolicyNames() throws VaultException { - return requireResponse((List) vaultOperations.read("sys/policy") - .getRequiredData().get("policies")); + return requireResponse( + (List) this.vaultOperations.read("sys/policy").getRequiredData().get("policies")); } @Nullable @@ -228,13 +219,12 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(name, "Name must not be null or empty"); - return vaultOperations.doWithSession(restOperations -> { + return this.vaultOperations.doWithSession(restOperations -> { ResponseEntity response; try { - response = restOperations.getForEntity("sys/policy/{name}", - VaultResponse.class, name); + response = restOperations.getForEntity("sys/policy/{name}", VaultResponse.class, name); } catch (HttpStatusCodeException e) { @@ -274,11 +264,10 @@ public class VaultSysTemplate implements VaultSysOperations { throw new VaultException("Cannot serialize policy to JSON", e); } - vaultOperations.doWithSession(restOperations -> { + this.vaultOperations.doWithSession(restOperations -> { restOperations.exchange("sys/policy/{name}", HttpMethod.PUT, - new HttpEntity<>(Collections.singletonMap("rules", rules)), - VaultResponse.class, name); + new HttpEntity<>(Collections.singletonMap("rules", rules)), VaultResponse.class, name); return null; }); @@ -289,12 +278,12 @@ public class VaultSysTemplate implements VaultSysOperations { Assert.hasText(name, "Name must not be null or empty"); - vaultOperations.delete(String.format("sys/policy/%s", name)); + this.vaultOperations.delete(String.format("sys/policy/%s", name)); } @Override public VaultHealth health() { - return requireResponse(vaultOperations.doWithVault(HEALTH)); + return requireResponse(this.vaultOperations.doWithVault(HEALTH)); } private static T requireResponse(@Nullable T response) { @@ -304,14 +293,13 @@ public class VaultSysTemplate implements VaultSysOperations { return response; } - private static class GetUnsealStatus - implements RestOperationsCallback { + private static class GetUnsealStatus implements RestOperationsCallback { @Override public VaultUnsealStatus doWithRestOperations(RestOperations restOperations) { - return restOperations.getForObject("sys/seal-status", - VaultUnsealStatusImpl.class); + return restOperations.getForObject("sys/seal-status", VaultUnsealStatusImpl.class); } + } private static class Seal implements RestOperationsCallback { @@ -324,8 +312,7 @@ public class VaultSysTemplate implements VaultSysOperations { } - private static class GetMounts - implements RestOperationsCallback> { + private static class GetMounts implements RestOperationsCallback> { private static final ParameterizedTypeReference MOUNT_TYPE_REF = new ParameterizedTypeReference() { }; @@ -337,11 +324,10 @@ public class VaultSysTemplate implements VaultSysOperations { } @Override - public Map doWithRestOperations( - RestOperations restOperations) { + public Map doWithRestOperations(RestOperations restOperations) { - ResponseEntity exchange = restOperations.exchange(path, - HttpMethod.GET, null, MOUNT_TYPE_REF, Collections.emptyMap()); + ResponseEntity exchange = restOperations.exchange(this.path, HttpMethod.GET, null, + MOUNT_TYPE_REF, Collections.emptyMap()); VaultMountsResponse body = exchange.getBody(); @@ -354,14 +340,13 @@ public class VaultSysTemplate implements VaultSysOperations { return body.getTopLevelMounts(); } - private static class VaultMountsResponse - extends VaultResponseSupport> { + private static class VaultMountsResponse extends VaultResponseSupport> { private Map topLevelMounts = new HashMap<>(); @JsonIgnore public Map getTopLevelMounts() { - return topLevelMounts; + return this.topLevelMounts; } @SuppressWarnings("unchecked") @@ -386,10 +371,12 @@ public class VaultSysTemplate implements VaultSysOperations { VaultMount vaultMount = builder.build(); - topLevelMounts.put(name, vaultMount); + this.topLevelMounts.put(name, vaultMount); } } + } + } private static HttpEntity emptyNamespace(@Nullable T body) { @@ -404,23 +391,22 @@ public class VaultSysTemplate implements VaultSysOperations { public VaultHealth doWithRestOperations(RestOperations restOperations) { try { - ResponseEntity healthResponse = restOperations.exchange( - "sys/health", HttpMethod.GET, emptyNamespace(null), - VaultHealthImpl.class); + ResponseEntity healthResponse = restOperations.exchange("sys/health", HttpMethod.GET, + emptyNamespace(null), VaultHealthImpl.class); return healthResponse.getBody(); } catch (RestClientResponseException responseError) { try { ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(responseError.getResponseBodyAsString(), - VaultHealthImpl.class); + return mapper.readValue(responseError.getResponseBodyAsString(), VaultHealthImpl.class); } catch (Exception jsonError) { throw responseError; } } } + } static class VaultInitializationResponseImpl implements VaultInitializationResponse { @@ -434,7 +420,7 @@ public class VaultSysTemplate implements VaultSysOperations { } public VaultToken getRootToken() { - return VaultToken.of(rootToken); + return VaultToken.of(this.rootToken); } public List getKeys() { @@ -456,13 +442,14 @@ public class VaultSysTemplate implements VaultSysOperations { if (!(o instanceof VaultInitializationResponseImpl)) return false; VaultInitializationResponseImpl that = (VaultInitializationResponseImpl) o; - return keys.equals(that.keys) && rootToken.equals(that.rootToken); + return this.keys.equals(that.keys) && this.rootToken.equals(that.rootToken); } @Override public int hashCode() { - return Objects.hash(keys, rootToken); + return Objects.hash(this.keys, this.rootToken); } + } static class VaultUnsealStatusImpl implements VaultUnsealStatus { @@ -519,36 +506,40 @@ public class VaultSysTemplate implements VaultSysOperations { if (!(o instanceof VaultUnsealStatusImpl)) return false; VaultUnsealStatusImpl that = (VaultUnsealStatusImpl) o; - return sealed == that.sealed && secretThreshold == that.secretThreshold - && secretShares == that.secretShares && progress == that.progress; + return this.sealed == that.sealed && this.secretThreshold == that.secretThreshold + && this.secretShares == that.secretShares && this.progress == that.progress; } @Override public int hashCode() { - return Objects.hash(sealed, secretThreshold, secretShares, progress); + return Objects.hash(this.sealed, this.secretThreshold, this.secretShares, this.progress); } + } @JsonIgnoreProperties(ignoreUnknown = true) static class VaultHealthImpl implements VaultHealth { private final boolean initialized; + private final boolean sealed; + private final boolean standby; + private final boolean performanceStandby; + private final boolean replicationRecoverySecondary; + private final int serverTimeUtc; @Nullable private final String version; - VaultHealthImpl(@JsonProperty("initialized") boolean initialized, - @JsonProperty("sealed") boolean sealed, + VaultHealthImpl(@JsonProperty("initialized") boolean initialized, @JsonProperty("sealed") boolean sealed, @JsonProperty("standby") boolean standby, @JsonProperty("performance_standby") boolean performanceStandby, @Nullable @JsonProperty("replication_dr_mode") String replicationRecoverySecondary, - @JsonProperty("server_time_utc") int serverTimeUtc, - @Nullable @JsonProperty("version") String version) { + @JsonProperty("server_time_utc") int serverTimeUtc, @Nullable @JsonProperty("version") String version) { this.initialized = initialized; this.sealed = sealed; @@ -573,11 +564,11 @@ public class VaultSysTemplate implements VaultSysOperations { } public boolean isPerformanceStandby() { - return performanceStandby; + return this.performanceStandby; } public boolean isRecoveryReplicationSecondary() { - return replicationRecoverySecondary; + return this.replicationRecoverySecondary; } public int getServerTimeUtc() { @@ -596,18 +587,18 @@ public class VaultSysTemplate implements VaultSysOperations { if (!(o instanceof VaultHealthImpl)) return false; VaultHealthImpl that = (VaultHealthImpl) o; - return initialized == that.initialized && sealed == that.sealed - && standby == that.standby - && performanceStandby == that.performanceStandby - && replicationRecoverySecondary == that.replicationRecoverySecondary - && serverTimeUtc == that.serverTimeUtc - && Objects.equals(version, that.version); + return this.initialized == that.initialized && this.sealed == that.sealed && this.standby == that.standby + && this.performanceStandby == that.performanceStandby + && this.replicationRecoverySecondary == that.replicationRecoverySecondary + && this.serverTimeUtc == that.serverTimeUtc && Objects.equals(this.version, that.version); } @Override public int hashCode() { - return Objects.hash(initialized, sealed, standby, performanceStandby, - replicationRecoverySecondary, serverTimeUtc, version); + return Objects.hash(this.initialized, this.sealed, this.standby, this.performanceStandby, + this.replicationRecoverySecondary, this.serverTimeUtc, this.version); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTemplate.java index 3c21dacb..fd993289 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTemplate.java @@ -68,24 +68,20 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * does not use a {@link ClientAuthentication} mechanism. It is intended for usage * with Vault Agent to inherit Vault Agent's authentication without using the * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}. - * * @param vaultEndpoint must not be {@literal null}. * @since 2.2.1 */ public VaultTemplate(VaultEndpoint vaultEndpoint) { - this(SimpleVaultEndpointProvider.of(vaultEndpoint), - new SimpleClientHttpRequestFactory()); + this(SimpleVaultEndpointProvider.of(vaultEndpoint), new SimpleClientHttpRequestFactory()); } /** * Create a new {@link VaultTemplate} with a {@link VaultEndpoint} and * {@link ClientAuthentication}. - * * @param vaultEndpoint must not be {@literal null}. * @param clientAuthentication must not be {@literal null}. */ - public VaultTemplate(VaultEndpoint vaultEndpoint, - ClientAuthentication clientAuthentication) { + public VaultTemplate(VaultEndpoint vaultEndpoint, ClientAuthentication clientAuthentication) { Assert.notNull(vaultEndpoint, "VaultEndpoint must not be null"); Assert.notNull(clientAuthentication, "ClientAuthentication must not be null"); @@ -95,8 +91,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - VaultEndpointProvider endpointProvider = SimpleVaultEndpointProvider - .of(vaultEndpoint); + VaultEndpointProvider endpointProvider = SimpleVaultEndpointProvider.of(vaultEndpoint); this.statelessTemplate = doCreateRestTemplate(endpointProvider, requestFactory); this.sessionTemplate = doCreateSessionTemplate(endpointProvider, requestFactory); @@ -108,29 +103,24 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * {@link ClientAuthentication} mechanism. It is intended for usage with Vault Agent * to inherit Vault Agent's authentication without using the * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}. - * * @param vaultEndpoint must not be {@literal null}. * @param clientHttpRequestFactory must not be {@literal null}. * @since 2.2.1 */ - public VaultTemplate(VaultEndpoint vaultEndpoint, - ClientHttpRequestFactory clientHttpRequestFactory) { + public VaultTemplate(VaultEndpoint vaultEndpoint, ClientHttpRequestFactory clientHttpRequestFactory) { this(SimpleVaultEndpointProvider.of(vaultEndpoint), clientHttpRequestFactory); } /** * Create a new {@link VaultTemplate} with a {@link VaultEndpoint}, * {@link ClientHttpRequestFactory} and {@link SessionManager}. - * * @param vaultEndpoint must not be {@literal null}. * @param clientHttpRequestFactory must not be {@literal null}. * @param sessionManager must not be {@literal null}. */ - public VaultTemplate(VaultEndpoint vaultEndpoint, - ClientHttpRequestFactory clientHttpRequestFactory, + public VaultTemplate(VaultEndpoint vaultEndpoint, ClientHttpRequestFactory clientHttpRequestFactory, SessionManager sessionManager) { - this(SimpleVaultEndpointProvider.of(vaultEndpoint), clientHttpRequestFactory, - sessionManager); + this(SimpleVaultEndpointProvider.of(vaultEndpoint), clientHttpRequestFactory, sessionManager); } /** @@ -139,19 +129,16 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * not use a {@link ClientAuthentication} mechanism. It is intended for usage with * Vault Agent to inherit Vault Agent's authentication without using the * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}. - * * @param endpointProvider must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @since 2.2.1 */ - public VaultTemplate(VaultEndpointProvider endpointProvider, - ClientHttpRequestFactory requestFactory) { + public VaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(requestFactory, "ClientHttpRequestFactory must not be null"); - RestTemplate restTemplate = doCreateRestTemplate(endpointProvider, - requestFactory); + RestTemplate restTemplate = doCreateRestTemplate(endpointProvider, requestFactory); this.sessionManager = NoSessionManager.INSTANCE; this.dedicatedSessionManager = false; @@ -162,14 +149,13 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa /** * Create a new {@link VaultTemplate} with a {@link VaultEndpointProvider}, * {@link ClientHttpRequestFactory} and {@link SessionManager}. - * * @param endpointProvider must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @param sessionManager must not be {@literal null}. * @since 1.1 */ - public VaultTemplate(VaultEndpointProvider endpointProvider, - ClientHttpRequestFactory requestFactory, SessionManager sessionManager) { + public VaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory, + SessionManager sessionManager) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(requestFactory, "ClientHttpRequestFactory must not be null"); @@ -187,7 +173,6 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * {@link ClientAuthentication} mechanism. It is intended for usage with Vault Agent * to inherit Vault Agent's authentication without using the * {@link VaultHttpHeaders#VAULT_TOKEN authentication token header}. - * * @param restTemplateBuilder must not be {@literal null}. * @since 2.2.1 */ @@ -206,13 +191,11 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa /** * Create a new {@link VaultTemplate} through a {@link RestTemplateBuilder} and * {@link SessionManager}. - * * @param restTemplateBuilder must not be {@literal null}. * @param sessionManager must not be {@literal null}. * @since 2.2 */ - public VaultTemplate(RestTemplateBuilder restTemplateBuilder, - SessionManager sessionManager) { + public VaultTemplate(RestTemplateBuilder restTemplateBuilder, SessionManager sessionManager) { Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null"); Assert.notNull(sessionManager, "SessionManager must not be null"); @@ -231,7 +214,6 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * {@link ClientHttpRequestFactory}. {@link VaultEndpointProvider} is used to * contribute host and port details for relative URLs typically used by the Template * API. Subclasses may override this method to customize the {@link RestTemplate}. - * * @param endpointProvider must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @return the {@link RestTemplate} used for Vault communication. @@ -240,8 +222,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa protected RestTemplate doCreateRestTemplate(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) { - return RestTemplateBuilder.builder().endpointProvider(endpointProvider) - .requestFactory(requestFactory).build(); + return RestTemplateBuilder.builder().endpointProvider(endpointProvider).requestFactory(requestFactory).build(); } /** @@ -251,7 +232,6 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa * {@link VaultEndpointProvider} is used to contribute host and port details for * relative URLs typically used by the Template API. Subclasses may override this * method to customize the {@link RestTemplate}. - * * @param endpointProvider must not be {@literal null}. * @param requestFactory must not be {@literal null}. * @return the {@link RestTemplate} used for Vault communication. @@ -260,20 +240,17 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa protected RestTemplate doCreateSessionTemplate(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) { - return RestTemplateBuilder.builder().endpointProvider(endpointProvider) - .requestFactory(requestFactory).customizers(restTemplate -> restTemplate - .getInterceptors().add(getSessionInterceptor())) - .build(); + return RestTemplateBuilder.builder().endpointProvider(endpointProvider).requestFactory(requestFactory) + .customizers(restTemplate -> restTemplate.getInterceptors().add(getSessionInterceptor())).build(); } private ClientHttpRequestInterceptor getSessionInterceptor() { return (request, body, execution) -> { - Assert.notNull(sessionManager, "SessionManager must not be null"); + Assert.notNull(this.sessionManager, "SessionManager must not be null"); - request.getHeaders().add(VaultHttpHeaders.VAULT_TOKEN, - sessionManager.getSessionToken().getToken()); + request.getHeaders().add(VaultHttpHeaders.VAULT_TOKEN, this.sessionManager.getSessionToken().getToken()); return execution.execute(request, body); }; @@ -281,7 +258,6 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa /** * Set the {@link SessionManager}. - * * @param sessionManager must not be {@literal null}. */ public void setSessionManager(SessionManager sessionManager) { @@ -293,20 +269,19 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa @Override public void afterPropertiesSet() { - Assert.notNull(sessionManager, "SessionManager must not be null"); + Assert.notNull(this.sessionManager, "SessionManager must not be null"); } @Override public void destroy() throws Exception { - if (dedicatedSessionManager && sessionManager instanceof DisposableBean) { - ((DisposableBean) sessionManager).destroy(); + if (this.dedicatedSessionManager && this.sessionManager instanceof DisposableBean) { + ((DisposableBean) this.sessionManager).destroy(); } } @Override - public VaultKeyValueOperations opsForKeyValue(String path, - KeyValueBackend apiVersion) { + public VaultKeyValueOperations opsForKeyValue(String path, KeyValueBackend apiVersion) { switch (apiVersion) { case KV_1: @@ -372,14 +347,13 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa @Nullable public VaultResponseSupport read(String path, Class responseType) { - ParameterizedTypeReference> ref = VaultResponses - .getTypeReference(responseType); + ParameterizedTypeReference> ref = VaultResponses.getTypeReference(responseType); return doWithSession(restOperations -> { try { - ResponseEntity> exchange = restOperations - .exchange(path, HttpMethod.GET, null, ref); + ResponseEntity> exchange = restOperations.exchange(path, HttpMethod.GET, null, + ref); return exchange.getBody(); } @@ -401,8 +375,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa Assert.hasText(path, "Path must not be empty"); - VaultListResponse read = doRead( - String.format("%s?list=true", path.endsWith("/") ? path : (path + "/")), + VaultListResponse read = doRead(String.format("%s?list=true", path.endsWith("/") ? path : (path + "/")), VaultListResponse.class); if (read == null) { return Collections.emptyList(); @@ -417,8 +390,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa Assert.hasText(path, "Path must not be empty"); - return doWithSession(restOperations -> restOperations.postForObject(path, body, - VaultResponse.class)); + return doWithSession(restOperations -> restOperations.postForObject(path, body, VaultResponse.class)); } @Override @@ -450,7 +422,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa Assert.notNull(clientCallback, "Client callback must not be null"); try { - return clientCallback.doWithRestOperations(statelessTemplate); + return clientCallback.doWithRestOperations(this.statelessTemplate); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); @@ -463,7 +435,7 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa Assert.notNull(sessionCallback, "Session callback must not be null"); try { - return sessionCallback.doWithRestOperations(sessionTemplate); + return sessionCallback.doWithRestOperations(this.sessionTemplate); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); @@ -490,11 +462,14 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa } private enum NoSessionManager implements SessionManager { + INSTANCE; @Override public VaultToken getSessionToken() { throw new UnsupportedOperationException(); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenOperations.java index 42b9fefd..5d544732 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenOperations.java @@ -30,7 +30,6 @@ public interface VaultTokenOperations { /** * Create a new token. - * * @return a {@link VaultTokenResponse} * @see POST * /auth/token/create @@ -39,7 +38,6 @@ public interface VaultTokenOperations { /** * Create a new token for the given {@link VaultTokenRequest}. - * * @param request must not be {@literal null}. * @return a {@link VaultTokenResponse} * @see POST @@ -49,7 +47,6 @@ public interface VaultTokenOperations { /** * Create a new orphan token. - * * @return a {@link VaultTokenResponse} * @see POST * /auth/token/create-orphan @@ -58,7 +55,6 @@ public interface VaultTokenOperations { /** * Create a new orphan token for the given {@link VaultTokenRequest}. - * * @param request must not be {@literal null}. * @return a {@link VaultTokenResponse} * @see POST @@ -68,7 +64,6 @@ public interface VaultTokenOperations { /** * Renew a {@link VaultToken}. - * * @param vaultToken must not be {@literal null}. * @return a {@link VaultTokenResponse} * @see POST @@ -78,7 +73,6 @@ public interface VaultTokenOperations { /** * Revoke a {@link VaultToken}. - * * @param vaultToken must not be {@literal null}. * @see POST * /auth/token/revoke @@ -87,10 +81,10 @@ public interface VaultTokenOperations { /** * Revoke a {@link VaultToken} but not its child tokens. - * * @param vaultToken must not be {@literal null}. * @see POST * /auth/token/revoke-orphan */ void revokeOrphan(VaultToken vaultToken); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenTemplate.java index 310f0b70..fc5edf71 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTokenTemplate.java @@ -40,7 +40,6 @@ public class VaultTokenTemplate implements VaultTokenOperations { /** * Create a new {@link VaultTokenTemplate} with the given {@link VaultOperations}. - * * @param vaultOperations must not be {@literal null}. */ public VaultTokenTemplate(VaultOperations vaultOperations) { @@ -73,8 +72,7 @@ public class VaultTokenTemplate implements VaultTokenOperations { Assert.notNull(request, "VaultTokenRequest must not be null"); - return writeAndReturn("auth/token/create-orphan", request, - VaultTokenResponse.class); + return writeAndReturn("auth/token/create-orphan", request, VaultTokenResponse.class); } @Override @@ -101,17 +99,15 @@ public class VaultTokenTemplate implements VaultTokenOperations { writeToken("auth/token/revoke-orphan", vaultToken, VaultTokenResponse.class); } - private > T writeAndReturn(String path, - @Nullable Object body, Class responseType) { + private > T writeAndReturn(String path, @Nullable Object body, + Class responseType) { Assert.hasText(path, "Path must not be empty"); - T response = vaultOperations.doWithSession(restOperations -> { + T response = this.vaultOperations.doWithSession(restOperations -> { try { - ResponseEntity exchange = restOperations.exchange(path, - HttpMethod.POST, - body == null ? HttpEntity.EMPTY : new HttpEntity<>(body), - responseType); + ResponseEntity exchange = restOperations.exchange(path, HttpMethod.POST, + body == null ? HttpEntity.EMPTY : new HttpEntity<>(body), responseType); return exchange.getBody(); } @@ -130,13 +126,11 @@ public class VaultTokenTemplate implements VaultTokenOperations { Assert.hasText(path, "Path must not be empty"); - vaultOperations.doWithSession(restOperations -> { + this.vaultOperations.doWithSession(restOperations -> { try { restOperations.exchange(path, HttpMethod.POST, - new HttpEntity<>( - Collections.singletonMap("token", token.getToken())), - responseType); + new HttpEntity<>(Collections.singletonMap("token", token.getToken())), responseType); return null; } @@ -145,4 +139,5 @@ public class VaultTokenTemplate implements VaultTokenOperations { } }); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitOperations.java index bfc3bdae..c78ef8b9 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitOperations.java @@ -49,7 +49,6 @@ public interface VaultTransitOperations { /** * Create a new named encryption key given a {@code name}. - * * @param keyName must not be empty or {@literal null}. */ void createKey(String keyName); @@ -58,7 +57,6 @@ public interface VaultTransitOperations { * Create a new named encryption key given a {@code name} and * {@link VaultTransitKeyCreationRequest}. The key options set here cannot be changed * after key creation. - * * @param keyName must not be empty or {@literal null}. * @param createKeyRequest must not be {@literal null}. */ @@ -66,14 +64,12 @@ public interface VaultTransitOperations { /** * Get a {@link List} of transit key names. - * * @return {@link List} of transit key names. */ List getKeys(); /** * Create a new named encryption key given a {@code name}. - * * @param keyName must not be empty or {@literal null}. * @param keyConfiguration must not be {@literal null}. */ @@ -83,7 +79,6 @@ public interface VaultTransitOperations { * Returns the value of the named encryption key. Depending on the type of key, * different information may be returned. The key must be exportable to support this * operation. - * * @param keyName must not be empty or {@literal null}. * @param type must not be {@literal null}. * @return the {@link RawTransitKey}. @@ -93,7 +88,6 @@ public interface VaultTransitOperations { /** * Return information about a named encryption key. - * * @param keyName must not be empty or {@literal null}. * @return the {@link VaultTransitKey}. */ @@ -103,7 +97,6 @@ public interface VaultTransitOperations { /** * Deletes a named encryption key. It will no longer be possible to decrypt any data * encrypted with the named key. - * * @param keyName must not be empty or {@literal null}. */ void deleteKey(String keyName); @@ -112,7 +105,6 @@ public interface VaultTransitOperations { * Rotates the version of the named key. After rotation, new plaintext requests will * be encrypted with the new version of the key. To upgrade ciphertext to be encrypted * with the latest version of the key, use {@link #rewrap(String, String)}. - * * @param keyName must not be empty or {@literal null}. * @see #rewrap(String, String) */ @@ -120,7 +112,6 @@ public interface VaultTransitOperations { /** * Encrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be empty or {@literal null}. * @return cipher text. @@ -129,7 +120,6 @@ public interface VaultTransitOperations { /** * Encrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be {@literal null}. * @since 1.1 @@ -139,11 +129,10 @@ public interface VaultTransitOperations { /** * Encrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be empty or {@literal null}. * @param transitRequest must not be {@literal null}. Use - * {@link VaultTransitContext#empty()} if no request options provided. + * {@link VaultTransitContext#empty()} if no request options provided. * @return cipher text. */ String encrypt(String keyName, byte[] plaintext, VaultTransitContext transitRequest); @@ -151,10 +140,9 @@ public interface VaultTransitOperations { /** * Encrypts the provided batch of plaintext using the named key and context. The * encryption is done using transit backend's batch operation. - * * @param keyName must not be empty or {@literal null}. * @param batchRequest a list of {@link Plaintext} which includes plaintext and an - * optional context. + * optional context. * @return the encrypted result in the order of {@code batchRequest} plaintexts. * @since 1.1 */ @@ -162,7 +150,6 @@ public interface VaultTransitOperations { /** * Decrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param ciphertext must not be empty or {@literal null}. * @return plain text. @@ -171,7 +158,6 @@ public interface VaultTransitOperations { /** * Decrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param ciphertext must not be {@literal null}. * @return plain text. @@ -181,11 +167,10 @@ public interface VaultTransitOperations { /** * Decrypts the provided plaintext using the named key. - * * @param keyName must not be empty or {@literal null}. * @param ciphertext must not be empty or {@literal null}. * @param transitContext must not be {@literal null}. Use - * {@link VaultTransitContext#empty()} if no request options provided. + * {@link VaultTransitContext#empty()} if no request options provided. * @return cipher text. * @return plain text. */ @@ -194,11 +179,9 @@ public interface VaultTransitOperations { /** * Decrypts the provided barch of ciphertext using the named key and context. The* * decryption is done using transit backend's batch operation. - * - * * @param keyName must not be empty or {@literal null}. * @param batchRequest a list of {@link Ciphertext} which includes plaintext and an - * optional context. + * optional context. * @return the decrypted result in the order of {@code batchRequest} ciphertexts. * @since 1.1 */ @@ -208,7 +191,6 @@ public interface VaultTransitOperations { * Rewrap the provided ciphertext using the latest version of the named key. Because * this never returns plaintext, it is possible to delegate this functionality to * untrusted users or scripts. - * * @param keyName must not be empty or {@literal null}. * @param ciphertext must not be empty or {@literal null}. * @return cipher text. @@ -220,11 +202,10 @@ public interface VaultTransitOperations { * Rewrap the provided ciphertext using the latest version of the named key. Because * this never returns plaintext, it is possible to delegate this functionality to * untrusted users or scripts. - * * @param keyName must not be empty or {@literal null}. * @param ciphertext must not be empty or {@literal null}. * @param transitContext must not be {@literal null}. Use - * {@link VaultTransitContext#empty()} if no request options provided. + * {@link VaultTransitContext#empty()} if no request options provided. * @return cipher text. * @see #rotate(String) */ @@ -235,7 +216,6 @@ public interface VaultTransitOperations { * hash algorithm. The key can be of any type supported by transit; the raw key will * be marshaled into bytes to be used for the HMAC function. If the key is of a type * that supports rotation, the latest (current) version will be used. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be {@literal null}. * @return the digest of given data the default hash algorithm and the named key. @@ -249,7 +229,6 @@ public interface VaultTransitOperations { * key will be marshaled into bytes to be used for the HMAC function. If the key is of * a type that supports rotation, configured {@link VaultHmacRequest#getKeyVersion()} * will be used. - * * @param keyName must not be empty or {@literal null}. * @param request the {@link VaultHmacRequest}, must not be {@literal null}. * @return the digest of given data the default hash algorithm and the named key. @@ -261,7 +240,6 @@ public interface VaultTransitOperations { * Create a cryptographic signature using {@code keyName} of the given * {@link Plaintext} and the default hash algorithm. The key must be of a type that * supports signing. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be empty or {@literal null}. * @return Signature for {@link Plaintext}. @@ -273,7 +251,6 @@ public interface VaultTransitOperations { * Create a cryptographic signature using {@code keyName} of the given * {@link VaultSignRequest} and the specified hash algorithm. The key must be of a * type that supports signing. - * * @param keyName must not be empty or {@literal null}. * @param request {@link VaultSignRequest} must not be empty or {@literal null}. * @return Signature for {@link VaultSignRequest}. @@ -284,7 +261,6 @@ public interface VaultTransitOperations { /** * Verify the cryptographic signature using {@code keyName} of the given * {@link Plaintext} and {@link Signature}. - * * @param keyName must not be empty or {@literal null}. * @param plaintext must not be {@literal null}. * @param signature Signature to be verified, must not be {@literal null}. @@ -296,12 +272,12 @@ public interface VaultTransitOperations { /** * Verify the cryptographic signature using {@code keyName} of the given * {@link VaultSignRequest}. - * * @param keyName must not be empty or {@literal null}. * @param request {@link VaultSignatureVerificationRequest} must not be - * {@literal null}. + * {@literal null}. * @return the resulting {@link SignatureValidation}. * @since 2.0 */ SignatureValidation verify(String keyName, VaultSignatureVerificationRequest request); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitTemplate.java index 1baaf98a..46e6532a 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultTransitTemplate.java @@ -67,7 +67,6 @@ public class VaultTransitTemplate implements VaultTransitOperations { /** * Create a new {@link VaultTransitTemplate} given {@link VaultOperations} and the * mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -85,40 +84,33 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); - vaultOperations.write(String.format("%s/keys/%s", path, keyName), null); + this.vaultOperations.write(String.format("%s/keys/%s", this.path, keyName), null); } @Override - public void createKey(String keyName, - VaultTransitKeyCreationRequest createKeyRequest) { + public void createKey(String keyName, VaultTransitKeyCreationRequest createKeyRequest) { Assert.hasText(keyName, "Key name must not be empty"); - Assert.notNull(createKeyRequest, - "VaultTransitKeyCreationRequest must not be empty"); + Assert.notNull(createKeyRequest, "VaultTransitKeyCreationRequest must not be empty"); - vaultOperations.write(String.format("%s/keys/%s", path, keyName), - createKeyRequest); + this.vaultOperations.write(String.format("%s/keys/%s", this.path, keyName), createKeyRequest); } @Override public List getKeys() { - VaultResponse response = vaultOperations - .read(String.format("%s/keys?list=true", path)); + VaultResponse response = this.vaultOperations.read(String.format("%s/keys?list=true", this.path)); - return response == null ? Collections.emptyList() - : (List) response.getRequiredData().get("keys"); + return response == null ? Collections.emptyList() : (List) response.getRequiredData().get("keys"); } @Override - public void configureKey(String keyName, - VaultTransitKeyConfiguration keyConfiguration) { + public void configureKey(String keyName, VaultTransitKeyConfiguration keyConfiguration) { Assert.hasText(keyName, "Key name must not be empty"); Assert.notNull(keyConfiguration, "VaultKeyConfiguration must not be empty"); - vaultOperations.write(String.format("%s/keys/%s/config", path, keyName), - keyConfiguration); + this.vaultOperations.write(String.format("%s/keys/%s/config", this.path, keyName), keyConfiguration); } @Override @@ -128,9 +120,8 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); Assert.notNull(type, "Key type must not be null"); - VaultResponseSupport result = vaultOperations.read( - String.format("%s/export/%s/%s", path, type.getValue(), keyName), - RawTransitKeyImpl.class); + VaultResponseSupport result = this.vaultOperations + .read(String.format("%s/export/%s/%s", this.path, type.getValue(), keyName), RawTransitKeyImpl.class); return result != null ? result.getRequiredData() : null; } @@ -141,8 +132,8 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); - VaultResponseSupport result = vaultOperations.read( - String.format("%s/keys/%s", path, keyName), VaultTransitKeyImpl.class); + VaultResponseSupport result = this.vaultOperations + .read(String.format("%s/keys/%s", this.path, keyName), VaultTransitKeyImpl.class); if (result != null) { return result.getRequiredData(); @@ -156,7 +147,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); - vaultOperations.delete(String.format("%s/keys/%s", path, keyName)); + this.vaultOperations.delete(String.format("%s/keys/%s", this.path, keyName)); } @Override @@ -164,7 +155,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); - vaultOperations.write(String.format("%s/keys/%s/rotate", path, keyName), null); + this.vaultOperations.write(String.format("%s/keys/%s/rotate", this.path, keyName), null); } @Override @@ -177,8 +168,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { request.put("plaintext", Base64Utils.encodeToString(plaintext.getBytes())); - return (String) vaultOperations - .write(String.format("%s/encrypt/%s", path, keyName), request) + return (String) this.vaultOperations.write(String.format("%s/encrypt/%s", this.path, keyName), request) .getRequiredData().get("ciphertext"); } @@ -188,15 +178,13 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be empty"); Assert.notNull(plaintext, "Plaintext must not be null"); - String ciphertext = encrypt(keyName, plaintext.getPlaintext(), - plaintext.getContext()); + String ciphertext = encrypt(keyName, plaintext.getPlaintext(), plaintext.getContext()); return toCiphertext(ciphertext, plaintext.getContext()); } @Override - public String encrypt(String keyName, byte[] plaintext, - VaultTransitContext transitContext) { + public String encrypt(String keyName, byte[] plaintext, VaultTransitContext transitContext) { Assert.hasText(keyName, "Key name must not be empty"); Assert.notNull(plaintext, "Plaintext must not be null"); @@ -208,28 +196,23 @@ public class VaultTransitTemplate implements VaultTransitOperations { applyTransitOptions(transitContext, request); - return (String) vaultOperations - .write(String.format("%s/encrypt/%s", path, keyName), request) + return (String) this.vaultOperations.write(String.format("%s/encrypt/%s", this.path, keyName), request) .getRequiredData().get("ciphertext"); } @Override - public List encrypt(String keyName, - List batchRequest) { + public List<VaultEncryptionResult> encrypt(String keyName, List<Plaintext> batchRequest) { Assert.hasText(keyName, "Key name must not be empty"); - Assert.notEmpty(batchRequest, - "BatchRequest must not be null and must have at least one entry"); + Assert.notEmpty(batchRequest, "BatchRequest must not be null and must have at least one entry"); - List<Map<String, String>> batch = new ArrayList<>( - batchRequest.size()); + List<Map<String, String>> batch = new ArrayList<>(batchRequest.size()); for (Plaintext request : batchRequest) { Map<String, String> vaultRequest = new LinkedHashMap<>(2); - vaultRequest.put("plaintext", - Base64Utils.encodeToString(request.getPlaintext())); + vaultRequest.put("plaintext", Base64Utils.encodeToString(request.getPlaintext())); if (request.getContext() != null) { applyTransitOptions(request.getContext(), vaultRequest); @@ -238,8 +221,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { batch.add(vaultRequest); } - VaultResponse vaultResponse = vaultOperations.write( - String.format("%s/encrypt/%s", path, keyName), + VaultResponse vaultResponse = this.vaultOperations.write(String.format("%s/encrypt/%s", this.path, keyName), Collections.singletonMap("batch_input", batch)); return toEncryptionResults(vaultResponse, batchRequest); @@ -255,9 +237,8 @@ public class VaultTransitTemplate implements VaultTransitOperations { request.put("ciphertext", ciphertext); - String plaintext = (String) vaultOperations - .write(String.format("%s/decrypt/%s", path, keyName), request) - .getRequiredData().get("plaintext"); + String plaintext = (String) this.vaultOperations + .write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext"); return new String(Base64Utils.decodeFromString(plaintext)); } @@ -268,15 +249,13 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.hasText(keyName, "Key name must not be null"); Assert.notNull(ciphertext, "Ciphertext must not be null"); - byte[] plaintext = decrypt(keyName, ciphertext.getCiphertext(), - ciphertext.getContext()); + byte[] plaintext = decrypt(keyName, ciphertext.getCiphertext(), ciphertext.getContext()); return Plaintext.of(plaintext).with(ciphertext.getContext()); } @Override - public byte[] decrypt(String keyName, String ciphertext, - VaultTransitContext transitContext) { + public byte[] decrypt(String keyName, String ciphertext, VaultTransitContext transitContext) { Assert.hasText(keyName, "Key name must not be empty"); Assert.hasText(ciphertext, "Ciphertext must not be empty"); @@ -288,23 +267,19 @@ public class VaultTransitTemplate implements VaultTransitOperations { applyTransitOptions(transitContext, request); - String plaintext = (String) vaultOperations - .write(String.format("%s/decrypt/%s", path, keyName), request) - .getRequiredData().get("plaintext"); + String plaintext = (String) this.vaultOperations + .write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext"); return Base64Utils.decodeFromString(plaintext); } @Override - public List<VaultDecryptionResult> decrypt(String keyName, - List<Ciphertext> batchRequest) { + public List<VaultDecryptionResult> decrypt(String keyName, List<Ciphertext> batchRequest) { Assert.hasText(keyName, "Key name must not be empty"); - Assert.notEmpty(batchRequest, - "BatchRequest must not be null and must have at least one entry"); + Assert.notEmpty(batchRequest, "BatchRequest must not be null and must have at least one entry"); - List<Map<String, String>> batch = new ArrayList<>( - batchRequest.size()); + List<Map<String, String>> batch = new ArrayList<>(batchRequest.size()); for (Ciphertext request : batchRequest) { @@ -319,8 +294,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { batch.add(vaultRequest); } - VaultResponse vaultResponse = vaultOperations.write( - String.format("%s/decrypt/%s", path, keyName), + VaultResponse vaultResponse = this.vaultOperations.write(String.format("%s/decrypt/%s", this.path, keyName), Collections.singletonMap("batch_input", batch)); return toDecryptionResults(vaultResponse, batchRequest); @@ -335,14 +309,12 @@ public class VaultTransitTemplate implements VaultTransitOperations { Map<String, String> request = new LinkedHashMap<>(); request.put("ciphertext", ciphertext); - return (String) vaultOperations - .write(String.format("%s/rewrap/%s", path, keyName), request) + return (String) this.vaultOperations.write(String.format("%s/rewrap/%s", this.path, keyName), request) .getRequiredData().get("ciphertext"); } @Override - public String rewrap(String keyName, String ciphertext, - VaultTransitContext transitContext) { + public String rewrap(String keyName, String ciphertext, VaultTransitContext transitContext) { Assert.hasText(keyName, "Key name must not be empty"); Assert.hasText(ciphertext, "Ciphertext must not be empty"); @@ -354,8 +326,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { applyTransitOptions(transitContext, request); - return (String) vaultOperations - .write(String.format("%s/rewrap/%s", path, keyName), request) + return (String) this.vaultOperations.write(String.format("%s/rewrap/%s", this.path, keyName), request) .getRequiredData().get("ciphertext"); } @@ -377,8 +348,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.notNull(hmacRequest, "HMAC request must not be null"); Map<String, Object> request = new LinkedHashMap<>(); - request.put("input", - Base64Utils.encodeToString(hmacRequest.getPlaintext().getPlaintext())); + request.put("input", Base64Utils.encodeToString(hmacRequest.getPlaintext().getPlaintext())); if (StringUtils.hasText(hmacRequest.getAlgorithm())) { request.put("algorithm", hmacRequest.getAlgorithm()); @@ -388,8 +358,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { request.put("key_version ", hmacRequest.getKeyVersion()); } - String hmac = (String) vaultOperations - .write(String.format("%s/hmac/%s", path, keyName), request) + String hmac = (String) this.vaultOperations.write(String.format("%s/hmac/%s", this.path, keyName), request) .getRequiredData().get("hmac"); return Hmac.of(hmac); @@ -413,15 +382,13 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.notNull(signRequest, "Sign request must not be null"); Map<String, Object> request = new LinkedHashMap<>(); - request.put("input", - Base64Utils.encodeToString(signRequest.getPlaintext().getPlaintext())); + request.put("input", Base64Utils.encodeToString(signRequest.getPlaintext().getPlaintext())); if (StringUtils.hasText(signRequest.getAlgorithm())) { request.put("algorithm", signRequest.getAlgorithm()); } - String signature = (String) vaultOperations - .write(String.format("%s/sign/%s", path, keyName), request) + String signature = (String) this.vaultOperations.write(String.format("%s/sign/%s", this.path, keyName), request) .getRequiredData().get("signature"); return Signature.of(signature); @@ -434,22 +401,18 @@ public class VaultTransitTemplate implements VaultTransitOperations { Assert.notNull(plainText, "Plaintext must not be null"); Assert.notNull(signature, "Signature must not be null"); - VaultSignatureVerificationRequest request = VaultSignatureVerificationRequest - .create(plainText, signature); + VaultSignatureVerificationRequest request = VaultSignatureVerificationRequest.create(plainText, signature); return verify(keyName, request).isValid(); } @Override - public SignatureValidation verify(String keyName, - VaultSignatureVerificationRequest verificationRequest) { + public SignatureValidation verify(String keyName, VaultSignatureVerificationRequest verificationRequest) { Assert.hasText(keyName, "Key name must not be empty"); - Assert.notNull(verificationRequest, - "Signature verification request must not be null"); + Assert.notNull(verificationRequest, "Signature verification request must not be null"); Map<String, Object> request = new LinkedHashMap<>(); - request.put("input", Base64Utils - .encodeToString(verificationRequest.getPlaintext().getPlaintext())); + request.put("input", Base64Utils.encodeToString(verificationRequest.getPlaintext().getPlaintext())); if (verificationRequest.getHmac() != null) { request.put("hmac", verificationRequest.getHmac().getHmac()); @@ -463,20 +426,17 @@ public class VaultTransitTemplate implements VaultTransitOperations { request.put("algorithm", verificationRequest.getAlgorithm()); } - Map<String, Object> response = vaultOperations - .write(String.format("%s/verify/%s", path, keyName), request) - .getRequiredData(); + Map<String, Object> response = this.vaultOperations + .write(String.format("%s/verify/%s", this.path, keyName), request).getRequiredData(); - if (response.containsKey("valid") - && Boolean.valueOf("" + response.get("valid"))) { + if (response.containsKey("valid") && Boolean.valueOf("" + response.get("valid"))) { return SignatureValidation.valid(); } return SignatureValidation.invalid(); } - private static void applyTransitOptions(VaultTransitContext context, - Map<String, String> request) { + private static void applyTransitOptions(VaultTransitContext context, Map<String, String> request) { if (!ObjectUtils.isEmpty(context.getContext())) { request.put("context", Base64Utils.encodeToString(context.getContext())); @@ -487,11 +447,10 @@ public class VaultTransitTemplate implements VaultTransitOperations { } } - private static List<VaultEncryptionResult> toEncryptionResults( - VaultResponse vaultResponse, List<Plaintext> batchRequest) { + private static List<VaultEncryptionResult> toEncryptionResults(VaultResponse vaultResponse, + List<Plaintext> batchRequest) { - List<VaultEncryptionResult> result = new ArrayList<>( - batchRequest.size()); + List<VaultEncryptionResult> result = new ArrayList<>(batchRequest.size()); List<Map<String, String>> batchData = getBatchData(vaultResponse); for (int i = 0; i < batchRequest.size(); i++) { @@ -502,17 +461,14 @@ public class VaultTransitTemplate implements VaultTransitOperations { Map<String, String> data = batchData.get(i); if (StringUtils.hasText(data.get("error"))) { - encrypted = new VaultEncryptionResult( - new VaultException(data.get("error"))); + encrypted = new VaultEncryptionResult(new VaultException(data.get("error"))); } else { - encrypted = new VaultEncryptionResult( - toCiphertext(data.get("ciphertext"), plaintext.getContext())); + encrypted = new VaultEncryptionResult(toCiphertext(data.get("ciphertext"), plaintext.getContext())); } } else { - encrypted = new VaultEncryptionResult( - new VaultException("No result for plaintext #" + i)); + encrypted = new VaultEncryptionResult(new VaultException("No result for plaintext #" + i)); } result.add(encrypted); @@ -521,11 +477,10 @@ public class VaultTransitTemplate implements VaultTransitOperations { return result; } - private static List<VaultDecryptionResult> toDecryptionResults( - VaultResponse vaultResponse, List<Ciphertext> batchRequest) { + private static List<VaultDecryptionResult> toDecryptionResults(VaultResponse vaultResponse, + List<Ciphertext> batchRequest) { - List<VaultDecryptionResult> result = new ArrayList<>( - batchRequest.size()); + List<VaultDecryptionResult> result = new ArrayList<>(batchRequest.size()); List<Map<String, String>> batchData = getBatchData(vaultResponse); for (int i = 0; i < batchRequest.size(); i++) { @@ -537,8 +492,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { encrypted = getDecryptionResult(batchData.get(i), ciphertext); } else { - encrypted = new VaultDecryptionResult( - new VaultException("No result for ciphertext #" + i)); + encrypted = new VaultDecryptionResult(new VaultException("No result for ciphertext #" + i)); } result.add(encrypted); @@ -547,8 +501,7 @@ public class VaultTransitTemplate implements VaultTransitOperations { return result; } - private static VaultDecryptionResult getDecryptionResult(Map<String, String> data, - Ciphertext ciphertext) { + private static VaultDecryptionResult getDecryptionResult(Map<String, String> data, Ciphertext ciphertext) { if (StringUtils.hasText(data.get("error"))) { return new VaultDecryptionResult(new VaultException(data.get("error"))); @@ -557,23 +510,19 @@ public class VaultTransitTemplate implements VaultTransitOperations { if (StringUtils.hasText(data.get("plaintext"))) { byte[] plaintext = Base64Utils.decodeFromString(data.get("plaintext")); - return new VaultDecryptionResult( - Plaintext.of(plaintext).with(ciphertext.getContext())); + return new VaultDecryptionResult(Plaintext.of(plaintext).with(ciphertext.getContext())); } return new VaultDecryptionResult(Plaintext.empty().with(ciphertext.getContext())); } - private static Ciphertext toCiphertext(String ciphertext, - @Nullable VaultTransitContext context) { - return context != null ? Ciphertext.of(ciphertext).with(context) - : Ciphertext.of(ciphertext); + private static Ciphertext toCiphertext(String ciphertext, @Nullable VaultTransitContext context) { + return context != null ? Ciphertext.of(ciphertext).with(context) : Ciphertext.of(ciphertext); } @SuppressWarnings("unchecked") private static List<Map<String, String>> getBatchData(VaultResponse vaultResponse) { - return (List<Map<String, String>>) vaultResponse.getRequiredData() - .get("batch_results"); + return (List<Map<String, String>>) vaultResponse.getRequiredData().get("batch_results"); } static class VaultTransitKeyImpl implements VaultTransitKey { @@ -767,27 +716,26 @@ public class VaultTransitTemplate implements VaultTransitOperations { if (!(o instanceof VaultTransitKeyImpl)) return false; VaultTransitKeyImpl that = (VaultTransitKeyImpl) o; - return deletionAllowed == that.deletionAllowed && derived == that.derived - && exportable == that.exportable - && latestVersion == that.latestVersion - && minDecryptionVersion == that.minDecryptionVersion - && minEncryptionVersion == that.minEncryptionVersion - && supportsDecryption == that.supportsDecryption - && supportsEncryption == that.supportsEncryption - && supportsDerivation == that.supportsDerivation - && supportsSigning == that.supportsSigning - && Objects.equals(name, that.name) - && cipherMode.equals(that.cipherMode) - && Objects.equals(type, that.type) && keys.equals(that.keys); + return this.deletionAllowed == that.deletionAllowed && this.derived == that.derived + && this.exportable == that.exportable && this.latestVersion == that.latestVersion + && this.minDecryptionVersion == that.minDecryptionVersion + && this.minEncryptionVersion == that.minEncryptionVersion + && this.supportsDecryption == that.supportsDecryption + && this.supportsEncryption == that.supportsEncryption + && this.supportsDerivation == that.supportsDerivation + && this.supportsSigning == that.supportsSigning && Objects.equals(this.name, that.name) + && this.cipherMode.equals(that.cipherMode) && Objects.equals(this.type, that.type) + && this.keys.equals(that.keys); } @Override public int hashCode() { - return Objects.hash(name, cipherMode, type, deletionAllowed, derived, - exportable, keys, latestVersion, minDecryptionVersion, - minEncryptionVersion, supportsDecryption, supportsEncryption, - supportsDerivation, supportsSigning); + return Objects.hash(this.name, this.cipherMode, this.type, this.deletionAllowed, this.derived, + this.exportable, this.keys, this.latestVersion, this.minDecryptionVersion, + this.minEncryptionVersion, this.supportsDecryption, this.supportsEncryption, + this.supportsDerivation, this.supportsSigning); } + } static class RawTransitKeyImpl implements RawTransitKey { @@ -824,12 +772,12 @@ public class VaultTransitTemplate implements VaultTransitOperations { if (!(o instanceof RawTransitKeyImpl)) return false; RawTransitKeyImpl that = (RawTransitKeyImpl) o; - return keys.equals(that.keys) && Objects.equals(name, that.name); + return this.keys.equals(that.keys) && Objects.equals(this.name, that.name); } @Override public int hashCode() { - return Objects.hash(keys, name); + return Objects.hash(this.keys, this.name); } } @@ -838,9 +786,10 @@ public class VaultTransitTemplate implements VaultTransitOperations { public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [vaultOperations=").append(vaultOperations); - sb.append(", path='").append(path).append('\''); + sb.append(" [vaultOperations=").append(this.vaultOperations); + sb.append(", path='").append(this.path).append('\''); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueOperations.java index 838cef70..7230b4bf 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueOperations.java @@ -40,7 +40,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Read the most recent secret at {@code path}. - * * @param path must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. */ @@ -51,7 +50,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Read the requested {@link Version} of the secret at {@code path}. - * * @param path must not be {@literal null}. * @param version must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. @@ -62,7 +60,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Read the most recent secret at {@code path} and deserialize the secret to the given * {@link Class responseType}. - * * @param path must not be {@literal null}. * @param responseType must not be {@literal null}. * @return the data. May be {@literal null} if the path does not exist. @@ -75,7 +72,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Read the requested {@link Version} of the secret at {@code path} and deserialize * the secret to the given {@link Class responseType}. - * * @param path must not be {@literal null}. * @param version must not be {@literal null}. * @param responseType must not be {@literal null}. @@ -88,7 +84,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation * Write the {@link Versioned versioned secret} at {@code path}. {@code body} may be * either plain secrets (e.g. map) or {@link Versioned} objects. Using * {@link Versioned} will apply versioning for Compare-and-Set (CAS). - * * @param path must not be {@literal null}. * @param body must not be {@literal null}. * @return the resulting {@link Metadata}. @@ -97,7 +92,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Delete one or more {@link Version versions} of the secret at {@code path}. - * * @param path must not be {@literal null}. * @param versionsToDelete must not be {@literal null} or empty. */ @@ -106,7 +100,6 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Undelete (restore) one or more {@link Version versions} of the secret at * {@code path}. - * * @param path must not be {@literal null}. * @param versionsToDelete must not be {@literal null} or empty. */ @@ -115,9 +108,9 @@ public interface VaultVersionedKeyValueOperations extends VaultKeyValueOperation /** * Permanently remove the specified {@link Version versions} of the secret at * {@code path}. - * * @param path must not be {@literal null}. * @param versionsToDelete must not be {@literal null} or empty. */ void destroy(String path, Version... versionsToDelete); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueTemplate.java index eaf75274..d929d436 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultVersionedKeyValueTemplate.java @@ -48,15 +48,13 @@ import org.springframework.web.client.HttpStatusCodeException; * @author Maciej Drozdzowski * @since 2.1 */ -public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor - implements VaultVersionedKeyValueOperations { +public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor implements VaultVersionedKeyValueOperations { private final VaultOperations vaultOperations; /** * Create a new {@link VaultVersionedKeyValueTemplate} given {@link VaultOperations} * and the mount {@code path}. - * * @param vaultOperations must not be {@literal null}. * @param path must not be empty or {@literal null}. */ @@ -93,23 +91,19 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor private <T> Versioned<T> doRead(String path, Version version, Class<T> responseType) { String secretPath = version.isVersioned() - ? String.format("%s?version=%d", createDataPath(path), - version.getVersion()) - : createDataPath(path); + ? String.format("%s?version=%d", createDataPath(path), version.getVersion()) : createDataPath(path); - VersionedResponse response = vaultOperations.doWithSession(restOperations -> { + VersionedResponse response = this.vaultOperations.doWithSession(restOperations -> { try { - return restOperations.exchange(secretPath, HttpMethod.GET, null, - VersionedResponse.class).getBody(); + return restOperations.exchange(secretPath, HttpMethod.GET, null, VersionedResponse.class).getBody(); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { if (e.getResponseBodyAsString().contains("deletion_time")) { - return VaultResponses.unwrap(e.getResponseBodyAsString(), - VersionedResponse.class); + return VaultResponses.unwrap(e.getResponseBodyAsString(), VersionedResponse.class); } return null; @@ -185,8 +179,7 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor } @Nullable - private static TemporalAccessor getDate(Map<String, Object> responseMetadata, - String key) { + private static TemporalAccessor getDate(Map<String, Object> responseMetadata, String key) { String date = (String) responseMetadata.getOrDefault(key, ""); if (StringUtils.hasText(date)) { @@ -208,13 +201,12 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor List<Integer> versions = toVersionList(versionsToDelete); - doWrite(createBackendPath("delete", path), - Collections.singletonMap("versions", versions)); + doWrite(createBackendPath("delete", path), Collections.singletonMap("versions", versions)); } private static List<Integer> toVersionList(Version[] versionsToDelete) { - return Arrays.stream(versionsToDelete).filter(Version::isVersioned) - .map(Version::getVersion).collect(Collectors.toList()); + return Arrays.stream(versionsToDelete).filter(Version::isVersioned).map(Version::getVersion) + .collect(Collectors.toList()); } @Override @@ -225,8 +217,7 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor List<Integer> versions = toVersionList(versionsToDelete); - doWrite(createBackendPath("undelete", path), - Collections.singletonMap("versions", versions)); + doWrite(createBackendPath("undelete", path), Collections.singletonMap("versions", versions)); } @Override @@ -237,11 +228,11 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor List<Integer> versions = toVersionList(versionsToDelete); - doWrite(createBackendPath("destroy", path), - Collections.singletonMap("versions", versions)); + doWrite(createBackendPath("destroy", path), Collections.singletonMap("versions", versions)); } - private static class VersionedResponse - extends VaultResponseSupport<VaultResponseSupport<JsonNode>> { + private static class VersionedResponse extends VaultResponseSupport<VaultResponseSupport<JsonNode>> { + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingOperations.java index 150f936e..b995ae5d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingOperations.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingOperations.java @@ -35,7 +35,6 @@ public interface VaultWrappingOperations { /** * Looks up {@link WrappedMetadata metadata} for the given token containing a wrapped * response. - * * @param token must not be {@literal null}. * @return the {@link WrappedMetadata} the {@code token} or {@literal null} if the * token was invalid or expired. @@ -45,7 +44,6 @@ public interface VaultWrappingOperations { /** * Read a wrapped secret. - * * @param token must not be {@literal null}. * @return the data or {@literal null} if the token was invalid or expired. */ @@ -54,7 +52,6 @@ public interface VaultWrappingOperations { /** * Read a wrapped secret of type {@link Class responseType}. - * * @param token must not be {@literal null}. * @param responseType must not be {@literal null}. * @return the data or {@literal null} if the token was invalid or expired. @@ -68,7 +65,6 @@ public interface VaultWrappingOperations { * invalidated. This can be used for long-term storage of a secret in a * response-wrapped token when rotation is a requirement. Rewrapping with an invalid * token throws {@link VaultException}. - * * @param token must not be {@literal null}. * @return the {@link WrappedMetadata} for this wrapping operation. */ @@ -76,7 +72,6 @@ public interface VaultWrappingOperations { /** * Wraps the given user-supplied data inside a response-wrapped token. - * * @param body must not be {@literal null}. * @param ttl must not be {@literal null}. * @return the {@link WrappedMetadata} for this wrapping operation. diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingTemplate.java index 3671c390..f5e36ef4 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultWrappingTemplate.java @@ -50,7 +50,6 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { /** * Create a new {@link VaultWrappingTemplate} given {@link VaultOperations}. - * * @param vaultOperations must not be {@literal null}. */ public VaultWrappingTemplate(VaultOperations vaultOperations) { @@ -68,7 +67,7 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { VaultResponse response = null; try { - response = vaultOperations.write("sys/wrapping/lookup", + response = this.vaultOperations.write("sys/wrapping/lookup", Collections.singletonMap("token", token.getToken())); } catch (VaultException e) { @@ -92,8 +91,8 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { public VaultResponse read(VaultToken token) { return doUnwrap(token, (restOperations, entity) -> { - return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, - VaultResponse.class).getBody(); + return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, VaultResponse.class) + .getBody(); }); } @@ -101,13 +100,10 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { @Override public <T> VaultResponseSupport<T> read(VaultToken token, Class<T> responseType) { - ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses - .getTypeReference(responseType); + ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses.getTypeReference(responseType); return doUnwrap(token, (restOperations, entity) -> { - return restOperations - .exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, ref) - .getBody(); + return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, ref).getBody(); }); } @@ -115,11 +111,10 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { private <T extends VaultResponseSupport<?>> T doUnwrap(VaultToken token, BiFunction<RestOperations, HttpEntity<?>, T> requestFunction) { - return vaultOperations.doWithVault(restOperations -> { + return this.vaultOperations.doWithVault(restOperations -> { try { - return requestFunction.apply(restOperations, - new HttpEntity<>(VaultHttpHeaders.from(token))); + return requestFunction.apply(restOperations, new HttpEntity<>(VaultHttpHeaders.from(token))); } catch (HttpStatusCodeException e) { @@ -142,7 +137,7 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { Assert.notNull(token, "token VaultToken not be null"); - VaultResponse response = vaultOperations.write("sys/wrapping/rewrap", + VaultResponse response = this.vaultOperations.write("sys/wrapping/rewrap", Collections.singletonMap("token", token.getToken())); Map<String, String> wrapInfo = response.getWrapInfo(); @@ -156,15 +151,13 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { Assert.notNull(body, "Body must not be null"); Assert.notNull(duration, "TTL duration must not be null"); - VaultResponse response = vaultOperations.doWithSession(restOperations -> { + VaultResponse response = this.vaultOperations.doWithSession(restOperations -> { HttpHeaders headers = new HttpHeaders(); headers.add("X-Vault-Wrap-TTL", Long.toString(duration.getSeconds())); - return restOperations - .exchange("sys/wrapping/wrap", HttpMethod.POST, - new HttpEntity<>(body, headers), VaultResponse.class) - .getBody(); + return restOperations.exchange("sys/wrapping/wrap", HttpMethod.POST, new HttpEntity<>(body, headers), + VaultResponse.class).getBody(); }); Map<String, String> wrapInfo = response.getWrapInfo(); @@ -172,8 +165,7 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { return getWrappedMetadata(wrapInfo, VaultToken.of(wrapInfo.get("token"))); } - private static WrappedMetadata getWrappedMetadata(Map<String, ?> wrapInfo, - VaultToken token) { + private static WrappedMetadata getWrappedMetadata(Map<String, ?> wrapInfo, VaultToken token) { TemporalAccessor creation_time = getDate(wrapInfo, "creation_time"); String path = (String) wrapInfo.get("creation_path"); @@ -187,9 +179,7 @@ public class VaultWrappingTemplate implements VaultWrappingOperations { String date = (String) ((Map) responseMetadata).getOrDefault(key, ""); - return StringUtils.hasText(date) - ? DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(date) - : null; + return StringUtils.hasText(date) ? DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(date) : null; } @Nullable diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySource.java b/spring-vault-core/src/main/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySource.java index d9076966..508d4134 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySource.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySource.java @@ -51,11 +51,9 @@ import org.springframework.vault.support.JsonMapFlattener; * @see PropertyTransformer * @see PropertyTransformers */ -public class LeaseAwareVaultPropertySource - extends EnumerablePropertySource<VaultOperations> { +public class LeaseAwareVaultPropertySource extends EnumerablePropertySource<VaultOperations> { - private static final Log logger = LogFactory - .getLog(LeaseAwareVaultPropertySource.class); + private static final Log logger = LogFactory.getLog(LeaseAwareVaultPropertySource.class); private final SecretLeaseContainer secretLeaseContainer; @@ -79,12 +77,10 @@ public class LeaseAwareVaultPropertySource * {@link SecretLeaseContainer} and {@link RequestedSecret}. This property source * requests the secret upon initialization and receives secrets once they are emitted * through events published by {@link SecretLeaseContainer}. - * * @param secretLeaseContainer must not be {@literal null}. * @param requestedSecret must not be {@literal null}. */ - public LeaseAwareVaultPropertySource(SecretLeaseContainer secretLeaseContainer, - RequestedSecret requestedSecret) { + public LeaseAwareVaultPropertySource(SecretLeaseContainer secretLeaseContainer, RequestedSecret requestedSecret) { this(requestedSecret.getPath(), secretLeaseContainer, requestedSecret); } @@ -93,13 +89,12 @@ public class LeaseAwareVaultPropertySource * {@link SecretLeaseContainer} and {@link RequestedSecret}. This property source * requests the secret upon initialization and receives secrets once they are emitted * through events published by {@link SecretLeaseContainer}. - * * @param name name of the property source, must not be {@literal null}. * @param secretLeaseContainer must not be {@literal null}. * @param requestedSecret must not be {@literal null}. */ - public LeaseAwareVaultPropertySource(String name, - SecretLeaseContainer secretLeaseContainer, RequestedSecret requestedSecret) { + public LeaseAwareVaultPropertySource(String name, SecretLeaseContainer secretLeaseContainer, + RequestedSecret requestedSecret) { this(name, secretLeaseContainer, requestedSecret, PropertyTransformers.noop()); } @@ -108,16 +103,14 @@ public class LeaseAwareVaultPropertySource * {@link SecretLeaseContainer} and {@link RequestedSecret}. This property source * requests the secret upon initialization and receives secrets once they are emitted * through events published by {@link SecretLeaseContainer}. - * * @param name name of the property source, must not be {@literal null}. * @param secretLeaseContainer must not be {@literal null}. * @param requestedSecret must not be {@literal null}. * @param propertyTransformer object to transform properties. * @see PropertyTransformers */ - public LeaseAwareVaultPropertySource(String name, - SecretLeaseContainer secretLeaseContainer, RequestedSecret requestedSecret, - PropertyTransformer propertyTransformer) { + public LeaseAwareVaultPropertySource(String name, SecretLeaseContainer secretLeaseContainer, + RequestedSecret requestedSecret, PropertyTransformer propertyTransformer) { this(name, secretLeaseContainer, requestedSecret, propertyTransformer, true); } @@ -127,37 +120,32 @@ public class LeaseAwareVaultPropertySource * {@link SecretLeaseContainer} and {@link RequestedSecret}. This property source * requests the secret upon initialization and receives secrets once they are emitted * through events published by {@link SecretLeaseContainer}. - * * @param name name of the property source, must not be {@literal null}. * @param secretLeaseContainer must not be {@literal null}. * @param requestedSecret must not be {@literal null}. * @param propertyTransformer object to transform properties. * @param ignoreSecretNotFound indicate if failure to find a secret at {@code path} - * should be ignored. + * should be ignored. * @since 2.2 * @see PropertyTransformers */ - public LeaseAwareVaultPropertySource(String name, - SecretLeaseContainer secretLeaseContainer, RequestedSecret requestedSecret, - PropertyTransformer propertyTransformer, boolean ignoreSecretNotFound) { + public LeaseAwareVaultPropertySource(String name, SecretLeaseContainer secretLeaseContainer, + RequestedSecret requestedSecret, PropertyTransformer propertyTransformer, boolean ignoreSecretNotFound) { super(name); - Assert.notNull(secretLeaseContainer, - "Path name must contain at least one character"); + Assert.notNull(secretLeaseContainer, "Path name must contain at least one character"); Assert.notNull(requestedSecret, "SecretLeaseContainer must not be null"); Assert.notNull(propertyTransformer, "PropertyTransformer must not be null"); this.secretLeaseContainer = secretLeaseContainer; this.requestedSecret = requestedSecret; - this.propertyTransformer = propertyTransformer - .andThen(PropertyTransformers.removeNullProperties()); + this.propertyTransformer = propertyTransformer.andThen(PropertyTransformers.removeNullProperties()); this.ignoreSecretNotFound = ignoreSecretNotFound; this.leaseListener = new LeaseListenerAdapter() { @Override public void onLeaseEvent(SecretLeaseEvent leaseEvent) { - handleLeaseEvent(leaseEvent, - LeaseAwareVaultPropertySource.this.properties); + handleLeaseEvent(leaseEvent, LeaseAwareVaultPropertySource.this.properties); } @Override @@ -175,24 +163,22 @@ public class LeaseAwareVaultPropertySource private void loadProperties() { if (logger.isDebugEnabled()) { - logger.debug(String.format("Requesting secrets from Vault at %s using %s", - requestedSecret.getPath(), requestedSecret.getMode())); + logger.debug(String.format("Requesting secrets from Vault at %s using %s", this.requestedSecret.getPath(), + this.requestedSecret.getMode())); } - secretLeaseContainer.addLeaseListener(leaseListener); - secretLeaseContainer.addErrorListener(leaseListener); - secretLeaseContainer.addRequestedSecret(requestedSecret); + this.secretLeaseContainer.addLeaseListener(this.leaseListener); + this.secretLeaseContainer.addErrorListener(this.leaseListener); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); Exception loadError = this.loadError; - if (notFound || loadError != null) { + if (this.notFound || loadError != null) { - String msg = String.format("Vault location [%s] not resolvable", - requestedSecret.getPath()); + String msg = String.format("Vault location [%s] not resolvable", this.requestedSecret.getPath()); - if (ignoreSecretNotFound) { + if (this.ignoreSecretNotFound) { if (logger.isInfoEnabled()) { - logger.info(String.format("%s: %s", msg, - loadError != null ? loadError.getMessage() : "Not found")); + logger.info(String.format("%s: %s", msg, loadError != null ? loadError.getMessage() : "Not found")); } } else { @@ -205,7 +191,7 @@ public class LeaseAwareVaultPropertySource } public RequestedSecret getRequestedSecret() { - return requestedSecret; + return this.requestedSecret; } @Override @@ -226,12 +212,10 @@ public class LeaseAwareVaultPropertySource /** * Hook method to handle a {@link SecretLeaseEvent}. - * * @param leaseEvent must not be {@literal null}. * @param properties reference to property storage of this property source. */ - protected void handleLeaseEvent(SecretLeaseEvent leaseEvent, - Map<String, Object> properties) { + protected void handleLeaseEvent(SecretLeaseEvent leaseEvent, Map<String, Object> properties) { if (leaseEvent.getSource() != getRequestedSecret()) { return; @@ -241,8 +225,7 @@ public class LeaseAwareVaultPropertySource this.notFound = true; } - if (leaseEvent instanceof SecretLeaseExpiredEvent - || leaseEvent instanceof BeforeSecretLeaseRevocationEvent + if (leaseEvent instanceof SecretLeaseExpiredEvent || leaseEvent instanceof BeforeSecretLeaseRevocationEvent || leaseEvent instanceof SecretLeaseCreatedEvent) { properties.clear(); } @@ -256,12 +239,10 @@ public class LeaseAwareVaultPropertySource /** * Hook method to handle a {@link SecretLeaseEvent} errors. - * * @param leaseEvent must not be {@literal null}. * @param exception offending exception. */ - protected void handleLeaseErrorEvent(SecretLeaseEvent leaseEvent, - Exception exception) { + protected void handleLeaseErrorEvent(SecretLeaseEvent leaseEvent, Exception exception) { if (leaseEvent.getSource() != getRequestedSecret()) { return; @@ -272,7 +253,6 @@ public class LeaseAwareVaultPropertySource /** * Hook method to transform properties using {@link PropertyTransformer}. - * * @param properties must not be {@literal null}. * @return the transformed properties. */ @@ -283,7 +263,6 @@ public class LeaseAwareVaultPropertySource /** * Utility method converting a {@code String/Object} map to a flat * {@code String/String} map. Nested objects are represented with property paths. - * * @param data the map * @return the flattened map. * @deprecated since 2.0, use {@link #flattenMap(Map)} to retain JSON data types. @@ -296,7 +275,6 @@ public class LeaseAwareVaultPropertySource /** * Utility method converting a {@code String/Object} map to a flat * {@code String/Object} map. Nested objects are represented with property path keys. - * * @param data the map * @return the flattened map. * @since 2.0 @@ -304,4 +282,5 @@ public class LeaseAwareVaultPropertySource protected Map<String, Object> flattenMap(Map<String, Object> data) { return JsonMapFlattener.flatten(data); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySource.java b/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySource.java index be3723e2..ad88490d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySource.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySource.java @@ -65,10 +65,9 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation * Create a new {@link VaultPropertySource} given a {@link VaultTemplate} and * {@code path} inside of Vault. This property source loads properties upon * construction. - * * @param vaultOperations must not be {@literal null}. * @param path the path inside Vault (e.g. {@code secret/myapp/myproperties}. Must not - * be empty or {@literal null}. + * be empty or {@literal null}. */ public VaultPropertySource(VaultOperations vaultOperations, String path) { this(path, vaultOperations, path); @@ -78,14 +77,12 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation * Create a new {@link VaultPropertySource} given a {@code name}, * {@link VaultTemplate} and {@code path} inside of Vault. This property source loads * properties upon construction. - * * @param name name of the property source, must not be {@literal null}. * @param vaultOperations must not be {@literal null}. * @param path the path inside Vault (e.g. {@code secret/myapp/myproperties}. Must not - * be empty or {@literal null}. + * be empty or {@literal null}. */ - public VaultPropertySource(String name, VaultOperations vaultOperations, - String path) { + public VaultPropertySource(String name, VaultOperations vaultOperations, String path) { this(name, vaultOperations, path, PropertyTransformers.noop()); } @@ -94,11 +91,10 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation * {@link VaultTemplate} and {@code path} inside of Vault. This property source loads * properties upon construction and transforms these by applying * {@link PropertyTransformer}. - * * @param name name of the property source, must not be {@literal null}. * @param vaultOperations must not be {@literal null}. * @param path the path inside Vault (e.g. {@code secret/myapp/myproperties}. Must not - * be empty or {@literal null}. + * be empty or {@literal null}. * @param propertyTransformer object to transform properties. * @see PropertyTransformers */ @@ -112,14 +108,13 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation * {@link VaultTemplate} and {@code path} inside of Vault. This property source loads * properties upon construction and transforms these by applying * {@link PropertyTransformer}. - * * @param name name of the property source, must not be {@literal null}. * @param vaultOperations must not be {@literal null}. * @param path the path inside Vault (e.g. {@code secret/myapp/myproperties}. Must not - * be empty or {@literal null}. + * be empty or {@literal null}. * @param propertyTransformer object to transform properties. * @param ignoreSecretNotFound indicate if failure to find a secret at {@code path} - * should be ignored. + * should be ignored. * @since 2.2 * @see PropertyTransformers */ @@ -134,8 +129,7 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation this.path = path; this.keyValueDelegate = new KeyValueDelegate(vaultOperations, LinkedHashMap::new); - this.propertyTransformer = propertyTransformer - .andThen(PropertyTransformers.removeNullProperties()); + this.propertyTransformer = propertyTransformer.andThen(PropertyTransformers.removeNullProperties()); this.ignoreSecretNotFound = ignoreSecretNotFound; loadProperties(); @@ -146,16 +140,16 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation */ protected void loadProperties() { - synchronized (lock) { + synchronized (this.lock) { if (logger.isDebugEnabled()) { - logger.debug(String.format("Fetching properties from Vault at %s", path)); + logger.debug(String.format("Fetching properties from Vault at %s", this.path)); } Map<String, Object> properties = null; RuntimeException error = null; try { - properties = doGetProperties(path); + properties = doGetProperties(this.path); } catch (RuntimeException e) { error = e; @@ -163,12 +157,11 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation if (properties == null) { - String msg = String.format("Vault location [%s] not resolvable", path); + String msg = String.format("Vault location [%s] not resolvable", this.path); - if (ignoreSecretNotFound) { + if (this.ignoreSecretNotFound) { if (logger.isInfoEnabled()) { - logger.info(String.format("%s: %s", msg, - error != null ? error.getMessage() : "Not found")); + logger.info(String.format("%s: %s", msg, error != null ? error.getMessage() : "Not found")); } } else { @@ -202,7 +195,6 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation /** * Hook method to obtain properties from Vault. - * * @param path the path, must not be empty or {@literal null}. * @return the resulting {@link Map} or {@literal null} if properties were not found. * @throws VaultException on problems retrieving properties @@ -232,7 +224,6 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation /** * Hook method to transform properties using {@link PropertyTransformer}. - * * @param properties must not be {@literal null}. * @return the transformed properties. */ @@ -243,7 +234,6 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation /** * Utility method converting a {@code String/Object} map to a flat * {@code String/String} map. - * * @param data the map * @return the flattened map. * @deprecated since 2.0, use {@link #flattenMap(Map)} to retain JSON data types. @@ -256,7 +246,6 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation /** * Utility method converting a {@code String/Object} map to a flat * {@code String/Object} map. Nested objects are represented with property path keys. - * * @param data the map * @return the flattened map. * @since 2.0 @@ -264,4 +253,5 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation protected Map<String, Object> flattenMap(Map<String, Object> data) { return JsonMapFlattener.flatten(data); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySourceNotFoundException.java b/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySourceNotFoundException.java index 1d7ce381..b2acf51f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySourceNotFoundException.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/env/VaultPropertySourceNotFoundException.java @@ -30,7 +30,6 @@ public class VaultPropertySourceNotFoundException extends VaultException { /** * Create a {@code VaultPropertySourceNotFoundException} with the specified detail * message. - * * @param msg the detail message. */ public VaultPropertySourceNotFoundException(String msg) { @@ -40,11 +39,11 @@ public class VaultPropertySourceNotFoundException extends VaultException { /** * Create a {@code VaultPropertySourceNotFoundException} with the specified detail * message and nested exception. - * * @param msg the detail message. * @param cause the nested exception. */ public VaultPropertySourceNotFoundException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/LeaseEndpoints.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/LeaseEndpoints.java index 00afb941..3bb68443 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/LeaseEndpoints.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/LeaseEndpoints.java @@ -44,8 +44,7 @@ public enum LeaseEndpoints { @Override public void revoke(Lease lease, RestOperations operations) { - operations.exchange("sys/revoke", HttpMethod.PUT, - LeaseEndpoints.getLeaseRevocationBody(lease), Map.class, + operations.exchange("sys/revoke", HttpMethod.PUT, LeaseEndpoints.getLeaseRevocationBody(lease), Map.class, lease.getLeaseId()); } @@ -55,11 +54,10 @@ public enum LeaseEndpoints { HttpEntity<Object> leaseRenewalEntity = getLeaseRenewalBody(lease); - ResponseEntity<Map<String, Object>> entity = (ResponseEntity) operations - .exchange("sys/renew", HttpMethod.PUT, leaseRenewalEntity, Map.class); + ResponseEntity<Map<String, Object>> entity = (ResponseEntity) operations.exchange("sys/renew", + HttpMethod.PUT, leaseRenewalEntity, Map.class); - Assert.state(entity != null && entity.getBody() != null, - "Renew response must not be null"); + Assert.state(entity != null && entity.getBody() != null, "Renew response must not be null"); return toLease(entity.getBody()); } @@ -73,9 +71,8 @@ public enum LeaseEndpoints { @Override public void revoke(Lease lease, RestOperations operations) { - operations.exchange("sys/leases/revoke", HttpMethod.PUT, - LeaseEndpoints.getLeaseRevocationBody(lease), Map.class, - lease.getLeaseId()); + operations.exchange("sys/leases/revoke", HttpMethod.PUT, LeaseEndpoints.getLeaseRevocationBody(lease), + Map.class, lease.getLeaseId()); } @Override @@ -84,12 +81,10 @@ public enum LeaseEndpoints { HttpEntity<Object> leaseRenewalEntity = getLeaseRenewalBody(lease); - ResponseEntity<Map<String, Object>> entity = (ResponseEntity) operations - .exchange("sys/leases/renew", HttpMethod.PUT, leaseRenewalEntity, - Map.class); + ResponseEntity<Map<String, Object>> entity = (ResponseEntity) operations.exchange("sys/leases/renew", + HttpMethod.PUT, leaseRenewalEntity, Map.class); - Assert.state(entity != null && entity.getBody() != null, - "Renew response must not be null"); + Assert.state(entity != null && entity.getBody() != null, "Renew response must not be null"); return toLease(entity.getBody()); } @@ -97,7 +92,6 @@ public enum LeaseEndpoints { /** * Revoke a {@link Lease}. - * * @param lease must not be {@literal null}. * @param operations must not be {@literal null}. */ @@ -105,7 +99,6 @@ public enum LeaseEndpoints { /** * Renew a {@link Lease} and return the renewed {@link Lease}. - * * @param lease must not be {@literal null}. * @param operations must not be {@literal null}. * @return the renewed {@link Lease}. @@ -118,17 +111,14 @@ public enum LeaseEndpoints { Number leaseDuration = (Number) body.get("lease_duration"); boolean renewable = (Boolean) body.get("renewable"); - return Lease.of(leaseId, - Duration.ofSeconds(leaseDuration != null ? leaseDuration.longValue() : 0), - renewable); + return Lease.of(leaseId, Duration.ofSeconds(leaseDuration != null ? leaseDuration.longValue() : 0), renewable); } private static HttpEntity<Object> getLeaseRenewalBody(Lease lease) { Map<String, String> leaseRenewalData = new HashMap<>(); leaseRenewalData.put("lease_id", lease.getLeaseId()); - leaseRenewalData.put("increment", - Long.toString(lease.getLeaseDuration().getSeconds())); + leaseRenewalData.put("increment", Long.toString(lease.getLeaseDuration().getSeconds())); return new HttpEntity<>(leaseRenewalData); } @@ -140,4 +130,5 @@ public enum LeaseEndpoints { return new HttpEntity<>(leaseRenewalData); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseContainer.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseContainer.java index 202015eb..fd6b1b96 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseContainer.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseContainer.java @@ -90,8 +90,7 @@ import org.springframework.web.client.HttpStatusCodeException; * * container.afterPropertiesSet(); * container.start(); // events are triggered after starting the container - * </code> - * </pre> + * </code> </pre> * <p> * This container keeps track over {@link RequestedSecret}s and requests secrets upon * {@link #start()}. Leases qualified for {@link Lease#isRenewable() renewal} are renewed @@ -119,8 +118,7 @@ import org.springframework.web.client.HttpStatusCodeException; * @see LeaseEndpoints * @see LeaseStrategy */ -public class SecretLeaseContainer extends SecretLeaseEventPublisher - implements InitializingBean, DisposableBean { +public class SecretLeaseContainer extends SecretLeaseEventPublisher implements InitializingBean, DisposableBean { private static final AtomicIntegerFieldUpdater<SecretLeaseContainer> UPDATER = AtomicIntegerFieldUpdater .newUpdater(SecretLeaseContainer.class, "status"); @@ -128,8 +126,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher private static final AtomicInteger poolId = new AtomicInteger(); private static final int STATUS_INITIAL = 0; + private static final int STATUS_STARTED = 1; + private static final int STATUS_DESTROYED = 2; + private static final Log log = LogFactory.getLog(SecretLeaseContainer.class); private final List<RequestedSecret> requestedSecrets = new CopyOnWriteArrayList<>(); @@ -159,7 +160,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Create a new {@link SecretLeaseContainer} given {@link VaultOperations}. - * * @param operations must not be {@literal null}. */ public SecretLeaseContainer(VaultOperations operations) { @@ -173,7 +173,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Create a new {@link SecretLeaseContainer} given {@link VaultOperations} and * {@link TaskScheduler}. - * * @param operations must not be {@literal null}. * @param taskScheduler must not be {@literal null}. */ @@ -191,7 +190,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher * Set the {@link LeaseEndpoints} to delegate renewal/revocation calls to. * {@link LeaseEndpoints} encapsulates differences between Vault versions that affect * the location of renewal/revocation endpoints. - * * @param leaseEndpoints must not be {@literal null}. * @since 2.1 * @see LeaseEndpoints @@ -206,9 +204,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Sets the amount of seconds that is at least required before renewing a lease. * {@code minRenewalSeconds} prevents renewals from happening too often. - * * @param minRenewalSeconds number of seconds that is at least required before - * renewing a {@link Lease}, must not be negative. + * renewing a {@link Lease}, must not be negative. * @deprecated since 2.0, use {@link #setMinRenewal(Duration)} for time unit safety. */ @Deprecated @@ -219,16 +216,14 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Sets the amount {@link Duration} that is at least required before renewing a lease. * {@code minRenewal} prevents renewals from happening too often. - * * @param minRenewal duration that is at least required before renewing a - * {@link Lease}, must not be {@literal null} or negative. + * {@link Lease}, must not be {@literal null} or negative. * @since 2.0 */ public void setMinRenewal(Duration minRenewal) { Assert.notNull(minRenewal, "Minimal renewal time must not be null"); - Assert.isTrue(!minRenewal.isNegative(), - "Minimal renewal time must not be negative"); + Assert.isTrue(!minRenewal.isNegative(), "Minimal renewal time must not be negative"); this.minRenewal = minRenewal; } @@ -236,9 +231,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Set the expiry threshold. A {@link Lease} is renewed the given seconds before it * expires. - * * @param expiryThresholdSeconds number of seconds before {@link Lease} expiry, must - * not be negative. + * not be negative. * @deprecated since 2.0, use {@link #setExpiryThreshold(Duration)} for time unit * safety. */ @@ -250,22 +244,20 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Set the expiry threshold. A {@link Lease} is renewed the given time before it * expires. - * * @param expiryThreshold duration before {@link Lease} expiry, must not be - * {@literal null} or negative. + * {@literal null} or negative. * @since 2.0 */ public void setExpiryThreshold(Duration expiryThreshold) { Assert.notNull(expiryThreshold, "Expiry threshold must not be null"); - Assert.isTrue(!expiryThreshold.isNegative(), - "Expiry threshold must not be negative"); + Assert.isTrue(!expiryThreshold.isNegative(), "Expiry threshold must not be negative"); this.expiryThreshold = expiryThreshold; } public int getMinRenewalSeconds() { - return Math.toIntExact(minRenewal.getSeconds()); + return Math.toIntExact(this.minRenewal.getSeconds()); } /** @@ -273,11 +265,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher * @since 2.0 */ public Duration getMinRenewal() { - return minRenewal; + return this.minRenewal; } public int getExpiryThresholdSeconds() { - return Math.toIntExact(expiryThreshold.getSeconds()); + return Math.toIntExact(this.expiryThreshold.getSeconds()); } /** @@ -285,12 +277,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher * @since 2.0 */ public Duration getExpiryThreshold() { - return expiryThreshold; + return this.expiryThreshold; } /** * Set the {@link LeaseStrategy} for lease renewal error handling. - * * @param leaseStrategy the {@link LeaseStrategy}, must not be {@literal null}. * @since 2.2 */ @@ -303,7 +294,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Sets the {@link TaskScheduler} to use for scheduling and execution of lease * renewals. - * * @param taskScheduler must not be {@literal null}. */ public void setTaskScheduler(TaskScheduler taskScheduler) { @@ -314,7 +304,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Request a renewable secret at {@code path}. - * * @param path must not be {@literal null} or empty. * @return the {@link RequestedSecret}. */ @@ -324,7 +313,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Request a rotating secret at {@code path}. - * * @param path must not be {@literal null} or empty. * @return the {@link RequestedSecret}. */ @@ -334,7 +322,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Add a {@link RequestedSecret}. - * * @param requestedSecret must not be {@literal null}. */ public RequestedSecret addRequestedSecret(RequestedSecret requestedSecret) { @@ -343,12 +330,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher this.requestedSecrets.add(requestedSecret); - if (initialized) { + if (this.initialized) { Assert.state(this.taskScheduler != null, "TaskScheduler must not be null"); - LeaseRenewalScheduler leaseRenewalScheduler = new LeaseRenewalScheduler( - this.taskScheduler); + LeaseRenewalScheduler leaseRenewalScheduler = new LeaseRenewalScheduler(this.taskScheduler); this.renewals.put(requestedSecret, leaseRenewalScheduler); if (this.status == STATUS_STARTED) { @@ -375,23 +361,19 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher public void start() { Assert.state(this.initialized, "Container is not initialized"); - Assert.state(this.status != STATUS_DESTROYED, - "Container is destroyed and cannot be started"); + Assert.state(this.status != STATUS_DESTROYED, "Container is destroyed and cannot be started"); - Map<RequestedSecret, LeaseRenewalScheduler> renewals = new HashMap<>( - this.renewals); + Map<RequestedSecret, LeaseRenewalScheduler> renewals = new HashMap<>(this.renewals); if (UPDATER.compareAndSet(this, STATUS_INITIAL, STATUS_STARTED)) { - for (Entry<RequestedSecret, LeaseRenewalScheduler> entry : renewals - .entrySet()) { + for (Entry<RequestedSecret, LeaseRenewalScheduler> entry : renewals.entrySet()) { start(entry.getKey(), entry.getValue()); } } } - private void start(RequestedSecret requestedSecret, - LeaseRenewalScheduler renewalScheduler) { + private void start(RequestedSecret requestedSecret, LeaseRenewalScheduler renewalScheduler) { VaultResponseSupport<Map<String, Object>> secrets = doGetSecrets(requestedSecret); @@ -400,13 +382,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher Lease lease; if (StringUtils.hasText(secrets.getLeaseId())) { - lease = Lease.of(secrets.getLeaseId(), - Duration.ofSeconds(secrets.getLeaseDuration()), + lease = Lease.of(secrets.getLeaseId(), Duration.ofSeconds(secrets.getLeaseDuration()), secrets.isRenewable()); } else if (isRotatingGenericSecret(requestedSecret, secrets)) { - lease = Lease - .fromTimeToLive(Duration.ofSeconds(secrets.getLeaseDuration())); + lease = Lease.fromTimeToLive(Duration.ofSeconds(secrets.getLeaseDuration())); } else { lease = Lease.none(); @@ -461,17 +441,16 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setDaemon(true); - scheduler.setThreadNamePrefix(String.format("%s-%d-", - getClass().getSimpleName(), poolId.incrementAndGet())); + scheduler.setThreadNamePrefix( + String.format("%s-%d-", getClass().getSimpleName(), poolId.incrementAndGet())); scheduler.afterPropertiesSet(); this.taskScheduler = scheduler; this.manageTaskScheduler = true; } - for (RequestedSecret requestedSecret : requestedSecrets) { - this.renewals.put(requestedSecret, - new LeaseRenewalScheduler(this.taskScheduler)); + for (RequestedSecret requestedSecret : this.requestedSecrets) { + this.renewals.put(requestedSecret, new LeaseRenewalScheduler(this.taskScheduler)); } } } @@ -493,8 +472,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher if (UPDATER.compareAndSet(this, status, STATUS_DESTROYED)) { - for (Entry<RequestedSecret, LeaseRenewalScheduler> entry : renewals - .entrySet()) { + for (Entry<RequestedSecret, LeaseRenewalScheduler> entry : this.renewals.entrySet()) { Lease lease = entry.getValue().getLease(); entry.getValue().disableScheduleRenewal(); @@ -504,7 +482,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher } } - if (manageTaskScheduler) { + if (this.manageTaskScheduler) { if (this.taskScheduler instanceof DisposableBean) { ((DisposableBean) this.taskScheduler).destroy(); @@ -517,13 +495,12 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Renew a {@link RequestedSecret secret}. - * * @param secret the {@link RequestedSecret secret}' to renew. * @return {@literal true} if the lease was renewed. * @throws IllegalArgumentException if the {@link RequestedSecret secret} was not - * previously {@link #addRequestedSecret(RequestedSecret) registered}. + * previously {@link #addRequestedSecret(RequestedSecret) registered}. * @throws IllegalStateException if there's no {@link Lease} associated with the - * {@link RequestedSecret secret} or the secret is not qualified for renewal. + * {@link RequestedSecret secret} or the secret is not qualified for renewal. * @since 2.2 */ public boolean renew(RequestedSecret secret) { @@ -532,8 +509,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher Lease lease = renewalScheduler.getLease(); if (lease == null) { - throw new IllegalStateException( - String.format("No lease associated with secret %s", secret)); + throw new IllegalStateException(String.format("No lease associated with secret %s", secret)); } if (!renewalScheduler.isLeaseRenewable(lease, secret)) { @@ -545,12 +521,11 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Rotate a {@link RequestedSecret secret}. - * * @param secret the {@link RequestedSecret secret}' to rotate. * @throws IllegalArgumentException if the {@link RequestedSecret secret} was not - * previously {@link #addRequestedSecret(RequestedSecret) registered}. + * previously {@link #addRequestedSecret(RequestedSecret) registered}. * @throws IllegalStateException if there's no {@link Lease} associated with the - * {@link RequestedSecret secret} or the secret is not qualified for rotation. + * {@link RequestedSecret secret} or the secret is not qualified for rotation. * @since 2.2 */ public void rotate(RequestedSecret secret) { @@ -559,12 +534,10 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher Lease lease = renewalScheduler.getLease(); if (lease == null) { - throw new IllegalStateException( - String.format("No lease associated with secret %s", secret)); + throw new IllegalStateException(String.format("No lease associated with secret %s", secret)); } - if (!renewalScheduler.isLeaseRenewable(lease, secret) - && !renewalScheduler.isLeaseRotateOnly(lease, secret)) { + if (!renewalScheduler.isLeaseRenewable(lease, secret) && !renewalScheduler.isLeaseRotateOnly(lease, secret)) { throw new IllegalStateException("Secret is not qualified for rotation"); } @@ -583,8 +556,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher } - private Lease renewAndSchedule(RequestedSecret requestedSecret, - LeaseRenewalScheduler leaseRenewal, Lease leaseToRenew) { + private Lease renewAndSchedule(RequestedSecret requestedSecret, LeaseRenewalScheduler leaseRenewal, + Lease leaseToRenew) { Lease newLease = doRenewLease(requestedSecret, leaseToRenew); @@ -598,8 +571,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher return newLease; } - private void scheduleLeaseRotation(RequestedSecret secret, Lease lease, - LeaseRenewalScheduler leaseRenewal) { + private void scheduleLeaseRotation(RequestedSecret secret, Lease lease, LeaseRenewalScheduler leaseRenewal) { logRenewalCandidate(secret, lease, "rotation"); @@ -615,24 +587,22 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher LeaseRenewalScheduler renewalScheduler = this.renewals.get(secret); if (renewalScheduler == null) { - throw new IllegalArgumentException( - String.format("No such secret %s", secret)); + throw new IllegalArgumentException(String.format("No such secret %s", secret)); } return renewalScheduler; } - private static void logRenewalCandidate(RequestedSecret requestedSecret, Lease lease, - String action) { + private static void logRenewalCandidate(RequestedSecret requestedSecret, Lease lease, String action) { if (log.isDebugEnabled()) { if (lease.hasLeaseId()) { - log.debug(String.format("Secret %s with Lease %s qualified for %s", - requestedSecret.getPath(), lease.getLeaseId(), action)); + log.debug(String.format("Secret %s with Lease %s qualified for %s", requestedSecret.getPath(), + lease.getLeaseId(), action)); } else { - log.debug(String.format("Secret %s with cache hint is qualified for %s", - requestedSecret.getPath(), action)); + log.debug(String.format("Secret %s with cache hint is qualified for %s", requestedSecret.getPath(), + action)); } } } @@ -643,20 +613,18 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Retrieve secrets from {@link VaultOperations}. - * * @param requestedSecret the {@link RequestedSecret} providing the secret - * {@code path}. + * {@code path}. * @return the response. */ @Nullable - protected VaultResponseSupport<Map<String, Object>> doGetSecrets( - RequestedSecret requestedSecret) { + protected VaultResponseSupport<Map<String, Object>> doGetSecrets(RequestedSecret requestedSecret) { try { VaultResponseSupport<Map<String, Object>> secrets; - if (keyValueDelegate.isVersioned(requestedSecret.getPath())) { - secrets = keyValueDelegate.getSecret(requestedSecret.getPath()); + if (this.keyValueDelegate.isVersioned(requestedSecret.getPath())) { + secrets = this.keyValueDelegate.getSecret(requestedSecret.getPath()); } else { secrets = this.operations.read(requestedSecret.getPath()); @@ -677,7 +645,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Renew a {@link Lease} for a {@link RequestedSecret}. - * * @param requestedSecret the requested secret. * @param lease the lease. * @return the new lease or {@literal null} if expired/secret cannot be rotated. @@ -687,8 +654,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher try { Lease renewed = lease.hasLeaseId() ? doRenew(lease) : lease; - if (!renewed.hasLeaseId() || renewed.getLeaseDuration().isZero() || renewed - .getLeaseDuration().getSeconds() < minRenewal.getSeconds()) { + if (!renewed.hasLeaseId() || renewed.getLeaseDuration().isZero() + || renewed.getLeaseDuration().getSeconds() < this.minRenewal.getSeconds()) { onLeaseExpired(requestedSecret, lease); return Lease.none(); @@ -698,8 +665,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher } catch (RuntimeException e) { - HttpStatusCodeException httpException = potentiallyUnwrapHttpStatusCodeException( - e); + HttpStatusCodeException httpException = potentiallyUnwrapHttpStatusCodeException(e); boolean expired = false; Exception exceptionToUse; @@ -710,11 +676,9 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher onLeaseExpired(requestedSecret, lease); } - exceptionToUse = new VaultException(String.format( - "Cannot renew lease: Status %s %s%s", + exceptionToUse = new VaultException(String.format("Cannot renew lease: Status %s %s%s", httpException.getRawStatusCode(), httpException.getStatusText(), - VaultResponses.getError(httpException.getResponseBodyAsString())), - e); + VaultResponses.getError(httpException.getResponseBodyAsString())), e); } else { exceptionToUse = new VaultException("Cannot renew lease", e); @@ -722,7 +686,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher onError(requestedSecret, lease, exceptionToUse); - if (expired || leaseStrategy.shouldDrop(exceptionToUse)) { + if (expired || this.leaseStrategy.shouldDrop(exceptionToUse)) { return Lease.none(); } else { @@ -732,8 +696,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher } @Nullable - private HttpStatusCodeException potentiallyUnwrapHttpStatusCodeException( - RuntimeException e) { + private HttpStatusCodeException potentiallyUnwrapHttpStatusCodeException(RuntimeException e) { if (e instanceof HttpStatusCodeException) { return (HttpStatusCodeException) e; @@ -748,15 +711,13 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher private Lease doRenew(Lease lease) { - return operations.doWithSession( - restOperations -> leaseEndpoints.renew(lease, restOperations)); + return this.operations.doWithSession(restOperations -> this.leaseEndpoints.renew(lease, restOperations)); } /** * Hook method called when a {@link Lease} expires. The default implementation is to * notify {@link LeaseListener}. Implementations can override this method in * subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -765,13 +726,12 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher super.onLeaseExpired(requestedSecret, lease); if (requestedSecret.getMode() == Mode.ROTATE) { - start(requestedSecret, renewals.get(requestedSecret)); + start(requestedSecret, this.renewals.get(requestedSecret)); } } /** * Revoke the {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -782,17 +742,16 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher onBeforeLeaseRevocation(requestedSecret, lease); - operations.doWithSession(restOperations -> { - leaseEndpoints.revoke(lease, restOperations); + this.operations.doWithSession(restOperations -> { + this.leaseEndpoints.revoke(lease, restOperations); return null; }); onAfterLeaseRevocation(requestedSecret, lease); } catch (HttpStatusCodeException e) { - onError(requestedSecret, lease, - new VaultException(String.format("Cannot revoke lease: %s", - VaultResponses.getError(e.getResponseBodyAsString())))); + onError(requestedSecret, lease, new VaultException( + String.format("Cannot revoke lease: %s", VaultResponses.getError(e.getResponseBodyAsString())))); } catch (RuntimeException e) { onError(requestedSecret, lease, e); @@ -808,8 +767,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher */ static class LeaseRenewalScheduler { - private static final Log log = org.apache.commons.logging.LogFactory - .getLog(LeaseRenewalScheduler.class); + private static final Log log = org.apache.commons.logging.LogFactory.getLog(LeaseRenewalScheduler.class); + private final TaskScheduler taskScheduler; final AtomicReference<Lease> currentLeaseRef = new AtomicReference<>(); @@ -817,7 +776,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher final Map<Lease, ScheduledFuture<?>> schedules = new ConcurrentHashMap<>(); /** - * * @param taskScheduler must not be {@literal null}. */ LeaseRenewalScheduler(TaskScheduler taskScheduler) { @@ -831,24 +789,20 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher * @param renewLease strategy to renew a {@link Lease}. * @param lease the current {@link Lease}. * @param minRenewal minimum duration before renewing a {@link Lease}. This is to - * prevent too many renewals in a very short timeframe. + * prevent too many renewals in a very short timeframe. * @param expiryThreshold duration to renew before {@link Lease}. */ - void scheduleRenewal(RequestedSecret requestedSecret, RenewLease renewLease, - Lease lease, Duration minRenewal, Duration expiryThreshold) { + void scheduleRenewal(RequestedSecret requestedSecret, RenewLease renewLease, Lease lease, Duration minRenewal, + Duration expiryThreshold) { if (log.isDebugEnabled()) { if (lease.hasLeaseId()) { - log.debug(String.format( - "Scheduling renewal for secret %s with lease %s, lease duration %d", - requestedSecret.getPath(), lease.getLeaseId(), - lease.getLeaseDuration().getSeconds())); + log.debug(String.format("Scheduling renewal for secret %s with lease %s, lease duration %d", + requestedSecret.getPath(), lease.getLeaseId(), lease.getLeaseDuration().getSeconds())); } else { - log.debug(String.format( - "Scheduling renewal for secret %s, with cache hint duration %d", - requestedSecret.getPath(), - lease.getLeaseDuration().getSeconds())); + log.debug(String.format("Scheduling renewal for secret %s, with cache hint duration %d", + requestedSecret.getPath(), lease.getLeaseDuration().getSeconds())); } } @@ -864,21 +818,20 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher @Override public void run() { - schedules.remove(lease); + LeaseRenewalScheduler.this.schedules.remove(lease); - if (currentLeaseRef.get() != lease) { + if (LeaseRenewalScheduler.this.currentLeaseRef.get() != lease) { log.debug("Current lease has changed. Skipping renewal"); return; } if (log.isDebugEnabled()) { if (lease.hasLeaseId()) { - log.debug(String.format("Renewing lease %s for secret %s", - lease.getLeaseId(), requestedSecret.getPath())); + log.debug(String.format("Renewing lease %s for secret %s", lease.getLeaseId(), + requestedSecret.getPath())); } else { - log.debug(String.format("Renewing secret without lease %s", - requestedSecret.getPath())); + log.debug(String.format("Renewing secret without lease %s", requestedSecret.getPath())); } } @@ -887,32 +840,28 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher // Renew lease may call scheduleRenewal(…) with a different lease // Id to alter set up its own renewal schedule. If it's the old // lease, then renewLease() outcome controls the current LeaseId. - currentLeaseRef.compareAndSet(lease, - renewLease.renewLease(lease)); + LeaseRenewalScheduler.this.currentLeaseRef.compareAndSet(lease, renewLease.renewLease(lease)); } catch (Exception e) { - log.error(String.format("Cannot renew lease %s", - lease.getLeaseId()), e); + log.error(String.format("Cannot renew lease %s", lease.getLeaseId()), e); } } }; - ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(task, - new OneShotTrigger( - getRenewalSeconds(lease, minRenewal, expiryThreshold))); + ScheduledFuture<?> scheduledFuture = this.taskScheduler.schedule(task, + new OneShotTrigger(getRenewalSeconds(lease, minRenewal, expiryThreshold))); - schedules.put(lease, scheduledFuture); + this.schedules.put(lease, scheduledFuture); } private void cancelSchedule(Lease lease) { - ScheduledFuture<?> scheduledFuture = schedules.get(lease); + ScheduledFuture<?> scheduledFuture = this.schedules.get(lease); if (scheduledFuture != null) { if (log.isDebugEnabled()) { - log.debug(String.format( - "Canceling previously registered schedule for lease %s", - lease.getLeaseId())); + log.debug( + String.format("Canceling previously registered schedule for lease %s", lease.getLeaseId())); } scheduledFuture.cancel(false); @@ -924,23 +873,21 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher */ void disableScheduleRenewal() { - currentLeaseRef.set(null); - Set<Lease> leases = new HashSet<>(schedules.keySet()); + this.currentLeaseRef.set(null); + Set<Lease> leases = new HashSet<>(this.schedules.keySet()); for (Lease lease : leases) { cancelSchedule(lease); - schedules.remove(lease); + this.schedules.remove(lease); } } - private long getRenewalSeconds(Lease lease, Duration minRenewal, - Duration expiryThreshold) { + private long getRenewalSeconds(Lease lease, Duration minRenewal, Duration expiryThreshold) { return Math.max(minRenewal.getSeconds(), lease.getLeaseDuration().getSeconds() - expiryThreshold.getSeconds()); } - private boolean isLeaseRenewable(@Nullable Lease lease, - RequestedSecret requestedSecret) { + private boolean isLeaseRenewable(@Nullable Lease lease, RequestedSecret requestedSecret) { if (lease == null) { return false; @@ -959,7 +906,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher @Nullable public Lease getLease() { - return currentLeaseRef.get(); + return this.currentLeaseRef.get(); } private boolean isLeaseRotateOnly(Lease lease, RequestedSecret requestedSecret) { @@ -968,9 +915,9 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher return false; } - return lease.hasLeaseId() && !lease.isRenewable() - && requestedSecret.getMode() == Mode.ROTATE; + return lease.hasLeaseId() && !lease.isRenewable() && requestedSecret.getMode() == Mode.ROTATE; } + } /** @@ -983,6 +930,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher .newUpdater(OneShotTrigger.class, "status"); private static final int STATUS_ARMED = 0; + private static final int STATUS_FIRED = 1; // see AtomicIntegerFieldUpdater UPDATER @@ -999,12 +947,12 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher public Date nextExecutionTime(TriggerContext triggerContext) { if (UPDATER.compareAndSet(this, STATUS_ARMED, STATUS_FIRED)) { - return new Date( - System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds)); + return new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(this.seconds)); } return null; } + } /** @@ -1014,11 +962,12 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher /** * Renew a lease. - * * @param lease must not be {@literal null}. * @return the new lease. * @throws VaultException if lease renewal runs into problems */ Lease renewLease(Lease lease) throws VaultException; + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseEventPublisher.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseEventPublisher.java index da7f5ad3..94352f9e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseEventPublisher.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/SecretLeaseEventPublisher.java @@ -59,7 +59,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { /** * Add a {@link LeaseListener} to the container. The listener starts receiving events * as soon as possible. - * * @param listener lease listener, must not be {@literal null}. */ public void addLeaseListener(LeaseListener listener) { @@ -71,7 +70,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { /** * Remove a {@link LeaseListener}. - * * @param listener must not be {@literal null}. */ public void removeLeaseListener(LeaseListener listener) { @@ -81,7 +79,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { /** * Add a {@link LeaseErrorListener} to the container. The listener starts receiving * events as soon as possible. - * * @param listener lease listener, must not be {@literal null}. */ public void addErrorListener(LeaseErrorListener listener) { @@ -93,7 +90,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { /** * Remove a {@link LeaseErrorListener}. - * * @param listener must not be {@literal null}. */ public void removeLeaseErrorListener(LeaseErrorListener listener) { @@ -112,13 +108,11 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called when secrets were obtained. The default implementation is to * notify {@link LeaseListener}. Implementations can override this method in * subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. * @param body must not be {@literal null}. */ - protected void onSecretsObtained(RequestedSecret requestedSecret, Lease lease, - Map<String, Object> body) { + protected void onSecretsObtained(RequestedSecret requestedSecret, Lease lease, Map<String, Object> body) { dispatch(new SecretLeaseCreatedEvent(requestedSecret, lease, body)); } @@ -126,7 +120,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called when secrets were not found. The default implementation is to * notify {@link LeaseListener}. Implementations can override this method in * subclasses. - * * @param requestedSecret must not be {@literal null}. */ protected void onSecretsNotFound(RequestedSecret requestedSecret) { @@ -137,7 +130,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called when a {@link Lease} is renewed. The default implementation is * to notify {@link LeaseListener}. Implementations can override this method in * subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -149,7 +141,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called before triggering revocation for a {@link Lease}. The default * implementation is to notify {@link LeaseListener}. Implementations can override * this method in subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -161,7 +152,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called after triggering revocation for a {@link Lease}. The default * implementation is to notify {@link LeaseListener}. Implementations can override * this method in subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -173,7 +163,6 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called when a {@link Lease} expires. The default implementation is to * notify {@link LeaseListener}. Implementations can override this method in * subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ @@ -185,36 +174,32 @@ public class SecretLeaseEventPublisher implements InitializingBean { * Hook method called when an error occurred during secret retrieval, lease renewal, * and other Vault interactions. The default implementation is to notify * {@link LeaseErrorListener}. Implementations can override this method in subclasses. - * * @param requestedSecret must not be {@literal null}. * @param lease may be {@literal null} * @param e the causing exception. */ - protected void onError(RequestedSecret requestedSecret, @Nullable Lease lease, - Exception e) { + protected void onError(RequestedSecret requestedSecret, @Nullable Lease lease, Exception e) { dispatch(new SecretLeaseErrorEvent(requestedSecret, lease, e)); } /** * Dispatch the event to all {@link LeaseListener}s. - * * @param leaseEvent the event to dispatch. */ void dispatch(SecretLeaseEvent leaseEvent) { - for (LeaseListener listener : leaseListeners) { + for (LeaseListener listener : this.leaseListeners) { listener.onLeaseEvent(leaseEvent); } } /** * Dispatch the event to all {@link LeaseErrorListener}s. - * * @param errorEvent the event to dispatch. */ void dispatch(SecretLeaseErrorEvent errorEvent) { - for (LeaseErrorListener listener : leaseErrorListeners) { + for (LeaseErrorListener listener : this.leaseErrorListeners) { listener.onLeaseError(errorEvent, (Exception) errorEvent.getException()); } } @@ -230,8 +215,10 @@ public class SecretLeaseEventPublisher implements InitializingBean { @Override public void onLeaseError(SecretLeaseEvent leaseEvent, Exception exception) { - log.warn(String.format("[%s] %s %s", leaseEvent.getSource(), - leaseEvent.getLease(), exception.getMessage()), exception); + log.warn(String.format("[%s] %s %s", leaseEvent.getSource(), leaseEvent.getLease(), exception.getMessage()), + exception); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/Lease.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/Lease.java index 213f0f29..1e777ef2 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/Lease.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/Lease.java @@ -46,7 +46,6 @@ public class Lease { /** * Create a new {@link Lease}. - * * @param leaseId must not be empty or {@literal null}. * @param leaseDurationSeconds the lease duration in seconds, must not be negative. * @param renewable {@literal true} if this lease is renewable. @@ -64,7 +63,6 @@ public class Lease { /** * Create a new {@link Lease}. - * * @param leaseId must not be empty or {@literal null}. * @param leaseDuration the lease duration, must not be {@literal null} or negative. * @param renewable {@literal true} if this lease is renewable. @@ -83,7 +81,6 @@ public class Lease { /** * Create a new non-renewable {@link Lease}, without a {@code leaseId} and specified * duration. - * * @param leaseDuration the lease duration in seconds, must not be negative. * @return the created {@link Lease} * @since 1.1 @@ -100,7 +97,6 @@ public class Lease { /** * Create a new non-renewable {@link Lease}, without a {@code leaseId} and specified * duration. - * * @param leaseDuration the lease duration, must not be {@literal null} or negative. * @return the created {@link Lease} * @since 2.0 @@ -115,7 +111,6 @@ public class Lease { /** * Factory method to return a non-renewable, zero-duration {@link Lease}. - * * @return a non-renewable, zero-duration {@link Lease}. */ public static Lease none() { @@ -127,7 +122,7 @@ public class Lease { * @since 1.1 */ public boolean hasLeaseId() { - return leaseId != null; + return this.leaseId != null; } /** @@ -135,21 +130,21 @@ public class Lease { */ @Nullable public String getLeaseId() { - return leaseId; + return this.leaseId; } /** * @return the lease duration in seconds. */ public Duration getLeaseDuration() { - return leaseDuration; + return this.leaseDuration; } /** * @return {@literal true} if the lease is renewable. */ public boolean isRenewable() { - return renewable; + return this.renewable; } @Override @@ -162,19 +157,19 @@ public class Lease { Lease lease = (Lease) o; - if (leaseDuration != lease.leaseDuration) + if (this.leaseDuration != lease.leaseDuration) return false; - if (renewable != lease.renewable) + if (this.renewable != lease.renewable) return false; - return leaseId != null ? leaseId.equals(lease.leaseId) : lease.leaseId == null; + return this.leaseId != null ? this.leaseId.equals(lease.leaseId) : lease.leaseId == null; } @Override public int hashCode() { - int result = leaseId != null ? leaseId.hashCode() : 0; - result = 31 * result + leaseDuration.hashCode(); - result = 31 * result + (renewable ? 1 : 0); + int result = this.leaseId != null ? this.leaseId.hashCode() : 0; + result = 31 * result + this.leaseDuration.hashCode(); + result = 31 * result + (this.renewable ? 1 : 0); return result; } @@ -183,10 +178,11 @@ public class Lease { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [leaseId='").append(leaseId).append('\''); - sb.append(", leaseDuration=").append(leaseDuration); - sb.append(", renewable=").append(renewable); + sb.append(" [leaseId='").append(this.leaseId).append('\''); + sb.append(", leaseDuration=").append(this.leaseDuration); + sb.append(", renewable=").append(this.renewable); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/RequestedSecret.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/RequestedSecret.java index cd7ad70e..8a11a327 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/RequestedSecret.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/domain/RequestedSecret.java @@ -31,6 +31,7 @@ import org.springframework.util.Assert; public class RequestedSecret { private final String path; + private final Mode mode; private RequestedSecret(String path, Mode mode) { @@ -46,7 +47,6 @@ public class RequestedSecret { * Create a renewable {@link RequestedSecret} at {@code path}. A lease associated with * this secret will be renewed if the lease is qualified for renewal. The lease is no * longer valid after expiry. - * * @param path must not be {@literal null} or empty, must not start with a slash. * @return the renewable {@link RequestedSecret}. */ @@ -58,7 +58,6 @@ public class RequestedSecret { * Create a rotating {@link RequestedSecret} at {@code path}. A lease associated with * this secret will be renewed if the lease is qualified for renewal. Once the lease * expires, a new secret with a new lease is obtained. - * * @param path must not be {@literal null} or empty, must not start with a slash. * @return the rotating {@link RequestedSecret}. */ @@ -68,7 +67,6 @@ public class RequestedSecret { /** * Create a {@link RequestedSecret} given {@link Mode} at {@code path}. - * * @param mode must not be {@literal null}. * @param path must not be {@literal null} or empty, must not start with a slash. * @see #rotating(String) @@ -86,7 +84,7 @@ public class RequestedSecret { * @return the Vault path of the requested secret. */ public String getPath() { - return path; + return this.path; } /** @@ -94,7 +92,7 @@ public class RequestedSecret { * @see Mode */ public Mode getMode() { - return mode; + return this.mode; } @Override @@ -107,16 +105,16 @@ public class RequestedSecret { RequestedSecret that = (RequestedSecret) o; - if (!path.equals(that.path)) + if (!this.path.equals(that.path)) return false; - return mode == that.mode; + return this.mode == that.mode; } @Override public int hashCode() { - int result = path.hashCode(); - result = 31 * result + mode.hashCode(); + int result = this.path.hashCode(); + result = 31 * result + this.mode.hashCode(); return result; } @@ -125,8 +123,8 @@ public class RequestedSecret { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [path='").append(path).append('\''); - sb.append(", mode=").append(mode); + sb.append(" [path='").append(this.path).append('\''); + sb.append(", mode=").append(this.mode); sb.append(']'); return sb.toString(); } @@ -143,5 +141,7 @@ public class RequestedSecret { * the previous lease expires its max lease time. */ ROTATE; + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRenewedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRenewedEvent.java index 53ed1743..99625a8b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRenewedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRenewedEvent.java @@ -32,11 +32,11 @@ public class AfterSecretLeaseRenewedEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret} and * {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ public AfterSecretLeaseRenewedEvent(RequestedSecret requestedSecret, Lease lease) { super(requestedSecret, lease); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRevocationEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRevocationEvent.java index 12b51934..a79c5eea 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRevocationEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/AfterSecretLeaseRevocationEvent.java @@ -32,11 +32,11 @@ public class AfterSecretLeaseRevocationEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret} and * {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ public AfterSecretLeaseRevocationEvent(RequestedSecret requestedSecret, Lease lease) { super(requestedSecret, lease); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/BeforeSecretLeaseRevocationEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/BeforeSecretLeaseRevocationEvent.java index be33b9a1..8a6f4d39 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/BeforeSecretLeaseRevocationEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/BeforeSecretLeaseRevocationEvent.java @@ -32,12 +32,11 @@ public class BeforeSecretLeaseRevocationEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret} and * {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ - public BeforeSecretLeaseRevocationEvent(RequestedSecret requestedSecret, - Lease lease) { + public BeforeSecretLeaseRevocationEvent(RequestedSecret requestedSecret, Lease lease) { super(requestedSecret, lease); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseErrorListener.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseErrorListener.java index 7ef34c4c..3257a758 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseErrorListener.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseErrorListener.java @@ -28,9 +28,9 @@ public interface LeaseErrorListener { /** * Callback for a {@link SecretLeaseEvent}. - * * @param leaseEvent the event object, must not be {@literal null}. * @param exception the thrown {@link Exception}. */ void onLeaseError(SecretLeaseEvent leaseEvent, Exception exception); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListener.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListener.java index b901d4ae..e65bd144 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListener.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListener.java @@ -25,8 +25,8 @@ public interface LeaseListener { /** * Callback for a {@link SecretLeaseEvent} - * * @param leaseEvent the event object, must not be {@literal null}. */ void onLeaseEvent(SecretLeaseEvent leaseEvent); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListenerAdapter.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListenerAdapter.java index 54f99903..b5ac616f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListenerAdapter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/LeaseListenerAdapter.java @@ -33,4 +33,5 @@ public abstract class LeaseListenerAdapter implements LeaseListener, LeaseErrorL public void onLeaseError(SecretLeaseEvent leaseEvent, Exception exception) { // empty listener method } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseCreatedEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseCreatedEvent.java index c26edb95..25ff28c7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseCreatedEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseCreatedEvent.java @@ -36,18 +36,17 @@ public class SecretLeaseCreatedEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret}, * {@link Lease} and {@code secrets}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ - public SecretLeaseCreatedEvent(RequestedSecret requestedSecret, Lease lease, - Map<String, Object> secrets) { + public SecretLeaseCreatedEvent(RequestedSecret requestedSecret, Lease lease, Map<String, Object> secrets) { super(requestedSecret, lease); this.secrets = Collections.unmodifiableMap(new LinkedHashMap<>(secrets)); } public Map<String, Object> getSecrets() { - return secrets; + return this.secrets; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseErrorEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseErrorEvent.java index 56820162..04c7284e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseErrorEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseErrorEvent.java @@ -34,13 +34,11 @@ public class SecretLeaseErrorEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret}, * {@link Lease} and {@link Throwable}. - * * @param requestedSecret must not be {@literal null}. * @param lease can be {@literal null}. * @param exception must not be {@literal null}. */ - public SecretLeaseErrorEvent(RequestedSecret requestedSecret, @Nullable Lease lease, - Throwable exception) { + public SecretLeaseErrorEvent(RequestedSecret requestedSecret, @Nullable Lease lease, Throwable exception) { super(requestedSecret, lease); @@ -48,6 +46,7 @@ public class SecretLeaseErrorEvent extends SecretLeaseEvent { } public Throwable getException() { - return exception; + return this.exception; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseEvent.java index 40d39fbf..7c9e9850 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseEvent.java @@ -39,7 +39,6 @@ public abstract class SecretLeaseEvent extends ApplicationEvent { /** * Create a new {@link SecretLeaseEvent} given {@link RequestedSecret} and * {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease can be {@literal null}. */ @@ -56,6 +55,7 @@ public abstract class SecretLeaseEvent extends ApplicationEvent { @Nullable public Lease getLease() { - return lease; + return this.lease; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseExpiredEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseExpiredEvent.java index 8c3c6e71..958a471d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseExpiredEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretLeaseExpiredEvent.java @@ -32,11 +32,11 @@ public class SecretLeaseExpiredEvent extends SecretLeaseEvent { /** * Create a new {@link SecretLeaseExpiredEvent} given {@link RequestedSecret} and * {@link Lease}. - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ public SecretLeaseExpiredEvent(RequestedSecret requestedSecret, Lease lease) { super(requestedSecret, lease); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretNotFoundEvent.java b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretNotFoundEvent.java index 7c2b20b8..2c963eb7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretNotFoundEvent.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/lease/event/SecretNotFoundEvent.java @@ -30,11 +30,11 @@ public class SecretNotFoundEvent extends SecretLeaseEvent { /** * Create a new {@link SecretNotFoundEvent} given {@link RequestedSecret} - * * @param requestedSecret must not be {@literal null}. * @param lease must not be {@literal null}. */ public SecretNotFoundEvent(RequestedSecret requestedSecret, Lease lease) { super(requestedSecret, lease); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/util/KeyValueDelegate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/util/KeyValueDelegate.java index 1d87ba1b..e4aec57d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/util/KeyValueDelegate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/util/KeyValueDelegate.java @@ -48,15 +48,13 @@ public class KeyValueDelegate { } @SuppressWarnings("unchecked") - public KeyValueDelegate(VaultOperations operations, - Supplier<Map<String, ?>> cacheSupplier) { + public KeyValueDelegate(VaultOperations operations, Supplier<Map<String, ?>> cacheSupplier) { this.operations = operations; this.mountInfo = (Map) cacheSupplier.get(); } /** * Determine whether the {@code path} belongs to a versioned Key-Value mount. - * * @param path the path to inspect. * @return {@literal true} if the {@code path} belongs to a versioned Key-Value mount. */ @@ -67,7 +65,6 @@ public class KeyValueDelegate { /** * Read a secret from a key-value backend. Considers the backend type and whether the * backend is a versioned key-value backend. - * * @param path the path to fetch the secret from. * @return the secret, can be {@literal null}. */ @@ -80,8 +77,7 @@ public class KeyValueDelegate { return this.operations.read(path); } - VaultResponse response = this.operations - .read(getKeyValue2Path(mountInfo.getPath(), path)); + VaultResponse response = this.operations.read(getKeyValue2Path(mountInfo.getPath(), path)); unwrapDataResponse(response); return response; @@ -101,21 +97,18 @@ public class KeyValueDelegate { @SuppressWarnings("unchecked") private static void unwrapDataResponse(@Nullable VaultResponse response) { - if (response == null || response.getData() == null - || !response.getData().containsKey("data")) { + if (response == null || response.getData() == null || !response.getData().containsKey("data")) { return; } - Map<String, Object> nested = new LinkedHashMap<>( - (Map) response.getRequiredData().get("data")); + Map<String, Object> nested = new LinkedHashMap<>((Map) response.getRequiredData().get("data")); response.setData(nested); } @SuppressWarnings("unchecked") private MountInfo doGetMountInfo(String path) { - VaultResponse response = this.operations - .read(String.format("sys/internal/ui/mounts/%s", path)); + VaultResponse response = this.operations.read(String.format("sys/internal/ui/mounts/%s", path)); if (response == null || response.getData() == null) { return MountInfo.unavailable(); @@ -145,15 +138,15 @@ public class KeyValueDelegate { static class MountInfo { - static final MountInfo UNAVAILABLE = new MountInfo("", Collections.emptyMap(), - false); + static final MountInfo UNAVAILABLE = new MountInfo("", Collections.emptyMap(), false); final String path; + final @Nullable Map<String, Object> options; + final boolean available; - private MountInfo(String path, @Nullable Map<String, Object> options, - boolean available) { + private MountInfo(String path, @Nullable Map<String, Object> options, boolean available) { this.path = path; this.options = options; this.available = available; @@ -161,7 +154,6 @@ public class KeyValueDelegate { /** * Creates a new {@link MountInfo} representing an absent {@link MountInfo}. - * * @return a new {@link MountInfo} representing an absent {@link MountInfo}. */ static MountInfo unavailable() { @@ -170,7 +162,6 @@ public class KeyValueDelegate { /** * Creates a new {@link MountInfo} given {@code path} and {@link Map options map}. - * * @param path * @param options * @return a new {@link MountInfo} for {@code path} and {@link Map options map}. @@ -181,11 +172,11 @@ public class KeyValueDelegate { boolean isKeyValue(KeyValueBackend versioned) { - if (!isAvailable() || !StringUtils.hasText(path) || options == null) { + if (!isAvailable() || !StringUtils.hasText(this.path) || this.options == null) { return false; } - Object version = options.get("version"); + Object version = this.options.get("version"); if (version != null) { @@ -213,5 +204,7 @@ public class KeyValueDelegate { public boolean isAvailable() { return this.available; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformer.java b/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformer.java index 29278e53..51081b4e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformer.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformer.java @@ -35,7 +35,6 @@ public interface PropertyTransformer { * <p> * Implementing classes do not change the {@code input} but create a new {@link Map * property map}. - * * @param input must not be {@literal null}. * @return transformed properties. */ @@ -51,4 +50,5 @@ public interface PropertyTransformer { default PropertyTransformer andThen(PropertyTransformer after) { return input -> after.transformProperties(transformProperties(input)); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformers.java b/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformers.java index 2c6af6bb..67544774 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformers.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/core/util/PropertyTransformers.java @@ -73,10 +73,10 @@ public abstract class PropertyTransformers { @Override @SuppressWarnings("unchecked") - public Map<String, Object> transformProperties( - Map<String, ? extends Object> input) { + public Map<String, Object> transformProperties(Map<String, ? extends Object> input) { return (Map) input; } + } /** @@ -97,8 +97,7 @@ public abstract class PropertyTransformers { } @Override - public Map<String, Object> transformProperties( - Map<String, ? extends Object> input) { + public Map<String, Object> transformProperties(Map<String, ? extends Object> input) { Map<String, Object> target = new LinkedHashMap<>(input.size(), 1); @@ -113,6 +112,7 @@ public abstract class PropertyTransformers { return target; } + } /** @@ -133,7 +133,7 @@ public abstract class PropertyTransformers { * Create a new {@link KeyPrefixPropertyTransformer} that adds a prefix to each * key name. * @param propertyNamePrefix the property name prefix to be added in front of each - * property name, must not be {@literal null}. + * property name, must not be {@literal null}. * @return a new {@link KeyPrefixPropertyTransformer} that adds a prefix to each * key name. */ @@ -142,16 +142,17 @@ public abstract class PropertyTransformers { } @Override - public Map<String, Object> transformProperties( - Map<String, ? extends Object> input) { + public Map<String, Object> transformProperties(Map<String, ? extends Object> input) { Map<String, Object> target = new LinkedHashMap<>(input.size(), 1); for (Entry<String, ? extends Object> entry : input.entrySet()) { - target.put(propertyNamePrefix + entry.getKey(), entry.getValue()); + target.put(this.propertyNamePrefix + entry.getKey(), entry.getValue()); } return target; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/EnableVaultRepositories.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/EnableVaultRepositories.java index 68aa2d0b..6c254ecc 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/EnableVaultRepositories.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/EnableVaultRepositories.java @@ -134,4 +134,5 @@ public @interface EnableVaultRepositories { * {@literal vaultTemplate}. */ String vaultTemplateRef() default "vaultTemplate"; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoriesRegistrar.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoriesRegistrar.java index 2b8710de..b2320dac 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoriesRegistrar.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoriesRegistrar.java @@ -38,4 +38,5 @@ public class VaultRepositoriesRegistrar extends RepositoryBeanDefinitionRegistra protected RepositoryConfigurationExtension getExtension() { return new VaultRepositoryConfigurationExtension(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoryConfigurationExtension.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoryConfigurationExtension.java index 6f731e1d..91e4816c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoryConfigurationExtension.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/configuration/VaultRepositoryConfigurationExtension.java @@ -39,8 +39,7 @@ import org.springframework.vault.repository.mapping.VaultMappingContext; * @author Mark Paluch * @since 2.0 */ -public class VaultRepositoryConfigurationExtension - extends KeyValueRepositoryConfigurationExtension { +public class VaultRepositoryConfigurationExtension extends KeyValueRepositoryConfigurationExtension { private static final String VAULT_ADAPTER_BEAN_NAME = "vaultKeyValueAdapter"; @@ -65,55 +64,45 @@ public class VaultRepositoryConfigurationExtension public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConfigurationSource configurationSource) { - Optional<String> vaultTemplateRef = configurationSource - .getAttribute("vaultTemplateRef"); + Optional<String> vaultTemplateRef = configurationSource.getAttribute("vaultTemplateRef"); - RootBeanDefinition mappingContextDefinition = createVaultMappingContext( - configurationSource); + RootBeanDefinition mappingContextDefinition = createVaultMappingContext(configurationSource); mappingContextDefinition.setSource(configurationSource.getSource()); - registerIfNotAlreadyRegistered(() -> mappingContextDefinition, registry, - VAULT_MAPPING_CONTEXT_BEAN_NAME, configurationSource); + registerIfNotAlreadyRegistered(() -> mappingContextDefinition, registry, VAULT_MAPPING_CONTEXT_BEAN_NAME, + configurationSource); // register Adapter - RootBeanDefinition vaultKeyValueAdapterDefinition = new RootBeanDefinition( - VaultKeyValueAdapter.class); + RootBeanDefinition vaultKeyValueAdapterDefinition = new RootBeanDefinition(VaultKeyValueAdapter.class); ConstructorArgumentValues constructorArgumentValuesForVaultKeyValueAdapter = new ConstructorArgumentValues(); constructorArgumentValuesForVaultKeyValueAdapter.addIndexedArgumentValue(0, new RuntimeBeanReference(vaultTemplateRef.orElse("vaultTemplate"))); - vaultKeyValueAdapterDefinition.setConstructorArgumentValues( - constructorArgumentValuesForVaultKeyValueAdapter); + vaultKeyValueAdapterDefinition.setConstructorArgumentValues(constructorArgumentValuesForVaultKeyValueAdapter); - registerIfNotAlreadyRegistered(() -> vaultKeyValueAdapterDefinition, registry, - VAULT_ADAPTER_BEAN_NAME, configurationSource); + registerIfNotAlreadyRegistered(() -> vaultKeyValueAdapterDefinition, registry, VAULT_ADAPTER_BEAN_NAME, + configurationSource); - Optional<String> keyValueTemplateName = configurationSource - .getAttribute(KEY_VALUE_TEMPLATE_BEAN_REF_ATTRIBUTE); + Optional<String> keyValueTemplateName = configurationSource.getAttribute(KEY_VALUE_TEMPLATE_BEAN_REF_ATTRIBUTE); // No custom template reference configured and no matching bean definition found - if (keyValueTemplateName.isPresent() - && getDefaultKeyValueTemplateRef().equals(keyValueTemplateName.get()) + if (keyValueTemplateName.isPresent() && getDefaultKeyValueTemplateRef().equals(keyValueTemplateName.get()) && !registry.containsBeanDefinition(keyValueTemplateName.get())) { - registerIfNotAlreadyRegistered( - () -> getDefaultKeyValueTemplateBeanDefinition(configurationSource), - registry, keyValueTemplateName.get(), - configurationSource.getSource()); + registerIfNotAlreadyRegistered(() -> getDefaultKeyValueTemplateBeanDefinition(configurationSource), + registry, keyValueTemplateName.get(), configurationSource.getSource()); } super.registerBeansForRoot(registry, configurationSource); } - private RootBeanDefinition createVaultMappingContext( - RepositoryConfigurationSource configurationSource) { + private RootBeanDefinition createVaultMappingContext(RepositoryConfigurationSource configurationSource) { ConstructorArgumentValues mappingContextArgs = new ConstructorArgumentValues(); - RootBeanDefinition mappingContextBeanDef = new RootBeanDefinition( - VaultMappingContext.class); + RootBeanDefinition mappingContextBeanDef = new RootBeanDefinition(VaultMappingContext.class); mappingContextBeanDef.setConstructorArgumentValues(mappingContextArgs); mappingContextBeanDef.setSource(configurationSource.getSource()); @@ -124,8 +113,7 @@ public class VaultRepositoryConfigurationExtension protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition( RepositoryConfigurationSource configurationSource) { - RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition( - VaultKeyValueTemplate.class); + RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition(VaultKeyValueTemplate.class); ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues(); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(0, @@ -134,19 +122,19 @@ public class VaultRepositoryConfigurationExtension constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(1, new RuntimeBeanReference(VAULT_MAPPING_CONTEXT_BEAN_NAME)); - keyValueTemplateDefinition.setConstructorArgumentValues( - constructorArgumentValuesForKeyValueTemplate); + keyValueTemplateDefinition.setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate); return keyValueTemplateDefinition; } @Override protected Collection<Class<? extends Annotation>> getIdentifyingAnnotations() { - return Collections.<Class<? extends Annotation>> singleton(Secret.class); + return Collections.<Class<? extends Annotation>>singleton(Secret.class); } @Override protected String getMappingContextBeanRef() { return VAULT_MAPPING_CONTEXT_BEAN_NAME; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/AbstractVaultConverter.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/AbstractVaultConverter.java index 1c7f5fec..4298bf73 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/AbstractVaultConverter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/AbstractVaultConverter.java @@ -39,7 +39,6 @@ public abstract class AbstractVaultConverter implements VaultConverter, Initiali /** * Creates a new {@link AbstractVaultConverter} using the given * {@link GenericConversionService}. - * * @param conversionService must not be {@literal null}. */ public AbstractVaultConverter(GenericConversionService conversionService) { @@ -48,7 +47,6 @@ public abstract class AbstractVaultConverter implements VaultConverter, Initiali /** * Registers the given custom conversions with the converter. - * * @param conversions */ public void setCustomConversions(CustomConversions conversions) { @@ -57,7 +55,6 @@ public abstract class AbstractVaultConverter implements VaultConverter, Initiali /** * Registers {@link EntityInstantiators} to customize entity instantiation. - * * @param instantiators */ public void setInstantiators(EntityInstantiators instantiators) { @@ -66,7 +63,7 @@ public abstract class AbstractVaultConverter implements VaultConverter, Initiali @Override public ConversionService getConversionService() { - return conversionService; + return this.conversionService; } @Override @@ -79,6 +76,7 @@ public abstract class AbstractVaultConverter implements VaultConverter, Initiali * {@link ConversionService} directly (e.g. for id conversion). */ private void initializeConverters() { - conversions.registerConvertersIn(conversionService); + this.conversions.registerConvertersIn(this.conversionService); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapper.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapper.java index 0b476a45..62c96804 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapper.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapper.java @@ -39,14 +39,12 @@ import org.springframework.lang.Nullable; * @author Mark Paluch * @since 2.0 */ -public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object>> - implements VaultTypeMapper { +public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object>> implements VaultTypeMapper { public static final String DEFAULT_TYPE_KEY = "_class"; @SuppressWarnings("rawtypes") - private static final TypeInformation<Map> MAP_TYPE_INFO = ClassTypeInformation - .from(Map.class); + private static final TypeInformation<Map> MAP_TYPE_INFO = ClassTypeInformation.from(Map.class); private final @Nullable String typeKey; @@ -61,7 +59,6 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object /** * Creates a default {@link VaultTypeMapper} that exchanges types using the given * {@code typeKey}. - * * @param typeKey may not be {@literal null} to disable type hinting. */ public DefaultVaultTypeMapper(@Nullable String typeKey) { @@ -71,7 +68,6 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object /** * Creates a default {@link VaultTypeMapper} that exchanges types using the given * {@code typeKey} and {@link MappingContext}. - * * @param typeKey may not be {@literal null} to disable type hinting. * @param mappingContext must not be {@literal null} or empty. */ @@ -81,13 +77,11 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object Collections.singletonList(new SimpleTypeInformationMapper())); } - public DefaultVaultTypeMapper(@Nullable String typeKey, - List<? extends TypeInformationMapper> mappers) { + public DefaultVaultTypeMapper(@Nullable String typeKey, List<? extends TypeInformationMapper> mappers) { this(typeKey, new SecretDocumentTypeAliasAccessor(typeKey), null, mappers); } - private DefaultVaultTypeMapper(@Nullable String typeKey, - TypeAliasAccessor<Map<String, Object>> accessor, + private DefaultVaultTypeMapper(@Nullable String typeKey, TypeAliasAccessor<Map<String, Object>> accessor, MappingContext<? extends PersistentEntity<?, ?>, ?> mappingContext, List<? extends TypeInformationMapper> mappers) { @@ -98,12 +92,11 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object /** * Checks whether the given key name matches the {@literal typeKey}. - * * @param key * @return {@literal true} if {@code key} matches the {@literal typeKey}. */ public boolean isTypeKey(String key) { - return typeKey != null && typeKey.equals(key); + return this.typeKey != null && this.typeKey.equals(key); } @Override @@ -116,8 +109,7 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object * * @author Mark Paluch */ - static class SecretDocumentTypeAliasAccessor - implements TypeAliasAccessor<Map<String, Object>> { + static class SecretDocumentTypeAliasAccessor implements TypeAliasAccessor<Map<String, Object>> { private final @Nullable String typeKey; @@ -126,13 +118,15 @@ public class DefaultVaultTypeMapper extends DefaultTypeMapper<Map<String, Object } public Alias readAliasFrom(Map<String, Object> source) { - return typeKey == null ? Alias.NONE : Alias.ofNullable(source.get(typeKey)); + return this.typeKey == null ? Alias.NONE : Alias.ofNullable(source.get(this.typeKey)); } public void writeTypeTo(Map<String, Object> sink, Object alias) { - if (typeKey != null) { - sink.put(typeKey, alias); + if (this.typeKey != null) { + sink.put(this.typeKey, alias); } } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/MappingVaultConverter.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/MappingVaultConverter.java index c169d24f..46c7cbe6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/MappingVaultConverter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/MappingVaultConverter.java @@ -68,8 +68,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { Assert.notNull(mappingContext, "MappingContext must not be null"); this.mappingContext = mappingContext; - this.typeMapper = new DefaultVaultTypeMapper( - DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, mappingContext); + this.typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, mappingContext); } /** @@ -78,7 +77,6 @@ public class MappingVaultConverter extends AbstractVaultConverter { * from {@link SecretDocument}s when reading them. Uses a * {@link DefaultVaultTypeMapper} by default. Setting this to {@literal null} will * reset the {@link org.springframework.data.convert.TypeMapper} to the default one. - * * @param typeMapper the typeMapper to set, must not be {@literal null}. */ public void setTypeMapper(VaultTypeMapper typeMapper) { @@ -89,7 +87,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { @Override public MappingContext<? extends VaultPersistentEntity<?>, VaultPersistentProperty> getMappingContext() { - return mappingContext; + return this.mappingContext; } @Override @@ -103,12 +101,12 @@ public class MappingVaultConverter extends AbstractVaultConverter { SecretDocument secretDocument = getSecretDocument(source); TypeInformation<? extends S> typeToUse = secretDocument != null - ? typeMapper.readType(secretDocument.getBody(), type) + ? this.typeMapper.readType(secretDocument.getBody(), type) : (TypeInformation) ClassTypeInformation.OBJECT; Class<? extends S> rawType = typeToUse.getType(); - if (conversions.hasCustomReadTarget(source.getClass(), rawType)) { - return conversionService.convert(source, rawType); + if (this.conversions.hasCustomReadTarget(source.getClass(), rawType)) { + return this.conversionService.convert(source, rawType); } if (SecretDocument.class.isAssignableFrom(rawType)) { @@ -127,8 +125,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { return (S) source; } - return read((VaultPersistentEntity<S>) mappingContext - .getRequiredPersistentEntity(typeToUse), secretDocument); + return read((VaultPersistentEntity<S>) this.mappingContext.getRequiredPersistentEntity(typeToUse), + secretDocument); } @Nullable @@ -145,8 +143,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { return secretDocument; } - private ParameterValueProvider<VaultPersistentProperty> getParameterProvider( - VaultPersistentEntity<?> entity, SecretDocument source) { + private ParameterValueProvider<VaultPersistentProperty> getParameterProvider(VaultPersistentEntity<?> entity, + SecretDocument source) { VaultPropertyValueProvider provider = new VaultPropertyValueProvider(source); @@ -157,8 +155,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { @Nullable @Override - public <T> T getParameterValue( - Parameter<T, VaultPersistentProperty> parameter) { + public <T> T getParameterValue(Parameter<T, VaultPersistentProperty> parameter) { Object value = parameterProvider.getParameterValue(parameter); return value != null ? readValue(value, parameter.getType()) : null; @@ -168,13 +165,12 @@ public class MappingVaultConverter extends AbstractVaultConverter { private <S> S read(VaultPersistentEntity<S> entity, SecretDocument source) { - ParameterValueProvider<VaultPersistentProperty> provider = getParameterProvider( - entity, source); - EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity); + ParameterValueProvider<VaultPersistentProperty> provider = getParameterProvider(entity, source); + EntityInstantiator instantiator = this.instantiators.getInstantiatorFor(entity); S instance = instantiator.createInstance(entity, provider); - PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor( - entity.getPropertyAccessor(instance), conversionService); + PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance), + this.conversionService); VaultPersistentProperty idProperty = entity.getIdProperty(); SecretDocumentAccessor documentAccessor = new SecretDocumentAccessor(source); @@ -190,8 +186,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { accessor.setProperty(idProperty, idValue); } - VaultPropertyValueProvider valueProvider = new VaultPropertyValueProvider( - documentAccessor); + VaultPropertyValueProvider valueProvider = new VaultPropertyValueProvider(documentAccessor); readProperties(entity, accessor, idProperty, documentAccessor, valueProvider); } @@ -200,20 +195,15 @@ public class MappingVaultConverter extends AbstractVaultConverter { } @Nullable - private Object readIdValue(VaultPersistentProperty idProperty, - SecretDocumentAccessor documentAccessor) { + private Object readIdValue(VaultPersistentProperty idProperty, SecretDocumentAccessor documentAccessor) { Object resolvedValue = documentAccessor.get(idProperty); - return resolvedValue != null - ? readValue(resolvedValue, idProperty.getTypeInformation()) - : null; + return resolvedValue != null ? readValue(resolvedValue, idProperty.getTypeInformation()) : null; } - private void readProperties(VaultPersistentEntity<?> entity, - PersistentPropertyAccessor accessor, - @Nullable VaultPersistentProperty idProperty, - SecretDocumentAccessor documentAccessor, + private void readProperties(VaultPersistentEntity<?> entity, PersistentPropertyAccessor accessor, + @Nullable VaultPersistentProperty idProperty, SecretDocumentAccessor documentAccessor, VaultPropertyValueProvider valueProvider) { for (VaultPersistentProperty prop : entity) { @@ -237,8 +227,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { Class<?> rawType = type.getType(); - if (conversions.hasCustomReadTarget(value.getClass(), rawType)) { - return (T) conversionService.convert(value, rawType); + if (this.conversions.hasCustomReadTarget(value.getClass(), rawType)) { + return (T) this.conversionService.convert(value, rawType); } else if (value instanceof List) { return (T) readCollectionOrArray(type, (List) value); @@ -254,32 +244,25 @@ public class MappingVaultConverter extends AbstractVaultConverter { /** * Reads the given {@link List} into a collection of the given {@link TypeInformation} * . - * * @param targetType must not be {@literal null}. * @param sourceValue must not be {@literal null}. * @return the converted {@link Collection} or array, will never be {@literal null}. */ @Nullable @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object readCollectionOrArray(TypeInformation<?> targetType, - List sourceValue) { + private Object readCollectionOrArray(TypeInformation<?> targetType, List sourceValue) { Assert.notNull(targetType, "Target type must not be null"); Class<?> collectionType = targetType.getType(); - TypeInformation<?> componentType = targetType.getComponentType() != null - ? targetType.getComponentType() + TypeInformation<?> componentType = targetType.getComponentType() != null ? targetType.getComponentType() : ClassTypeInformation.OBJECT; Class<?> rawComponentType = componentType.getType(); - collectionType = Collection.class.isAssignableFrom(collectionType) - ? collectionType - : List.class; - Collection<Object> items = targetType.getType().isArray() - ? new ArrayList<>(sourceValue.size()) - : CollectionFactory.createCollection(collectionType, rawComponentType, - sourceValue.size()); + collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class; + Collection<Object> items = targetType.getType().isArray() ? new ArrayList<>(sourceValue.size()) + : CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size()); if (sourceValue.isEmpty()) { return getPotentiallyConvertedSimpleRead(items, collectionType); @@ -304,18 +287,16 @@ public class MappingVaultConverter extends AbstractVaultConverter { /** * Reads the given {@link Map} into a {@link Map}. will recursively resolve nested * {@link Map}s as well. - * * @param type the {@link Map} {@link TypeInformation} to be used to unmarshal this - * {@link Map}. + * {@link Map}. * @param sourceMap must not be {@literal null} * @return the converted {@link Map}. */ - protected Map<Object, Object> readMap(TypeInformation<?> type, - Map<String, Object> sourceMap) { + protected Map<Object, Object> readMap(TypeInformation<?> type, Map<String, Object> sourceMap) { Assert.notNull(sourceMap, "Source map must not be null"); - Class<?> mapType = typeMapper.readType(sourceMap, type).getType(); + Class<?> mapType = this.typeMapper.readType(sourceMap, type).getType(); TypeInformation<?> keyType = type.getComponentType(); TypeInformation<?> valueType = type.getMapValueType(); @@ -323,33 +304,29 @@ public class MappingVaultConverter extends AbstractVaultConverter { Class<?> rawKeyType = keyType != null ? keyType.getType() : null; Class<?> rawValueType = valueType != null ? valueType.getType() : null; - Map<Object, Object> map = CollectionFactory.createMap(mapType, rawKeyType, - sourceMap.keySet().size()); + Map<Object, Object> map = CollectionFactory.createMap(mapType, rawKeyType, sourceMap.keySet().size()); for (Entry<String, Object> entry : sourceMap.entrySet()) { - if (typeMapper.isTypeKey(entry.getKey())) { + if (this.typeMapper.isTypeKey(entry.getKey())) { continue; } Object key = entry.getKey(); if (rawKeyType != null && !rawKeyType.isAssignableFrom(key.getClass())) { - key = conversionService.convert(key, rawKeyType); + key = this.conversionService.convert(key, rawKeyType); } Object value = entry.getValue(); - TypeInformation<?> defaultedValueType = valueType != null ? valueType - : ClassTypeInformation.OBJECT; + TypeInformation<?> defaultedValueType = valueType != null ? valueType : ClassTypeInformation.OBJECT; if (value instanceof Map) { map.put(key, read(defaultedValueType, (Map) value)); } else if (value instanceof List) { map.put(key, - readCollectionOrArray( - valueType != null ? valueType : ClassTypeInformation.LIST, - (List) value)); + readCollectionOrArray(valueType != null ? valueType : ClassTypeInformation.LIST, (List) value)); } else { map.put(key, getPotentiallyConvertedSimpleRead(value, rawValueType)); @@ -362,18 +339,15 @@ public class MappingVaultConverter extends AbstractVaultConverter { /** * Checks whether we have a custom conversion for the given simple object. Converts * the given value if so, applies {@link Enum} handling or returns the value as is. - * * @param value * @param target must not be {@literal null}. * @return */ @Nullable @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object getPotentiallyConvertedSimpleRead(@Nullable Object value, - @Nullable Class<?> target) { + private Object getPotentiallyConvertedSimpleRead(@Nullable Object value, @Nullable Class<?> target) { - if (value == null || target == null - || target.isAssignableFrom(value.getClass())) { + if (value == null || target == null || target.isAssignableFrom(value.getClass())) { return value; } @@ -381,7 +355,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { return Enum.valueOf((Class<Enum>) target, value.toString()); } - return conversionService.convert(value, target); + return this.conversionService.convert(value, target); } @Override @@ -394,31 +368,27 @@ public class MappingVaultConverter extends AbstractVaultConverter { writeInternal(source, documentAccessor, type); - boolean handledByCustomConverter = conversions.hasCustomWriteTarget(entityType, - SecretDocument.class); + boolean handledByCustomConverter = this.conversions.hasCustomWriteTarget(entityType, SecretDocument.class); if (!handledByCustomConverter) { - typeMapper.writeType(type, sink.getBody()); + this.typeMapper.writeType(type, sink.getBody()); } } /** * Internal write conversion method which should be used for nested invocations. - * * @param obj * @param sink * @param typeHint */ @SuppressWarnings("unchecked") - protected void writeInternal(Object obj, SecretDocumentAccessor sink, - @Nullable TypeInformation<?> typeHint) { + protected void writeInternal(Object obj, SecretDocumentAccessor sink, @Nullable TypeInformation<?> typeHint) { Class<?> entityType = obj.getClass(); - Optional<Class<?>> customTarget = conversions.getCustomWriteTarget(entityType, - SecretDocument.class); + Optional<Class<?>> customTarget = this.conversions.getCustomWriteTarget(entityType, SecretDocument.class); if (customTarget.isPresent()) { - SecretDocument result = conversionService.convert(obj, SecretDocument.class); + SecretDocument result = this.conversionService.convert(obj, SecretDocument.class); if (result.getId() != null) { sink.setId(result.getId()); @@ -429,19 +399,16 @@ public class MappingVaultConverter extends AbstractVaultConverter { } if (Map.class.isAssignableFrom(entityType)) { - writeMapInternal((Map<Object, Object>) obj, sink.getBody(), - ClassTypeInformation.MAP); + writeMapInternal((Map<Object, Object>) obj, sink.getBody(), ClassTypeInformation.MAP); return; } - VaultPersistentEntity<?> entity = mappingContext - .getRequiredPersistentEntity(entityType); + VaultPersistentEntity<?> entity = this.mappingContext.getRequiredPersistentEntity(entityType); writeInternal(obj, sink, entity); addCustomTypeKeyIfNecessary(typeHint, obj, sink); } - protected void writeInternal(Object obj, SecretDocumentAccessor sink, - VaultPersistentEntity<?> entity) { + protected void writeInternal(Object obj, SecretDocumentAccessor sink, VaultPersistentEntity<?> entity) { PersistentPropertyAccessor accessor = entity.getPropertyAccessor(obj); @@ -457,9 +424,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { writeProperties(entity, accessor, sink, idProperty); } - private void writeProperties(VaultPersistentEntity<?> entity, - PersistentPropertyAccessor accessor, SecretDocumentAccessor sink, - @Nullable VaultPersistentProperty idProperty) { + private void writeProperties(VaultPersistentEntity<?> entity, PersistentPropertyAccessor accessor, + SecretDocumentAccessor sink, @Nullable VaultPersistentProperty idProperty) { // Write the properties for (VaultPersistentProperty prop : entity) { @@ -474,7 +440,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { continue; } - if (!conversions.isSimpleType(value.getClass())) { + if (!this.conversions.isSimpleType(value.getClass())) { writePropertyInternal(value, sink, prop); } else { @@ -485,8 +451,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { } @SuppressWarnings({ "unchecked" }) - protected void writePropertyInternal(@Nullable Object obj, - SecretDocumentAccessor accessor, VaultPersistentProperty prop) { + protected void writePropertyInternal(@Nullable Object obj, SecretDocumentAccessor accessor, + VaultPersistentProperty prop) { if (obj == null) { return; @@ -508,24 +474,22 @@ public class MappingVaultConverter extends AbstractVaultConverter { } // Lookup potential custom target type - Optional<Class<?>> basicTargetType = conversions - .getCustomWriteTarget(obj.getClass()); + Optional<Class<?>> basicTargetType = this.conversions.getCustomWriteTarget(obj.getClass()); if (basicTargetType.isPresent()) { - accessor.put(prop, conversionService.convert(obj, basicTargetType.get())); + accessor.put(prop, this.conversionService.convert(obj, basicTargetType.get())); return; } VaultPersistentEntity<?> entity = isSubtype(prop.getType(), obj.getClass()) - ? mappingContext.getRequiredPersistentEntity(obj.getClass()) - : mappingContext.getRequiredPersistentEntity(type); + ? this.mappingContext.getRequiredPersistentEntity(obj.getClass()) + : this.mappingContext.getRequiredPersistentEntity(type); SecretDocumentAccessor nested = accessor.writeNested(prop); writeInternal(obj, nested, entity); - addCustomTypeKeyIfNecessary(ClassTypeInformation.from(prop.getRawType()), obj, - nested); + addCustomTypeKeyIfNecessary(ClassTypeInformation.from(prop.getRawType()), obj, nested); } private static boolean isSubtype(Class<?> left, Class<?> right) { @@ -535,29 +499,25 @@ public class MappingVaultConverter extends AbstractVaultConverter { /** * Writes the given {@link Collection} using the given {@link VaultPersistentProperty} * information. - * * @param collection must not be {@literal null}. * @param property must not be {@literal null}. * @return the converted {@link List}. */ - protected List<Object> createCollection(Collection<?> collection, - VaultPersistentProperty property) { + protected List<Object> createCollection(Collection<?> collection, VaultPersistentProperty property) { - return writeCollectionInternal(collection, property.getTypeInformation(), - new ArrayList<>()); + return writeCollectionInternal(collection, property.getTypeInformation(), new ArrayList<>()); } /** * Populates the given {@link List} with values from the given {@link Collection}. - * * @param source the collection to create a {@link List} for, must not be - * {@literal null}. + * {@literal null}. * @param type the {@link TypeInformation} to consider or {@literal null} if unknown. * @param sink the {@link List} to write to. * @return the converted {@link List}. */ - private List<Object> writeCollectionInternal(Collection<?> source, - @Nullable TypeInformation<?> type, List<Object> sink) { + private List<Object> writeCollectionInternal(Collection<?> source, @Nullable TypeInformation<?> type, + List<Object> sink) { TypeInformation<?> componentType = null; @@ -569,16 +529,14 @@ public class MappingVaultConverter extends AbstractVaultConverter { Class<?> elementType = element == null ? null : element.getClass(); - if (elementType == null || conversions.isSimpleType(elementType)) { + if (elementType == null || this.conversions.isSimpleType(elementType)) { sink.add(getPotentiallyConvertedSimpleWrite(element)); } else if (element instanceof Collection || elementType.isArray()) { - sink.add(writeCollectionInternal(asCollection(element), componentType, - new ArrayList<>())); + sink.add(writeCollectionInternal(asCollection(element), componentType, new ArrayList<>())); } else { - SecretDocumentAccessor accessor = new SecretDocumentAccessor( - new SecretDocument()); + SecretDocumentAccessor accessor = new SecretDocumentAccessor(new SecretDocument()); writeInternal(element, accessor, componentType); sink.add(accessor.getBody()); } @@ -590,54 +548,48 @@ public class MappingVaultConverter extends AbstractVaultConverter { /** * Writes the given {@link Map} using the given {@link VaultPersistentProperty} * information. - * * @param map must not {@literal null}. * @param property must not be {@literal null}. * @return the converted {@link Map}. */ - protected Map<String, Object> createMap(Map<Object, Object> map, - VaultPersistentProperty property) { + protected Map<String, Object> createMap(Map<Object, Object> map, VaultPersistentProperty property) { Assert.notNull(map, "Given map must not be null"); Assert.notNull(property, "PersistentProperty must not be null"); - return writeMapInternal(map, new LinkedHashMap<>(), - property.getTypeInformation()); + return writeMapInternal(map, new LinkedHashMap<>(), property.getTypeInformation()); } /** * Writes the given {@link Map} to the given {@link Map} considering the given * {@link TypeInformation}. - * * @param obj must not be {@literal null}. * @param bson must not be {@literal null}. * @param propertyType must not be {@literal null}. * @return the converted {@link Map}. */ - protected Map<String, Object> writeMapInternal(Map<Object, Object> obj, - Map<String, Object> bson, TypeInformation<?> propertyType) { + protected Map<String, Object> writeMapInternal(Map<Object, Object> obj, Map<String, Object> bson, + TypeInformation<?> propertyType) { for (Entry<Object, Object> entry : obj.entrySet()) { Object key = entry.getKey(); Object val = entry.getValue(); - if (conversions.isSimpleType(key.getClass())) { + if (this.conversions.isSimpleType(key.getClass())) { String simpleKey = key.toString(); - if (val == null || conversions.isSimpleType(val.getClass())) { + if (val == null || this.conversions.isSimpleType(val.getClass())) { bson.put(simpleKey, val); } else if (val instanceof Collection || val.getClass().isArray()) { - bson.put(simpleKey, writeCollectionInternal(asCollection(val), - propertyType.getMapValueType(), new ArrayList<>())); + bson.put(simpleKey, writeCollectionInternal(asCollection(val), propertyType.getMapValueType(), + new ArrayList<>())); } else { - SecretDocumentAccessor nested = new SecretDocumentAccessor( - new SecretDocument()); - TypeInformation<?> valueTypeInfo = propertyType.isMap() - ? propertyType.getMapValueType() + SecretDocumentAccessor nested = new SecretDocumentAccessor(new SecretDocument()); + TypeInformation<?> valueTypeInfo = propertyType.isMap() ? propertyType.getMapValueType() : ClassTypeInformation.OBJECT; writeInternal(val, nested, valueTypeInfo); bson.put(simpleKey, nested.getBody()); @@ -655,20 +607,19 @@ public class MappingVaultConverter extends AbstractVaultConverter { * Adds custom type information to the given {@link SecretDocument} if necessary. That * is if the value is not the same as the one given. This is usually the case if you * store a subtype of the actual declared type of the property. - * * @param type type hint. * @param value must not be {@literal null}. * @param accessor must not be {@literal null}. */ - protected void addCustomTypeKeyIfNecessary(@Nullable TypeInformation<?> type, - Object value, SecretDocumentAccessor accessor) { + protected void addCustomTypeKeyIfNecessary(@Nullable TypeInformation<?> type, Object value, + SecretDocumentAccessor accessor) { Class<?> reference = type != null ? type.getActualType().getType() : Object.class; Class<?> valueType = ClassUtils.getUserClass(value.getClass()); boolean notTheSameClass = !valueType.equals(reference); if (notTheSameClass) { - typeMapper.writeType(valueType, accessor.getBody()); + this.typeMapper.writeType(valueType, accessor.getBody()); } } @@ -676,7 +627,6 @@ public class MappingVaultConverter extends AbstractVaultConverter { * Checks whether we have a custom conversion registered for the given value into an * arbitrary simple Vault type. Returns the converted value if so. If not, we perform * special enum handling or simply return the value as is. - * * @param value the value to write. * @return the converted value. Can be {@literal null}. */ @@ -687,11 +637,10 @@ public class MappingVaultConverter extends AbstractVaultConverter { return null; } - Optional<Class<?>> customTarget = conversions - .getCustomWriteTarget(value.getClass()); + Optional<Class<?>> customTarget = this.conversions.getCustomWriteTarget(value.getClass()); if (customTarget.isPresent()) { - return conversionService.convert(value, customTarget.get()); + return this.conversionService.convert(value, customTarget.get()); } if (ObjectUtils.isArray(value)) { @@ -702,8 +651,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { return asCollection(value); } - return Enum.class.isAssignableFrom(value.getClass()) ? ((Enum<?>) value).name() - : value; + return Enum.class.isAssignableFrom(value.getClass()) ? ((Enum<?>) value).name() : value; } /** @@ -711,9 +659,8 @@ public class MappingVaultConverter extends AbstractVaultConverter { * is if the source is a {@link Collection} already, will convert an array into a * {@link Collection} or simply create a single element collection for everything * else. - * * @param source the collection object. Can be a {@link Collection}, array or - * singleton object. + * singleton object. * @return the {@code source} as {@link Collection}. */ private static Collection<?> asCollection(Object source) { @@ -722,8 +669,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { return (Collection<?>) source; } - return source.getClass().isArray() ? CollectionUtils.arrayToList(source) - : Collections.singleton(source); + return source.getClass().isArray() ? CollectionUtils.arrayToList(source) : Collections.singleton(source); } /** @@ -732,8 +678,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { * {@link SecretDocument}. * */ - class VaultPropertyValueProvider - implements PropertyValueProvider<VaultPersistentProperty> { + class VaultPropertyValueProvider implements PropertyValueProvider<VaultPersistentProperty> { private final SecretDocumentAccessor source; @@ -754,7 +699,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { @Nullable public <T> T getPropertyValue(VaultPersistentProperty property) { - Object value = source.get(property); + Object value = this.source.get(property); if (value == null) { return null; @@ -762,5 +707,7 @@ public class MappingVaultConverter extends AbstractVaultConverter { return readValue(value, property.getTypeInformation()); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocument.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocument.java index 040356c0..e4837cc0 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocument.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocument.java @@ -76,7 +76,6 @@ public class SecretDocument { /** * Factory method to create a {@link SecretDocument} from an {@code id} and * {@link VaultResponse}. - * * @param id must not be {@literal null}. * @param vaultResponse must not be {@literal null}. * @return the {@link SecretDocument}. @@ -91,12 +90,11 @@ public class SecretDocument { */ @Nullable public String getId() { - return id; + return this.id; } /** * Set the Id. - * * @param id may be {@literal null}. */ public void setId(@Nullable String id) { @@ -107,23 +105,21 @@ public class SecretDocument { * @return the body of this {@link SecretDocument} */ public Map<String, Object> getBody() { - return body; + return this.body; } /** * Retrieve a value from the secret document by its {@code key}. - * * @param key must not be {@literal null}. * @return the value or {@literal null}, if the value is not present. */ @Nullable public Object get(String key) { - return body.get(key); + return this.body.get(key); } /** * Set a value in the secret document. - * * @param key must not be {@literal null}. * @param value must not be {@literal null}. */ @@ -138,21 +134,22 @@ public class SecretDocument { if (!(o instanceof SecretDocument)) return false; SecretDocument that = (SecretDocument) o; - return Objects.equals(id, that.id) && Objects.equals(body, that.body); + return Objects.equals(this.id, that.id) && Objects.equals(this.body, that.body); } @Override public int hashCode() { - return Objects.hash(id, body); + return Objects.hash(this.id, this.body); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [id='").append(id).append('\''); - sb.append(", body=").append(body); + sb.append(" [id='").append(this.id).append('\''); + sb.append(", body=").append(this.body); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocumentAccessor.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocumentAccessor.java index 5ac66aa7..fe317442 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocumentAccessor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/SecretDocumentAccessor.java @@ -42,9 +42,8 @@ class SecretDocumentAccessor { /** * Creates a new {@link SecretDocumentAccessor} for the given {@link SecretDocument}. - * * @param document must be a {@link SecretDocument} effectively, must not be - * {@literal null}. + * {@literal null}. */ SecretDocumentAccessor(SecretDocument document) { @@ -57,9 +56,8 @@ class SecretDocumentAccessor { /** * Creates a new {@link SecretDocumentAccessor} for the given {@link SecretDocument} * and {@link Map body}. - * * @param document must be a {@link SecretDocument} effectively, must not be - * {@literal null} + * {@literal null} * @param body must not be {@literal null}. */ private SecretDocumentAccessor(SecretDocument document, Map<String, Object> body) { @@ -76,7 +74,6 @@ class SecretDocumentAccessor { * coordinates defined through the given {@link VaultPersistentProperty}. By default * this will be the plain field name. But field names might also consist of path * traversals so we might need to create intermediate {@link Map}s. - * * @param prop must not be {@literal null}. * @param value */ @@ -116,7 +113,6 @@ class SecretDocumentAccessor { * this will be a direct field but the method will also transparently resolve nested * values the {@link VaultPersistentProperty} might refer to through a path expression * in the field name metadata. - * * @param property must not be {@literal null}. * @return */ @@ -152,7 +148,6 @@ class SecretDocumentAccessor { /** * Returns whether the underlying {@link SecretDocument} has a value ({@literal null} * or non-{@literal null}) for the given {@link VaultPersistentProperty}. - * * @param property must not be {@literal null}. * @return */ @@ -191,7 +186,6 @@ class SecretDocumentAccessor { /** * Returns the given source object as map, i.e. maps as is or {@literal null} * otherwise. - * * @param source can be {@literal null}. * @return */ @@ -210,14 +204,12 @@ class SecretDocumentAccessor { * Returns the {@link Map} which either already exists in the given source under the * given key, or creates a new nested one, registers it with the source and returns * it. - * * @param key must not be {@literal null} or empty. * @param source must not be {@literal null}. * @return */ @SuppressWarnings("unchecked") - private static Map<String, Object> getOrCreateNestedDocument(String key, - Map<String, Object> source) { + private static Map<String, Object> getOrCreateNestedDocument(String key, Map<String, Object> source) { Object existing = source.get(key); @@ -232,7 +224,7 @@ class SecretDocumentAccessor { } public Map<String, Object> getBody() { - return body; + return this.body; } public void setId(String id) { @@ -243,7 +235,6 @@ class SecretDocumentAccessor { * Obtains a nested {@link SecretDocumentAccessor} for a * {@link VaultPersistentProperty}. Nested accessors allows mapping of structured * hierarchies and represent accessors to nested maps. - * * @param property must not be {@literal null}. * @return */ @@ -257,6 +248,7 @@ class SecretDocumentAccessor { put(property, body); } - return new SecretDocumentAccessor(document, body); + return new SecretDocumentAccessor(this.document, body); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultConverter.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultConverter.java index 40d9aa01..8a20e395 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultConverter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultConverter.java @@ -24,6 +24,7 @@ import org.springframework.vault.repository.mapping.VaultPersistentProperty; * * @since 2.0 */ -public interface VaultConverter extends - EntityConverter<VaultPersistentEntity<?>, VaultPersistentProperty, Object, SecretDocument> { +public interface VaultConverter + extends EntityConverter<VaultPersistentEntity<?>, VaultPersistentProperty, Object, SecretDocument> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultCustomConversions.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultCustomConversions.java index 109ec9d3..8f869bbc 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultCustomConversions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultCustomConversions.java @@ -40,8 +40,7 @@ import org.springframework.vault.repository.mapping.VaultSimpleTypes; * @see org.springframework.data.mapping.model.SimpleTypeHolder * @see VaultSimpleTypes */ -public class VaultCustomConversions - extends org.springframework.data.convert.CustomConversions { +public class VaultCustomConversions extends org.springframework.data.convert.CustomConversions { private static final StoreConversions STORE_CONVERSIONS; @@ -55,8 +54,7 @@ public class VaultCustomConversions converters.addAll(JodaTimeConverters.getConvertersToRegister()); STORE_CONVERTERS = Collections.unmodifiableList(converters); - STORE_CONVERSIONS = StoreConversions.of(VaultSimpleTypes.HOLDER, - STORE_CONVERTERS); + STORE_CONVERSIONS = StoreConversions.of(VaultSimpleTypes.HOLDER, STORE_CONVERTERS); } /** @@ -69,7 +67,6 @@ public class VaultCustomConversions /** * Create a new {@link VaultCustomConversions} instance registering the given * converters. - * * @param converters must not be {@literal null}. */ public VaultCustomConversions(List<?> converters) { @@ -83,18 +80,17 @@ public class VaultCustomConversions public Set<ConvertiblePair> getConvertibleTypes() { - ConvertiblePair localeToString = new ConvertiblePair(Locale.class, - String.class); - ConvertiblePair booleanToString = new ConvertiblePair(Character.class, - String.class); + ConvertiblePair localeToString = new ConvertiblePair(Locale.class, String.class); + ConvertiblePair booleanToString = new ConvertiblePair(Character.class, String.class); return new HashSet<>(Arrays.asList(localeToString, booleanToString)); } @Nullable - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { return source != null ? source.toString() : null; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultTypeMapper.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultTypeMapper.java index 1eff17ea..fa608e1f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultTypeMapper.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/convert/VaultTypeMapper.java @@ -30,8 +30,8 @@ public interface VaultTypeMapper extends TypeMapper<Map<String, Object>> { /** * Returns whether the given {@code key} is the type key. - * * @return {@literal true} if the {@code key} is the type key. */ boolean isTypeKey(String key); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/MappingVaultEntityInformation.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/MappingVaultEntityInformation.java index 7ff11a61..a826025c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/MappingVaultEntityInformation.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/MappingVaultEntityInformation.java @@ -28,8 +28,8 @@ import org.springframework.vault.repository.mapping.VaultPersistentEntity; * @author Mark Paluch * @since 2.0 */ -public class MappingVaultEntityInformation<T, ID> extends - PersistentEntityInformation<T, ID> implements VaultEntityInformation<T, ID> { +public class MappingVaultEntityInformation<T, ID> extends PersistentEntityInformation<T, ID> + implements VaultEntityInformation<T, ID> { /** * @param entity @@ -45,4 +45,5 @@ public class MappingVaultEntityInformation<T, ID> extends entity.getName())); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultEntityInformation.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultEntityInformation.java index 4ad3f641..963ae66b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultEntityInformation.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultEntityInformation.java @@ -25,4 +25,5 @@ import org.springframework.data.repository.core.EntityInformation; * @since 2.0 */ public interface VaultEntityInformation<T, ID> extends EntityInformation<T, ID> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueAdapter.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueAdapter.java index 4e773df4..80f73276 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueAdapter.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueAdapter.java @@ -49,7 +49,6 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { /** * Create a new {@link VaultKeyValueAdapter} given {@link VaultOperations}. - * * @param vaultOperations must not be {@literal null}. */ public VaultKeyValueAdapter(VaultOperations vaultOperations) { @@ -59,12 +58,10 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { /** * Create a new {@link VaultKeyValueAdapter} given {@link VaultOperations} and * {@link VaultConverter}. - * * @param vaultOperations must not be {@literal null}. * @param vaultConverter must not be {@literal null}. */ - public VaultKeyValueAdapter(VaultOperations vaultOperations, - VaultConverter vaultConverter) { + public VaultKeyValueAdapter(VaultOperations vaultOperations, VaultConverter vaultConverter) { super(new VaultQueryEngine()); @@ -79,9 +76,9 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { public Object put(Object id, Object item, String keyspace) { SecretDocument secretDocument = new SecretDocument(id.toString()); - vaultConverter.write(item, secretDocument); + this.vaultConverter.write(item, secretDocument); - vaultOperations.write(createKey(id, keyspace), secretDocument.getBody()); + this.vaultOperations.write(createKey(id, keyspace), secretDocument.getBody()); return secretDocument; } @@ -101,7 +98,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { @Override public <T> T get(Object id, String keyspace, Class<T> type) { - VaultResponse response = vaultOperations.read(createKey(id, keyspace)); + VaultResponse response = this.vaultOperations.read(createKey(id, keyspace)); if (response == null) { return null; @@ -109,7 +106,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { SecretDocument document = SecretDocument.from(id.toString(), response); - return vaultConverter.read(type, document); + return this.vaultConverter.read(type, document); } @Nullable @@ -128,7 +125,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { return null; } - vaultOperations.delete(createKey(id, keyspace)); + this.vaultOperations.delete(createKey(id, keyspace)); return entity; } @@ -200,7 +197,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { List<String> ids = doList(keyspace); for (String id : ids) { - vaultOperations.delete(createKey(id, keyspace)); + this.vaultOperations.delete(createKey(id, keyspace)); } } @@ -223,7 +220,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { List<String> doList(String keyspace) { - List<String> list = vaultOperations.list(keyspace); + List<String> list = this.vaultOperations.list(keyspace); return list == null ? Collections.emptyList() : list; } @@ -233,6 +230,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter { } MappingContext<? extends VaultPersistentEntity<?>, VaultPersistentProperty> getMappingContext() { - return vaultConverter.getMappingContext(); + return this.vaultConverter.getMappingContext(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueTemplate.java index 349b7dbc..3f247e30 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueTemplate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultKeyValueTemplate.java @@ -30,7 +30,6 @@ public class VaultKeyValueTemplate extends KeyValueTemplate { /** * Create a new {@link VaultKeyValueTemplate} given {@link KeyValueAdapter} and * {@link VaultMappingContext}. - * * @param adapter must not be {@literal null}. */ public VaultKeyValueTemplate(KeyValueAdapter adapter) { @@ -40,12 +39,10 @@ public class VaultKeyValueTemplate extends KeyValueTemplate { /** * Create a new {@link VaultKeyValueTemplate} given {@link KeyValueAdapter} and * {@link VaultMappingContext}. - * * @param adapter must not be {@literal null}. * @param mappingContext must not be {@literal null}. */ - public VaultKeyValueTemplate(KeyValueAdapter adapter, - VaultMappingContext mappingContext) { + public VaultKeyValueTemplate(KeyValueAdapter adapter, VaultMappingContext mappingContext) { super(adapter, mappingContext); } @@ -53,4 +50,5 @@ public class VaultKeyValueTemplate extends KeyValueTemplate { public void destroy() throws Exception { // no-op to prevent clear() call. } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultQueryEngine.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultQueryEngine.java index 3ef22ff7..3679dd5c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultQueryEngine.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/core/VaultQueryEngine.java @@ -40,8 +40,7 @@ import org.springframework.vault.repository.query.VaultQuery; * @see VaultQuery * @see org.springframework.vault.repository.query.VaultQueryCreator */ -class VaultQueryEngine - extends QueryEngine<VaultKeyValueAdapter, VaultQuery, Comparator<?>> { +class VaultQueryEngine extends QueryEngine<VaultKeyValueAdapter, VaultQuery, Comparator<?>> { private static final SpelExpressionParser parser = new SpelExpressionParser(); @@ -51,16 +50,15 @@ class VaultQueryEngine @Override @SuppressWarnings("unchecked") - public Collection<?> execute(@Nullable VaultQuery vaultQuery, - @Nullable Comparator<?> comparator, long offset, int rows, String keyspace) { + public Collection<?> execute(@Nullable VaultQuery vaultQuery, @Nullable Comparator<?> comparator, long offset, + int rows, String keyspace) { return execute(vaultQuery, comparator, offset, rows, keyspace, Object.class); } @Override @SuppressWarnings("unchecked") - public <T> Collection<T> execute(@Nullable VaultQuery vaultQuery, - @Nullable Comparator<?> comparator, long offset, int rows, String keyspace, - Class<T> type) { + public <T> Collection<T> execute(@Nullable VaultQuery vaultQuery, @Nullable Comparator<?> comparator, long offset, + int rows, String keyspace, Class<T> type) { Stream<String> stream = getRequiredAdapter().doList(keyspace).stream(); @@ -112,10 +110,12 @@ class VaultQueryEngine enum VaultCriteriaAccessor implements CriteriaAccessor<VaultQuery> { INSTANCE; + @Override public VaultQuery resolve(KeyValueQuery<?> query) { return (VaultQuery) query.getCriteria(); } + } } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntity.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntity.java index 66851559..aa0741a1 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntity.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntity.java @@ -31,23 +31,21 @@ import org.springframework.util.StringUtils; * @author Mark Paluch * @since 2.0 */ -public class BasicVaultPersistentEntity<T> - extends BasicKeyValuePersistentEntity<T, VaultPersistentProperty> +public class BasicVaultPersistentEntity<T> extends BasicKeyValuePersistentEntity<T, VaultPersistentProperty> implements VaultPersistentEntity<T> { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); private final String backend; + private final @Nullable Expression backendExpression; /** * Creates new {@link BasicVaultPersistentEntity}. - * * @param information must not be {@literal null}. * @param fallbackKeySpaceResolver can be {@literal null}. */ - public BasicVaultPersistentEntity(TypeInformation<T> information, - KeySpaceResolver fallbackKeySpaceResolver) { + public BasicVaultPersistentEntity(TypeInformation<T> information, KeySpaceResolver fallbackKeySpaceResolver) { super(information, fallbackKeySpaceResolver); Secret annotation = findAnnotation(Secret.class); @@ -68,15 +66,13 @@ public class BasicVaultPersistentEntity<T> * Returns a SpEL {@link Expression} if the given {@link String} is actually an * expression that does not evaluate to a {@link LiteralExpression} (indicating that * no subsequent evaluation is necessary). - * * @param potentialExpression can be {@literal null} * @return */ @Nullable private static Expression detectExpression(String potentialExpression) { - Expression expression = PARSER.parseExpression(potentialExpression, - ParserContext.TEMPLATE_EXPRESSION); + Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION); return expression instanceof LiteralExpression ? null : expression; } @@ -88,8 +84,9 @@ public class BasicVaultPersistentEntity<T> @Override public String getSecretBackend() { - return backendExpression == null // - ? backend // - : backendExpression.getValue(getEvaluationContext(null), String.class); + return this.backendExpression == null // + ? this.backend // + : this.backendExpression.getValue(getEvaluationContext(null), String.class); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/Secret.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/Secret.java index e81e29ec..7c3f78ad 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/Secret.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/Secret.java @@ -53,4 +53,5 @@ public @interface Secret { * expressions to dynamically calculate the backend based on a per-operation basis. */ String backend() default "secret"; + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultMappingContext.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultMappingContext.java index 71eb1652..57c03326 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultMappingContext.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultMappingContext.java @@ -30,13 +30,12 @@ import org.springframework.util.StringUtils; * @author Mark Paluch * @since 2.0 */ -public class VaultMappingContext extends - KeyValueMappingContext<VaultPersistentEntity<?>, VaultPersistentProperty> { +public class VaultMappingContext extends KeyValueMappingContext<VaultPersistentEntity<?>, VaultPersistentProperty> { private KeySpaceResolver fallbackKeySpaceResolver = SimpleClassNameKeySpaceResolver.INSTANCE; public KeySpaceResolver getFallbackKeySpaceResolver() { - return fallbackKeySpaceResolver; + return this.fallbackKeySpaceResolver; } @Override @@ -45,15 +44,13 @@ public class VaultMappingContext extends } @Override - protected <T> VaultPersistentEntity<?> createPersistentEntity( - TypeInformation<T> typeInformation) { - return new BasicVaultPersistentEntity<>(typeInformation, - fallbackKeySpaceResolver); + protected <T> VaultPersistentEntity<?> createPersistentEntity(TypeInformation<T> typeInformation) { + return new BasicVaultPersistentEntity<>(typeInformation, this.fallbackKeySpaceResolver); } @Override - protected VaultPersistentProperty createPersistentProperty(Property property, - VaultPersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) { + protected VaultPersistentProperty createPersistentProperty(Property property, VaultPersistentEntity<?> owner, + SimpleTypeHolder simpleTypeHolder) { return new VaultPersistentProperty(property, owner, simpleTypeHolder); } @@ -71,8 +68,9 @@ public class VaultMappingContext extends public String resolveKeySpace(Class<?> type) { Assert.notNull(type, "Type must not be null"); - return StringUtils - .uncapitalize(ClassUtils.getUserClass(type).getSimpleName()); + return StringUtils.uncapitalize(ClassUtils.getUserClass(type).getSimpleName()); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentEntity.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentEntity.java index a45678cf..8272ca98 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentEntity.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentEntity.java @@ -24,11 +24,11 @@ import org.springframework.data.mapping.PersistentEntity; * @author Mark Paluch * @since 2.0 */ -public interface VaultPersistentEntity<T> - extends KeyValuePersistentEntity<T, VaultPersistentProperty> { +public interface VaultPersistentEntity<T> extends KeyValuePersistentEntity<T, VaultPersistentProperty> { /** * @return the secret backend in which this {@link PersistentEntity} is stored. */ String getSecretBackend(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentProperty.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentProperty.java index 633ec3b5..9bbcd84e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentProperty.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultPersistentProperty.java @@ -30,8 +30,7 @@ import org.springframework.data.mapping.model.SimpleTypeHolder; * @author Mark Paluch * @since 2.0 */ -public class VaultPersistentProperty - extends KeyValuePersistentProperty<VaultPersistentProperty> { +public class VaultPersistentProperty extends KeyValuePersistentProperty<VaultPersistentProperty> { private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>(); @@ -41,13 +40,11 @@ public class VaultPersistentProperty /** * Create a new {@link VaultPersistentProperty}. - * * @param property must not be {@literal null}. * @param owner must not be {@literal null}. * @param simpleTypeHolder must not be {@literal null}. */ - public VaultPersistentProperty(Property property, - PersistentEntity<?, VaultPersistentProperty> owner, + public VaultPersistentProperty(Property property, PersistentEntity<?, VaultPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) { super(property, owner, simpleTypeHolder); @@ -57,4 +54,5 @@ public class VaultPersistentProperty public boolean isIdProperty() { return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getName()); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultSimpleTypes.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultSimpleTypes.java index 3e902d70..c39b24d0 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultSimpleTypes.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/mapping/VaultSimpleTypes.java @@ -40,9 +40,10 @@ public abstract class VaultSimpleTypes { } private static final Set<Class<?>> VAULT_SIMPLE_TYPES; - public static final SimpleTypeHolder HOLDER = new SimpleTypeHolder(VAULT_SIMPLE_TYPES, - true); + + public static final SimpleTypeHolder HOLDER = new SimpleTypeHolder(VAULT_SIMPLE_TYPES, true); private VaultSimpleTypes() { } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultPartTreeQuery.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultPartTreeQuery.java index 4600edc7..6e54eaf7 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultPartTreeQuery.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultPartTreeQuery.java @@ -39,25 +39,20 @@ public class VaultPartTreeQuery extends KeyValuePartTreeQuery { * Creates a new {@link VaultPartTreeQuery} for the given {@link QueryMethod}, * {@link EvaluationContextProvider}, {@link KeyValueOperations} and query creator * type. - * * @param queryMethod must not be {@literal null}. * @param evaluationContextProvider must not be {@literal null}. * @param keyValueOperations must not be {@literal null}. * @param queryCreator must not be {@literal null}. */ @SuppressWarnings("unchecked") - public VaultPartTreeQuery(QueryMethod queryMethod, - QueryMethodEvaluationContextProvider evaluationContextProvider, - KeyValueOperations keyValueOperations, - Class<? extends AbstractQueryCreator<?, ?>> queryCreator) { + public VaultPartTreeQuery(QueryMethod queryMethod, QueryMethodEvaluationContextProvider evaluationContextProvider, + KeyValueOperations keyValueOperations, Class<? extends AbstractQueryCreator<?, ?>> queryCreator) { super(queryMethod, evaluationContextProvider, keyValueOperations, - new VaultQueryCreatorFactory( - (MappingContext) keyValueOperations.getMappingContext())); + new VaultQueryCreatorFactory((MappingContext) keyValueOperations.getMappingContext())); } - static class VaultQueryCreatorFactory - implements QueryCreatorFactory<VaultQueryCreator> { + static class VaultQueryCreatorFactory implements QueryCreatorFactory<VaultQueryCreator> { private final MappingContext<VaultPersistentEntity<?>, VaultPersistentProperty> mappingContext; @@ -67,9 +62,10 @@ public class VaultPartTreeQuery extends KeyValuePartTreeQuery { } @Override - public VaultQueryCreator queryCreatorFor(PartTree partTree, - ParameterAccessor accessor) { - return new VaultQueryCreator(partTree, accessor, mappingContext); + public VaultQueryCreator queryCreatorFor(PartTree partTree, ParameterAccessor accessor) { + return new VaultQueryCreator(partTree, accessor, this.mappingContext); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQuery.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQuery.java index 2b693138..e498bb08 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQuery.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQuery.java @@ -44,7 +44,6 @@ public class VaultQuery { /** * Create a new {@link VaultQuery} given {@link Predicate}. - * * @param predicate must not be {@literal null}. */ public VaultQuery(Predicate<String> predicate) { @@ -56,20 +55,18 @@ public class VaultQuery { /** * Evaluate the query against a {@link SecretDocument}. - * * @param document must not be {@literal null}. * @return {@literal true} if the predicate matches, {@literal false} otherwise. */ public boolean test(SecretDocument document) { - Assert.notNull(predicate, "Predicate must not be null"); + Assert.notNull(this.predicate, "Predicate must not be null"); - return predicate.test(document.getId()); + return this.predicate.test(document.getId()); } /** * Evaluate the query against a {@link String}. - * * @param id must not be {@literal null}. * @return {@literal true} if the predicate matches, {@literal false} otherwise. */ @@ -77,13 +74,12 @@ public class VaultQuery { Assert.notNull(id, "Id to test must not be null"); - return predicate.test(id); + return this.predicate.test(id); } /** * Compose a new {@link VaultQuery} using predicates of {@literal this} and the * {@code other} query using logical {@code AND}. - * * @param other must not be {@literal null}. * @return a new composed {@link VaultQuery}. * @see Predicate#and(Predicate) @@ -95,7 +91,6 @@ public class VaultQuery { /** * Compose a new {@link VaultQuery} using predicates of {@literal this} and the * {@code other} query using logical {@code AND}. - * * @param predicate must not be {@literal null}. * @return a new composed {@link VaultQuery}. * @see Predicate#and(Predicate) @@ -107,7 +102,6 @@ public class VaultQuery { /** * Compose a new {@link VaultQuery} using predicates of {@literal this} and the * {@code other} query using logical {@code OR}. - * * @param other must not be {@literal null}. * @return a new composed {@link VaultQuery}. * @see Predicate#and(Predicate) @@ -120,6 +114,7 @@ public class VaultQuery { * @return the underlying predicate. */ public Predicate<String> getPredicate() { - return predicate; + return this.predicate; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQueryCreator.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQueryCreator.java index c1131c90..153954f4 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQueryCreator.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/query/VaultQueryCreator.java @@ -44,15 +44,13 @@ import org.springframework.vault.repository.mapping.VaultPersistentProperty; * @author Mark Paluch * @since 2.0 */ -public class VaultQueryCreator - extends AbstractQueryCreator<KeyValueQuery<VaultQuery>, VaultQuery> { +public class VaultQueryCreator extends AbstractQueryCreator<KeyValueQuery<VaultQuery>, VaultQuery> { private final MappingContext<VaultPersistentEntity<?>, VaultPersistentProperty> mappingContext; /** * Create a new {@link VaultQueryCreator} given {@link PartTree} and * {@link ParameterAccessor}. - * * @param tree must not be {@literal null}. * @param parameters must not be {@literal null}. * @param mappingContext must not be {@literal null}. @@ -76,14 +74,12 @@ public class VaultQueryCreator private Predicate<String> createPredicate(Part part, Iterator<Object> parameters) { - PersistentPropertyPath<VaultPersistentProperty> propertyPath = mappingContext + PersistentPropertyPath<VaultPersistentProperty> propertyPath = this.mappingContext .getPersistentPropertyPath(part.getProperty()); - if (propertyPath.getLeafProperty() != null - && !propertyPath.getLeafProperty().isIdProperty()) { + if (propertyPath.getLeafProperty() != null && !propertyPath.getLeafProperty().isIdProperty()) { throw new InvalidDataAccessApiUsageException( - String.format("Cannot create criteria for non-@Id property %s", - propertyPath.getLeafProperty())); + String.format("Cannot create criteria for non-@Id property %s", propertyPath.getLeafProperty())); } VariableAccessor accessor = getVariableAccessor(part); @@ -95,31 +91,25 @@ public class VaultQueryCreator /** * Return a {@link Predicate} depending on the {@link Part} given. - * * @param part * @param parameters * @return */ - private static Predicate<String> from(Part part, VariableAccessor accessor, - Iterator<Object> parameters) { + private static Predicate<String> from(Part part, VariableAccessor accessor, Iterator<Object> parameters) { Type type = part.getType(); switch (type) { case AFTER: case GREATER_THAN: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.compareTo(value) > 0); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) > 0); case GREATER_THAN_EQUAL: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.compareTo(value) >= 0); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) >= 0); case BEFORE: case LESS_THAN: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.compareTo(value) < 0); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) < 0); case LESS_THAN_EQUAL: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.compareTo(value) <= 0); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) <= 0); case BETWEEN: String from = accessor.nextString(parameters); @@ -127,38 +117,28 @@ public class VaultQueryCreator return it -> it.compareTo(from) >= 0 && it.compareTo(to) <= 0; case NOT_IN: - return new Criteria<>(accessor.nextAsArray(parameters), - (value, it) -> Arrays.binarySearch(value, it) < 0); + return new Criteria<>(accessor.nextAsArray(parameters), (value, it) -> Arrays.binarySearch(value, it) < 0); case IN: - return new Criteria<>(accessor.nextAsArray(parameters), - (value, it) -> Arrays.binarySearch(value, it) >= 0); + return new Criteria<>(accessor.nextAsArray(parameters), (value, it) -> Arrays.binarySearch(value, it) >= 0); case STARTING_WITH: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.startsWith(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.startsWith(value)); case ENDING_WITH: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.endsWith(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.endsWith(value)); case CONTAINING: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.contains(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.contains(value)); case NOT_CONTAINING: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> !it.contains(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.contains(value)); case REGEX: - return Pattern - .compile((String) parameters.next(), - isIgnoreCase(part) ? Pattern.CASE_INSENSITIVE : 0) + return Pattern.compile((String) parameters.next(), isIgnoreCase(part) ? Pattern.CASE_INSENSITIVE : 0) .asPredicate(); case TRUE: return it -> it.equalsIgnoreCase("true"); case FALSE: return it -> it.equalsIgnoreCase("false"); case SIMPLE_PROPERTY: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> it.equals(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.equals(value)); case NEGATING_SIMPLE_PROPERTY: - return new Criteria<>(accessor.nextString(parameters), - (value, it) -> !it.equals(value)); + return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.equals(value)); default: throw new IllegalArgumentException("Unsupported keyword!"); } @@ -192,6 +172,7 @@ public class VaultQueryCreator static final class Criteria<T> implements Predicate<String> { private final T value; + private final BiPredicate<T, String> predicate; public Criteria(T value, BiPredicate<T, String> predicate) { @@ -201,7 +182,7 @@ public class VaultQueryCreator @Override public boolean test(String s) { - return predicate.test(value, s); + return this.predicate.test(this.value, s); } public T getValue() { @@ -220,13 +201,11 @@ public class VaultQueryCreator final Criteria<?> other = (Criteria<?>) o; final Object this$value = this.getValue(); final Object other$value = other.getValue(); - if (this$value == null ? other$value != null - : !this$value.equals(other$value)) + if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false; final Object this$predicate = this.getPredicate(); final Object other$predicate = other.getPredicate(); - if (this$predicate == null ? other$predicate != null - : !this$predicate.equals(other$predicate)) + if (this$predicate == null ? other$predicate != null : !this$predicate.equals(other$predicate)) return false; return true; } @@ -245,11 +224,12 @@ public class VaultQueryCreator public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [value=").append(value); - sb.append(", predicate=").append(predicate); + sb.append(" [value=").append(this.value); + sb.append(", predicate=").append(this.predicate); sb.append(']'); return sb.toString(); } + } enum VariableAccessor { @@ -313,5 +293,7 @@ public class VaultQueryCreator abstract String nextString(Iterator<Object> iterator); abstract String toString(String value); + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactory.java index 700840c1..c4a7c722 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactory.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactory.java @@ -58,9 +58,10 @@ public class VaultRepositoryFactory extends KeyValueRepositoryFactory { @SuppressWarnings("unchecked") public <T, ID> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) { - VaultPersistentEntity<T> entity = (VaultPersistentEntity<T>) operations - .getMappingContext().getPersistentEntity(domainClass); + VaultPersistentEntity<T> entity = (VaultPersistentEntity<T>) this.operations.getMappingContext() + .getPersistentEntity(domainClass); return new MappingVaultEntityInformation<>(entity); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactoryBean.java b/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactoryBean.java index 0d3b5775..2ab877fe 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactoryBean.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/repository/support/VaultRepositoryFactoryBean.java @@ -39,7 +39,6 @@ public class VaultRepositoryFactoryBean<T extends Repository<S, ID>, S, ID exten /** * Creates a new {@link VaultRepositoryFactoryBean} for the given repository * interface. - * * @param repositoryInterface must not be {@literal null}. */ public VaultRepositoryFactoryBean(Class<? extends T> repositoryInterface) { @@ -47,11 +46,11 @@ public class VaultRepositoryFactoryBean<T extends Repository<S, ID>, S, ID exten } @Override - protected VaultRepositoryFactory createRepositoryFactory( - KeyValueOperations operations, + protected VaultRepositoryFactory createRepositoryFactory(KeyValueOperations operations, Class<? extends AbstractQueryCreator<?, ?>> queryCreator, Class<? extends RepositoryQuery> repositoryQueryType) { return new VaultRepositoryFactory(operations, queryCreator, repositoryQueryType); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesEncryptor.java b/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesEncryptor.java index 433ec76c..f3b56a6c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesEncryptor.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesEncryptor.java @@ -40,7 +40,6 @@ public class VaultBytesEncryptor implements BytesEncryptor { /** * Create a new {@link VaultBytesEncryptor} given {@link VaultTransitOperations} and * {@code keyName}. - * * @param transitOperations must not be {@literal null}. * @param keyName must not be {@literal null} or empty. */ @@ -59,8 +58,7 @@ public class VaultBytesEncryptor implements BytesEncryptor { Assert.notNull(plaintext, "Plaintext must not be null"); Assert.isTrue(!ObjectUtils.isEmpty(plaintext), "Plaintext must not be empty"); - Ciphertext ciphertext = transitOperations.encrypt(keyName, - Plaintext.of(plaintext)); + Ciphertext ciphertext = this.transitOperations.encrypt(this.keyName, Plaintext.of(plaintext)); return Utf8.encode(ciphertext.getCiphertext()); } @@ -71,9 +69,9 @@ public class VaultBytesEncryptor implements BytesEncryptor { Assert.notNull(ciphertext, "Ciphertext must not be null"); Assert.isTrue(!ObjectUtils.isEmpty(ciphertext), "Ciphertext must not be empty"); - Plaintext plaintext = transitOperations.decrypt(keyName, - Ciphertext.of(Utf8.decode(ciphertext))); + Plaintext plaintext = this.transitOperations.decrypt(this.keyName, Ciphertext.of(Utf8.decode(ciphertext))); return plaintext.getPlaintext(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesKeyGenerator.java b/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesKeyGenerator.java index 1c096c4e..18da8fc5 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesKeyGenerator.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/security/VaultBytesKeyGenerator.java @@ -44,7 +44,6 @@ public class VaultBytesKeyGenerator implements BytesKeyGenerator { /** * Creates a new {@link VaultBytesKeyGenerator} initialized to generate {@code 32} * random bytes using {@code transit} for transit mount path. - * * @param vaultOperations must not be {@literal null}. */ public VaultBytesKeyGenerator(VaultOperations vaultOperations) { @@ -54,14 +53,12 @@ public class VaultBytesKeyGenerator implements BytesKeyGenerator { /** * Creates a new {@link VaultBytesKeyGenerator} initialized to generate {@code length} * random bytes. - * * @param vaultOperations must not be {@literal null}. * @param transitPath path of the transit backend, must not be {@literal null} or - * empty. + * empty. * @param length number of random bytes to generate. Must be greater than zero. */ - public VaultBytesKeyGenerator(VaultOperations vaultOperations, String transitPath, - int length) { + public VaultBytesKeyGenerator(VaultOperations vaultOperations, String transitPath, int length) { Assert.notNull(vaultOperations, "VaultOperations must not be null"); Assert.hasText(transitPath, "Transit path must not be null or empty"); @@ -74,17 +71,18 @@ public class VaultBytesKeyGenerator implements BytesKeyGenerator { @Override public int getKeyLength() { - return length; + return this.length; } @Override public byte[] generateKey() { - VaultResponse response = vaultOperations.write( - String.format("%s/random/%d", transitPath, getKeyLength()), + VaultResponse response = this.vaultOperations.write( + String.format("%s/random/%d", this.transitPath, getKeyLength()), Collections.singletonMap("format", "base64")); String randomBytes = (String) response.getRequiredData().get("random_bytes"); return Base64Utils.decodeFromString(randomBytes); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/AbstractResult.java b/spring-vault-core/src/main/java/org/springframework/vault/support/AbstractResult.java index 97b4675b..2ec19ad8 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/AbstractResult.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/AbstractResult.java @@ -35,12 +35,11 @@ public abstract class AbstractResult<V> { * Create a {@link AbstractResult} completed without an {@link VaultException}. */ protected AbstractResult() { - exception = null; + this.exception = null; } /** * Create a {@link AbstractResult} completed with an {@link VaultException}. - * * @param exception must not be {@literal null}. */ protected AbstractResult(VaultException exception) { @@ -54,28 +53,25 @@ public abstract class AbstractResult<V> { * Returns {@literal true} if and only if the batch operation was completed * successfully. Use {@link #getCause()} to obtain the actual exception if the * operation completed with an error. - * * @return {@literal true} if the batch operation was completed successfully. */ public boolean isSuccessful() { - return exception == null; + return this.exception == null; } /** * Returns the cause of the failed operation if the operation completed with an error. - * * @return the cause of the failure or {@literal null} if succeeded. */ @Nullable public Exception getCause() { - return exception; + return this.exception; } /** * Return the result or throw a {@link VaultException} if the operation completed with * an error. Use {@link #isSuccessful()} to verify the success status of this result * without throwing an exception. - * * @return the result value. * @throws VaultException if the operation completed with an error. */ @@ -86,7 +82,7 @@ public abstract class AbstractResult<V> { return get0(); } - throw new VaultException(exception.getMessage()); + throw new VaultException(this.exception.getMessage()); } /** @@ -94,4 +90,5 @@ public abstract class AbstractResult<V> { */ @Nullable protected abstract V get0(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Certificate.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Certificate.java index 24e974cc..52f273d5 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Certificate.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Certificate.java @@ -45,8 +45,7 @@ public class Certificate { private final String issuingCaCertificate; - Certificate(@JsonProperty("serial_number") String serialNumber, - @JsonProperty("certificate") String certificate, + Certificate(@JsonProperty("serial_number") String serialNumber, @JsonProperty("certificate") String certificate, @JsonProperty("issuing_ca") String issuingCaCertificate) { this.serialNumber = serialNumber; @@ -57,14 +56,12 @@ public class Certificate { /** * Create a {@link Certificate} given a private key with certificates and the serial * number. - * * @param serialNumber must not be empty or {@literal null}. * @param certificate must not be empty or {@literal null}. * @param issuingCaCertificate must not be empty or {@literal null}. * @return the {@link Certificate} */ - public static Certificate of(String serialNumber, String certificate, - String issuingCaCertificate) { + public static Certificate of(String serialNumber, String certificate, String issuingCaCertificate) { Assert.hasText(serialNumber, "Serial number must not be empty"); Assert.hasText(certificate, "Certificate must not be empty"); @@ -97,7 +94,6 @@ public class Certificate { /** * Retrieve the certificate as {@link X509Certificate}. Only supported if certificate * is DER-encoded. - * * @return the {@link X509Certificate}. */ public X509Certificate getX509Certificate() { @@ -114,7 +110,6 @@ public class Certificate { /** * Retrieve the issuing CA certificate as {@link X509Certificate}. Only supported if * certificate is DER-encoded. - * * @return the issuing CA {@link X509Certificate}. */ public X509Certificate getX509IssuerCertificate() { @@ -124,25 +119,23 @@ public class Certificate { return KeystoreUtil.getCertificate(bytes); } catch (CertificateException e) { - throw new VaultException( - "Cannot create Certificate from issuing CA certificate", e); + throw new VaultException("Cannot create Certificate from issuing CA certificate", e); } } /** * Create a trust store as {@link KeyStore} from this {@link Certificate} containing * the certificate chain. Only supported if certificate is DER-encoded. - * * @return the {@link KeyStore} containing the private key and certificate chain. */ public KeyStore createTrustStore() { try { - return KeystoreUtil.createKeyStore(getX509Certificate(), - getX509IssuerCertificate()); + return KeystoreUtil.createKeyStore(getX509Certificate(), getX509IssuerCertificate()); } catch (GeneralSecurityException | IOException e) { throw new VaultException("Cannot create KeyStore", e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/CertificateBundle.java b/spring-vault-core/src/main/java/org/springframework/vault/support/CertificateBundle.java index 254d18c8..3ec52266 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/CertificateBundle.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/CertificateBundle.java @@ -43,8 +43,7 @@ public class CertificateBundle extends Certificate { private final String privateKey; CertificateBundle(@JsonProperty("serial_number") String serialNumber, - @JsonProperty("certificate") String certificate, - @JsonProperty("issuing_ca") String issuingCaCertificate, + @JsonProperty("certificate") String certificate, @JsonProperty("issuing_ca") String issuingCaCertificate, @JsonProperty("private_key") String privateKey) { super(serialNumber, certificate, issuingCaCertificate); @@ -54,23 +53,21 @@ public class CertificateBundle extends Certificate { /** * Create a {@link CertificateBundle} given a private key with certificates and the * serial number. - * * @param serialNumber must not be empty or {@literal null}. * @param certificate must not be empty or {@literal null}. * @param issuingCaCertificate must not be empty or {@literal null}. * @param privateKey must not be empty or {@literal null}. * @return the {@link CertificateBundle} */ - public static CertificateBundle of(String serialNumber, String certificate, - String issuingCaCertificate, String privateKey) { + public static CertificateBundle of(String serialNumber, String certificate, String issuingCaCertificate, + String privateKey) { Assert.hasText(serialNumber, "Serial number must not be empty"); Assert.hasText(certificate, "Certificate must not be empty"); Assert.hasText(issuingCaCertificate, "Issuing CA certificate must not be empty"); Assert.hasText(privateKey, "Private key must not be empty"); - return new CertificateBundle(serialNumber, certificate, issuingCaCertificate, - privateKey); + return new CertificateBundle(serialNumber, certificate, issuingCaCertificate, privateKey); } /** @@ -83,7 +80,6 @@ public class CertificateBundle extends Certificate { /** * Retrieve the private key as {@link KeySpec}. Only supported if private key is * DER-encoded. - * * @return the private {@link KeySpec}. {@link java.security.KeyFactory} can generate * a {@link java.security.PrivateKey} from this {@link KeySpec}. */ @@ -102,7 +98,6 @@ public class CertificateBundle extends Certificate { * Create a {@link KeyStore} from this {@link CertificateBundle} containing the * private key and certificate chain. Only supported if certificate and private key * are DER-encoded. - * * @param keyAlias the key alias to use. * @return the {@link KeyStore} containing the private key and certificate chain. */ @@ -111,11 +106,12 @@ public class CertificateBundle extends Certificate { Assert.hasText(keyAlias, "Key alias must not be empty"); try { - return KeystoreUtil.createKeyStore(keyAlias, getPrivateKeySpec(), - getX509Certificate(), getX509IssuerCertificate()); + return KeystoreUtil.createKeyStore(keyAlias, getPrivateKeySpec(), getX509Certificate(), + getX509IssuerCertificate()); } catch (GeneralSecurityException | IOException e) { throw new VaultException("Cannot create KeyStore", e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Ciphertext.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Ciphertext.java index 68cb3be1..1e81fb23 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Ciphertext.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Ciphertext.java @@ -40,7 +40,6 @@ public class Ciphertext { /** * Factory method to create {@link Ciphertext} from the given {@code ciphertext}. - * * @param ciphertext the ciphertext to decrypt, must not be {@literal null} or empty. * @return the {@link Ciphertext} for {@code ciphertext}. */ @@ -52,17 +51,16 @@ public class Ciphertext { } public String getCiphertext() { - return ciphertext; + return this.ciphertext; } public VaultTransitContext getContext() { - return context; + return this.context; } /** * Create a new {@link Ciphertext} object from this ciphertext associated with the * given {@link VaultTransitContext}. - * * @param context transit context, must not be {@literal null}. * @return the new {@link Ciphertext} object. */ @@ -80,11 +78,12 @@ public class Ciphertext { if (!(o instanceof Ciphertext)) return false; Ciphertext that = (Ciphertext) o; - return ciphertext.equals(that.ciphertext) && context.equals(that.context); + return this.ciphertext.equals(that.ciphertext) && this.context.equals(that.context); } @Override public int hashCode() { - return Objects.hash(ciphertext, context); + return Objects.hash(this.ciphertext, this.context); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/ClientOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/support/ClientOptions.java index b31d20bb..e4fe89c3 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/ClientOptions.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/ClientOptions.java @@ -48,11 +48,10 @@ public class ClientOptions { /** * Create new {@link ClientOptions}. - * * @param connectionTimeout connection timeout in {@link TimeUnit#MILLISECONDS}, must - * not be negative. + * not be negative. * @param readTimeout read timeout in {@link TimeUnit#MILLISECONDS}, must not be - * negative. + * negative. * @deprecated since 2.0, use {@link #ClientOptions(Duration, Duration)} for time unit * safety. */ @@ -63,7 +62,6 @@ public class ClientOptions { /** * Create new {@link ClientOptions}. - * * @param connectionTimeout connection timeout, must not be {@literal null}. * @param readTimeout read timeout in, must not be {@literal null}. * @since 2.0 @@ -81,13 +79,14 @@ public class ClientOptions { * @return the connection timeout in {@link TimeUnit#MILLISECONDS}. */ public Duration getConnectionTimeout() { - return connectionTimeout; + return this.connectionTimeout; } /** * @return the read timeout in {@link TimeUnit#MILLISECONDS}. */ public Duration getReadTimeout() { - return readTimeout; + return this.readTimeout; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Hmac.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Hmac.java index 2e1fbd0c..d12ed928 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Hmac.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Hmac.java @@ -36,7 +36,6 @@ public class Hmac { /** * Factory method to create a {@link Hmac} from the given {@code hmac}. - * * @param hmac the Hmac digest, must not be {@literal null} or empty. * @return the {@link Hmac} encapsulating {@code hmac}. */ @@ -48,7 +47,7 @@ public class Hmac { } public String getHmac() { - return hmac; + return this.hmac; } @Override @@ -58,20 +57,21 @@ public class Hmac { if (!(o instanceof Hmac)) return false; Hmac other = (Hmac) o; - return hmac.equals(other.hmac); + return this.hmac.equals(other.hmac); } @Override public int hashCode() { - return Objects.hash(hmac); + return Objects.hash(this.hmac); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [hmac='").append(hmac).append('\''); + sb.append(" [hmac='").append(this.hmac).append('\''); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/JsonMapFlattener.java b/spring-vault-core/src/main/java/org/springframework/vault/support/JsonMapFlattener.java index b1d99a2e..1705c7b1 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/JsonMapFlattener.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/JsonMapFlattener.java @@ -62,7 +62,6 @@ public abstract class JsonMapFlattener { /** * Flatten a hierarchical {@link Map} into a flat {@link Map} with key names using * property dot notation. - * * @param inputMap must not be {@literal null}. * @return the resulting {@link Map}. */ @@ -72,8 +71,7 @@ public abstract class JsonMapFlattener { Map<String, Object> resultMap = new LinkedHashMap<>(); - doFlatten("", inputMap.entrySet().iterator(), resultMap, - UnaryOperator.identity()); + doFlatten("", inputMap.entrySet().iterator(), resultMap, UnaryOperator.identity()); return resultMap; } @@ -81,28 +79,23 @@ public abstract class JsonMapFlattener { /** * Flatten a hierarchical {@link Map} into a flat {@link Map} with key names using * property dot notation. - * * @param inputMap must not be {@literal null}. * @return the resulting {@link Map}. * @since 2.0 */ - public static Map<String, String> flattenToStringMap( - Map<String, ? extends Object> inputMap) { + public static Map<String, String> flattenToStringMap(Map<String, ? extends Object> inputMap) { Assert.notNull(inputMap, "Input Map must not be null"); Map<String, String> resultMap = new LinkedHashMap<>(); - doFlatten("", inputMap.entrySet().iterator(), resultMap, - it -> it == null ? null : it.toString()); + doFlatten("", inputMap.entrySet().iterator(), resultMap, it -> it == null ? null : it.toString()); return resultMap; } - private static void doFlatten(String propertyPrefix, - Iterator<? extends Entry<String, ?>> inputMap, - Map<String, ? extends Object> resultMap, - Function<Object, Object> valueTransformer) { + private static void doFlatten(String propertyPrefix, Iterator<? extends Entry<String, ?>> inputMap, + Map<String, ? extends Object> resultMap, Function<Object, Object> valueTransformer) { if (StringUtils.hasText(propertyPrefix)) { propertyPrefix = propertyPrefix + "."; @@ -111,40 +104,36 @@ public abstract class JsonMapFlattener { while (inputMap.hasNext()) { Entry<String, ? extends Object> entry = inputMap.next(); - flattenElement(propertyPrefix.concat(entry.getKey()), entry.getValue(), - resultMap, valueTransformer); + flattenElement(propertyPrefix.concat(entry.getKey()), entry.getValue(), resultMap, valueTransformer); } } @SuppressWarnings("unchecked") - private static void flattenElement(String propertyPrefix, @Nullable Object source, - Map<String, ?> resultMap, Function<Object, Object> valueTransformer) { + private static void flattenElement(String propertyPrefix, @Nullable Object source, Map<String, ?> resultMap, + Function<Object, Object> valueTransformer) { if (source instanceof Iterable) { - flattenCollection(propertyPrefix, (Iterable<Object>) source, resultMap, - valueTransformer); + flattenCollection(propertyPrefix, (Iterable<Object>) source, resultMap, valueTransformer); return; } if (source instanceof Map) { - doFlatten(propertyPrefix, ((Map<String, ?>) source).entrySet().iterator(), - resultMap, valueTransformer); + doFlatten(propertyPrefix, ((Map<String, ?>) source).entrySet().iterator(), resultMap, valueTransformer); return; } ((Map) resultMap).put(propertyPrefix, valueTransformer.apply(source)); } - private static void flattenCollection(String propertyPrefix, - Iterable<Object> iterable, Map<String, ?> resultMap, + private static void flattenCollection(String propertyPrefix, Iterable<Object> iterable, Map<String, ?> resultMap, Function<Object, Object> valueTransformer) { int counter = 0; for (Object element : iterable) { - flattenElement(propertyPrefix + "[" + counter + "]", element, resultMap, - valueTransformer); + flattenElement(propertyPrefix + "[" + counter + "]", element, resultMap, valueTransformer); counter++; } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/KeystoreUtil.java b/spring-vault-core/src/main/java/org/springframework/vault/support/KeystoreUtil.java index b9b7451c..496e6262 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/KeystoreUtil.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/KeystoreUtil.java @@ -65,15 +65,13 @@ class KeystoreUtil { /** * Create a {@link KeyStore} containing the {@link KeySpec} and {@link X509Certificate * certificates} using the given {@code keyAlias}. - * * @param keyAlias * @param certificates * @return * @throws GeneralSecurityException * @throws IOException */ - static KeyStore createKeyStore(String keyAlias, KeySpec privateKeySpec, - X509Certificate... certificates) + static KeyStore createKeyStore(String keyAlias, KeySpec privateKeySpec, X509Certificate... certificates) throws GeneralSecurityException, IOException { PrivateKey privateKey = KEY_FACTORY.generatePrivate(privateKeySpec); @@ -92,45 +90,39 @@ class KeystoreUtil { /** * Create a {@link KeyStore} containing the {@link X509Certificate certificates} * stored with as {@code cert_0, cert_1...cert_N}. - * * @param certificates * @return * @throws GeneralSecurityException * @throws IOException * @since 2.0 */ - static KeyStore createKeyStore(X509Certificate... certificates) - throws GeneralSecurityException, IOException { + static KeyStore createKeyStore(X509Certificate... certificates) throws GeneralSecurityException, IOException { KeyStore keyStore = createKeyStore(); int counter = 0; for (X509Certificate certificate : certificates) { - keyStore.setCertificateEntry(String.format("cert_%d", counter++), - certificate); + keyStore.setCertificateEntry(String.format("cert_%d", counter++), certificate); } return keyStore; } - static X509Certificate getCertificate(byte[] source) - throws CertificateException { + static X509Certificate getCertificate(byte[] source) throws CertificateException { List<X509Certificate> certificates = getCertificates(CERTIFICATE_FACTORY, source); - return certificates.stream().findFirst().orElseThrow( - () -> new IllegalArgumentException("No X509Certificate found")); + return certificates.stream().findFirst() + .orElseThrow(() -> new IllegalArgumentException("No X509Certificate found")); } /** * Create an empty {@link KeyStore}. - * * @return the {@link KeyStore}. * @throws GeneralSecurityException * @throws IOException */ - private static KeyStore createKeyStore() - throws GeneralSecurityException, IOException { + private static KeyStore createKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, new char[0]); @@ -138,8 +130,8 @@ class KeystoreUtil { return keyStore; } - private static List<X509Certificate> getCertificates(CertificateFactory cf, - byte[] source) throws CertificateException { + private static List<X509Certificate> getCertificates(CertificateFactory cf, byte[] source) + throws CertificateException { List<X509Certificate> x509Certificates = new ArrayList<>(); @@ -179,7 +171,6 @@ class KeystoreUtil { * otherPrimeInfos OtherPrimeInfos OPTIONAL * } * </pre> - * * @param keyBytes PKCS#1 encoded key * @return KeySpec */ @@ -204,8 +195,7 @@ class KeystoreUtil { BigInteger exp2 = parser.read().getInteger(); BigInteger crtCoef = parser.read().getInteger(); - return new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, - exp1, exp2, crtCoef); + return new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); } /** @@ -264,7 +254,6 @@ class KeystoreUtil { /** * Create a new DER decoder from an input stream. - * * @param in The DER encoded stream */ DerParser(InputStream in) { @@ -273,7 +262,6 @@ class KeystoreUtil { /** * Create a new DER decoder from a byte array. - * * @param bytes The encoded bytes */ DerParser(byte[] bytes) { @@ -283,25 +271,22 @@ class KeystoreUtil { /** * Read next object. If it's constructed, the value holds encoded content and it * should be parsed by a new parser from <code>Asn1Object.getParser</code>. - * * @return A object */ public Asn1Object read() throws IOException { - int tag = in.read(); + int tag = this.in.read(); if (tag == -1) { - throw new IllegalStateException( - "Invalid DER: stream too short, missing tag"); + throw new IllegalStateException("Invalid DER: stream too short, missing tag"); } int length = getLength(); byte[] value = new byte[length]; - int n = in.read(value); + int n = this.in.read(value); if (n < length) { - throw new IllegalStateException( - "Invalid DER: stream too short, missing value"); + throw new IllegalStateException("Invalid DER: stream too short, missing value"); } return new Asn1Object(tag, length, value); @@ -320,12 +305,11 @@ class KeystoreUtil { * Second and following octets give the length, base 256, most significant digit * first. * </ul> - * * @return The length as integer */ private int getLength() throws IOException { - int i = in.read(); + int i = this.in.read(); if (i == -1) { throw new IllegalStateException("Invalid DER: length missing"); } @@ -339,18 +323,18 @@ class KeystoreUtil { // We can't handle length longer than 4 bytes if (i >= 0xFF || num > 4) { - throw new IllegalStateException( - "Invalid DER: length field too big (" + i + ")"); + throw new IllegalStateException("Invalid DER: length field too big (" + i + ")"); } byte[] bytes = new byte[num]; - int n = in.read(bytes); + int n = this.in.read(bytes); if (n < num) { throw new IllegalStateException("Invalid DER: length too short"); } return new BigInteger(1, bytes).intValue(); } + } /** @@ -359,8 +343,11 @@ class KeystoreUtil { static class Asn1Object { private final int type; + private final int length; + private final byte[] value; + private final int tag; /** @@ -384,7 +371,6 @@ class KeystoreUtil { * <li>Type: This is actually called tag in ASN.1. It indicates data type * (Integer, String) or a construct (sequence, choice, set). * </ul> - * * @param tag Tag or Identifier * @param length Length of the field * @param value Encoded octet string for the field. @@ -397,60 +383,56 @@ class KeystoreUtil { } int getType() { - return type; + return this.type; } int getLength() { - return length; + return this.length; } byte[] getValue() { - return value; + return this.value; } boolean isConstructed() { - return (tag & DerParser.CONSTRUCTED) == DerParser.CONSTRUCTED; + return (this.tag & DerParser.CONSTRUCTED) == DerParser.CONSTRUCTED; } /** * For constructed field, return a parser for its content. - * * @return A parser for the construct. */ DerParser getParser() throws IOException { if (!isConstructed()) { - throw new IllegalStateException( - "Invalid DER: can't parse primitive entity"); + throw new IllegalStateException("Invalid DER: can't parse primitive entity"); } - return new DerParser(value); + return new DerParser(this.value); } /** * Get the value as integer - * * @return BigInteger */ BigInteger getInteger() { - if (type != DerParser.INTEGER) { + if (this.type != DerParser.INTEGER) { throw new IllegalStateException("Invalid DER: object is not integer"); } - return new BigInteger(value); + return new BigInteger(this.value); } /** * Get value as string. Most strings are treated as ISO-8859-1. - * * @return Java string */ String getString() throws IOException { String encoding; - switch (type) { + switch (this.type) { // Not all are ISO-8859-1 but it's the closest thing case DerParser.NUMERIC_STRING: @@ -478,7 +460,9 @@ class KeystoreUtil { throw new IOException("Invalid DER: object is not a string"); } - return new String(value, encoding); + return new String(this.value, encoding); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/LeaseStrategy.java b/spring-vault-core/src/main/java/org/springframework/vault/support/LeaseStrategy.java index a154d1d8..ba4420f4 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/LeaseStrategy.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/LeaseStrategy.java @@ -28,7 +28,6 @@ public interface LeaseStrategy { /** * Return {@literal true} to drop the lease after {@link Throwable error} happened. * {@literal false} to retain the lease. - * * @param error the error that occurred. * @return {@literal true} to drop the lease after {@link Throwable error} happened. * {@literal false} to retain the lease. @@ -37,7 +36,6 @@ public interface LeaseStrategy { /** * Predefined strategy to drop leases on error. - * * @return the drop on error strategy. */ static LeaseStrategy dropOnError() { @@ -46,10 +44,10 @@ public interface LeaseStrategy { /** * Predefined strategy to retain leases on error. - * * @return the retain on error strategy. */ static LeaseStrategy retainOnError() { return error -> false; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/PemObject.java b/spring-vault-core/src/main/java/org/springframework/vault/support/PemObject.java index e23910ea..974fcc26 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/PemObject.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/PemObject.java @@ -33,11 +33,10 @@ import org.springframework.util.Base64Utils; */ public class PemObject { - private static final Pattern KEY_PATTERN = Pattern - .compile("-+BEGIN\\s+.*PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + // Header - "([a-z0-9+/=\\r\\n]+)" + // Base64 text - "-+END\\s+.*PRIVATE\\s+KEY[^-]*-+", // Footer - Pattern.CASE_INSENSITIVE); + private static final Pattern KEY_PATTERN = Pattern.compile("-+BEGIN\\s+.*PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + // Header + "([a-z0-9+/=\\r\\n]+)" + // Base64 text + "-+END\\s+.*PRIVATE\\s+KEY[^-]*-+", // Footer + Pattern.CASE_INSENSITIVE); private final byte[] content; @@ -50,7 +49,6 @@ public class PemObject { /** * Create a{@link PemObject} from PEM {@code content} that is enclosed with * {@code -BEGIN PRIVATE KEY-} and {@code -END PRIVATE KEY-}. - * * @param content the PEM content. * @return the {@link PemObject} from PEM {@code content}. */ @@ -66,7 +64,6 @@ public class PemObject { /** * Retrieve a {@link RSAPrivateCrtKeySpec}. - * * @return the {@link RSAPrivateCrtKeySpec}. */ public RSAPrivateCrtKeySpec getRSAKeySpec() { @@ -78,4 +75,5 @@ public class PemObject { throw new IllegalArgumentException("Cannot obtain PrivateKey", e); } } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Plaintext.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Plaintext.java index a39685df..bc7616ea 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Plaintext.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Plaintext.java @@ -30,8 +30,7 @@ import org.springframework.util.Assert; */ public class Plaintext { - private static final Plaintext EMPTY = new Plaintext(new byte[0], - VaultTransitContext.empty()); + private static final Plaintext EMPTY = new Plaintext(new byte[0], VaultTransitContext.empty()); private final byte[] plaintext; @@ -45,7 +44,6 @@ public class Plaintext { /** * Factory method to create an empty {@link Plaintext}. - * * @return the empty {@link Plaintext} object. * @since 1.1.2 */ @@ -55,7 +53,6 @@ public class Plaintext { /** * Factory method to create {@link Plaintext} from a byte sequence. - * * @param plaintext the plaintext to encrypt, must not be {@literal null}. * @return the {@link Plaintext} for {@code plaintext}. */ @@ -74,7 +71,6 @@ public class Plaintext { * Factory method to create {@link Plaintext} using from {@link String}. * {@link String} is encoded to {@code byte} using the default * {@link java.nio.charset.Charset}. - * * @param plaintext the plaintext to encrypt, must not be {@literal null}. * @return the {@link Plaintext} for {@code plaintext}. */ @@ -90,17 +86,16 @@ public class Plaintext { } public byte[] getPlaintext() { - return plaintext; + return this.plaintext; } public VaultTransitContext getContext() { - return context; + return this.context; } /** * Create a new {@link Plaintext} object from this plaintext associated with the given * {@link VaultTransitContext}. - * * @param context transit context. * @return the new {@link Plaintext} object. */ @@ -123,14 +118,14 @@ public class Plaintext { if (!(o instanceof Plaintext)) return false; Plaintext plaintext1 = (Plaintext) o; - return Arrays.equals(plaintext, plaintext1.plaintext) - && context.equals(plaintext1.context); + return Arrays.equals(this.plaintext, plaintext1.plaintext) && this.context.equals(plaintext1.context); } @Override public int hashCode() { - int result = Objects.hash(context); - result = 31 * result + Arrays.hashCode(plaintext); + int result = Objects.hash(this.context); + result = 31 * result + Arrays.hashCode(this.plaintext); return result; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Policy.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Policy.java index 9261737e..a6f39fb4 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Policy.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Policy.java @@ -77,7 +77,6 @@ public class Policy { /** * Create an empty {@link Policy} without rules. - * * @return an empty {@link Policy}. */ public static Policy empty() { @@ -86,7 +85,6 @@ public class Policy { /** * Create a {@link Policy} from one or more {@code rules}. - * * @param rules must not be {@literal null}. * @return the {@link Policy} object containing {@code rules}. */ @@ -100,7 +98,6 @@ public class Policy { /** * Create a {@link Policy} from one or more {@code rules}. - * * @param rules must not be {@literal null}. * @return the {@link Policy} object containing {@code rules}. */ @@ -115,7 +112,6 @@ public class Policy { * Create a new {@link Policy} object containing all configured rules and add the * given {@link Rule} to the new policy object. If the given {@link Rule} matches an * existing rule path, the exiting rule will be overridden by the new rule object. - * * @param rule must not be {@literal null}. * @return the new {@link Policy} object containing all configured rules and the given * {@link Rule}. @@ -132,13 +128,12 @@ public class Policy { } public Set<Rule> getRules() { - return rules; + return this.rules; } /** * Lookup a {@link Rule} by its path. Returns {@literal null} if the rule was not * found. - * * @param path must not be {@literal null}. * @return the {@link Rule} or {@literal null}, if not found. */ @@ -147,7 +142,7 @@ public class Policy { Assert.notNull(path, "Path must not be null"); - for (Rule rule : rules) { + for (Rule rule : this.rules) { if (rule.getPath().equals(path)) { return rule; } @@ -163,12 +158,12 @@ public class Policy { if (!(o instanceof Policy)) return false; Policy policy = (Policy) o; - return rules.equals(policy.rules); + return this.rules.equals(policy.rules); } @Override public int hashCode() { - return Objects.hash(rules); + return Objects.hash(this.rules); } /** @@ -231,8 +226,10 @@ public class Policy { @JsonCreator private Rule(@JsonProperty("capabilities") List<Capability> capabilities, - @JsonProperty("min_wrapping_ttl") @JsonDeserialize(converter = StringToDurationConverter.class) Duration minWrappingTtl, - @JsonProperty("max_wrapping_ttl") @JsonDeserialize(converter = StringToDurationConverter.class) Duration maxWrappingTtl, + @JsonProperty("min_wrapping_ttl") @JsonDeserialize( + converter = StringToDurationConverter.class) Duration minWrappingTtl, + @JsonProperty("max_wrapping_ttl") @JsonDeserialize( + converter = StringToDurationConverter.class) Duration maxWrappingTtl, @JsonProperty("allowed_parameters") Map<String, List<String>> allowedParameters, @JsonProperty("denied_parameters") Map<String, List<String>> deniedParameters) { @@ -244,9 +241,8 @@ public class Policy { this.deniedParameters = deniedParameters; } - private Rule(String path, List<Capability> capabilities, - @Nullable Duration minWrappingTtl, @Nullable Duration maxWrappingTtl, - Map<String, List<String>> allowedParameters, + private Rule(String path, List<Capability> capabilities, @Nullable Duration minWrappingTtl, + @Nullable Duration maxWrappingTtl, Map<String, List<String>> allowedParameters, Map<String, List<String>> deniedParameters) { this.path = path; @@ -259,7 +255,6 @@ public class Policy { /** * Create a new builder for {@link Rule}. - * * @return a new {@link RuleBuilder}. */ public static RuleBuilder builder() { @@ -267,34 +262,34 @@ public class Policy { } private Rule withPath(String path) { - return new Rule(path, capabilities, minWrappingTtl, maxWrappingTtl, - allowedParameters, deniedParameters); + return new Rule(path, this.capabilities, this.minWrappingTtl, this.maxWrappingTtl, this.allowedParameters, + this.deniedParameters); } public String getPath() { - return path; + return this.path; } public List<Capability> getCapabilities() { - return capabilities; + return this.capabilities; } @Nullable public Duration getMinWrappingTtl() { - return minWrappingTtl; + return this.minWrappingTtl; } @Nullable public Duration getMaxWrappingTtl() { - return maxWrappingTtl; + return this.maxWrappingTtl; } public Map<String, List<String>> getAllowedParameters() { - return allowedParameters; + return this.allowedParameters; } public Map<String, List<String>> getDeniedParameters() { - return deniedParameters; + return this.deniedParameters; } @Override @@ -304,12 +299,12 @@ public class Policy { if (!(o instanceof Rule)) return false; Rule rule = (Rule) o; - return path.equals(rule.path); + return this.path.equals(rule.path); } @Override public int hashCode() { - return Objects.hash(path); + return Objects.hash(this.path); } /** @@ -329,11 +324,12 @@ public class Policy { private Map<String, List<String>> allowedParameters = new LinkedHashMap<String, List<String>>(); - private Map<String, List<String>> deniedParameters = new LinkedHashMap<String, List<String>>();; + private Map<String, List<String>> deniedParameters = new LinkedHashMap<String, List<String>>(); + + ; /** * Associate a {@code path} with the rule. - * * @param path must not be {@literal null} or empty. * @return {@code this} {@link RuleBuilder}. */ @@ -348,7 +344,6 @@ public class Policy { /** * Configure a {@link Capability} for the rule. Capabilities are added when * calling this method and do not replace already configured capabilities. - * * @param capability must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. */ @@ -363,15 +358,13 @@ public class Policy { /** * Configure capabilities. apabilities are added when calling this method and * do not replace already configured capabilities. - * * @param capabilities must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. */ public RuleBuilder capabilities(Capability... capabilities) { Assert.notNull(capabilities, "Capabilities must not be null"); - Assert.noNullElements(capabilities, - "Capabilities must not contain null elements"); + Assert.noNullElements(capabilities, "Capabilities must not contain null elements"); return capabilities(Arrays.asList(capabilities)); } @@ -381,25 +374,22 @@ public class Policy { * resolves capabilities using {@link BuiltinCapabilities}. Capabilities are * added when calling this method and do not replace already configured * capabilities. - * * @param capabilities must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. * @throws IllegalArgumentException if the capability cannot be resolved to a - * built-in {@link Capability}. + * built-in {@link Capability}. */ public RuleBuilder capabilities(String... capabilities) { Assert.notNull(capabilities, "Capabilities must not be null"); - Assert.noNullElements(capabilities, - "Capabilities must not contain null elements"); + Assert.noNullElements(capabilities, "Capabilities must not contain null elements"); List<Capability> mapped = Arrays.stream(capabilities).map(value -> { Capability capability = BuiltinCapabilities.find(value); if (capability == null) { - throw new IllegalArgumentException( - "Cannot resolve " + value + " to a capability"); + throw new IllegalArgumentException("Cannot resolve " + value + " to a capability"); } return capability; }).collect(Collectors.toList()); @@ -418,7 +408,6 @@ public class Policy { /** * Configure a min TTL for response wrapping. - * * @param ttl must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. */ @@ -432,7 +421,6 @@ public class Policy { /** * Configure a max TTL for response wrapping. - * * @param ttl must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. */ @@ -449,7 +437,6 @@ public class Policy { * Allowing parameter values replaces previously configured allowed parameter * values. Empty {@code values} allow all values for the given parameter * {@code name}. - * * @param name must not be {@literal null} or empty. * @param values must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. @@ -468,7 +455,6 @@ public class Policy { * Configure denied parameter values given {@code name} and {@code values}. * Denying parameter values replaces previously configured denied parameter * values. Empty {@code values} deny parameter usage. - * * @param name must not be {@literal null} or empty. * @param values must not be {@literal null}. * @return {@code this} {@link RuleBuilder}. @@ -486,14 +472,12 @@ public class Policy { /** * Build the {@link Rule} object. Requires a configured {@link #path(String)} * and at least one {@link #capability(Policy.Capability)}. - * * @return the new {@link Rule} object. */ public Rule build() { - Assert.state(StringUtils.hasText(path), "Path must not be empty"); - Assert.state(!capabilities.isEmpty(), - "Rule must define one or more capabilities"); + Assert.state(StringUtils.hasText(this.path), "Path must not be empty"); + Assert.state(!this.capabilities.isEmpty(), "Rule must define one or more capabilities"); List<Capability> capabilities; switch (this.capabilities.size()) { @@ -501,21 +485,17 @@ public class Policy { capabilities = Collections.emptyList(); break; case 1: - capabilities = Collections - .singletonList(this.capabilities.iterator().next()); + capabilities = Collections.singletonList(this.capabilities.iterator().next()); break; default: - capabilities = Collections - .unmodifiableList(new ArrayList<>(this.capabilities)); + capabilities = Collections.unmodifiableList(new ArrayList<>(this.capabilities)); } - return new Rule(path, capabilities, minWrappingTtl, maxWrappingTtl, - createMap(this.allowedParameters), - createMap(this.deniedParameters)); + return new Rule(this.path, capabilities, this.minWrappingTtl, this.maxWrappingTtl, + createMap(this.allowedParameters), createMap(this.deniedParameters)); } - private Map<String, List<String>> createMap( - Map<String, List<String>> source) { + private Map<String, List<String>> createMap(Map<String, List<String>> source) { if (source.isEmpty()) { return Collections.emptyMap(); @@ -523,7 +503,9 @@ public class Policy { return Collections.unmodifiableMap(new LinkedHashMap<>(source)); } + } + } /** @@ -535,6 +517,7 @@ public class Policy { * @return the capability literal. */ String name(); + } /** @@ -594,7 +577,6 @@ public class Policy { /** * Find a {@link Capability} by its name. The name is compared case-insensitive. - * * @param value must not be {@literal null}. * @return the {@link Capability} or {@literal null}, if not found. */ @@ -609,13 +591,13 @@ public class Policy { return null; } + } static class PolicySerializer extends JsonSerializer<Policy> { @Override - public void serialize(Policy value, JsonGenerator gen, - SerializerProvider serializers) throws IOException { + public void serialize(Policy value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); @@ -630,13 +612,13 @@ public class Policy { gen.writeEndObject(); } + } static class PolicyDeserializer extends JsonDeserializer<Policy> { @Override - public Policy deserialize(JsonParser p, DeserializationContext ctxt) - throws IOException { + public Policy deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Assert.isTrue(p.getCurrentToken() == JsonToken.START_OBJECT, "Expected START_OBJECT, got: " + p.getCurrentToken()); @@ -679,6 +661,7 @@ public class Policy { "Expected END_OBJECT, got: " + p.getCurrentToken()); return Policy.of(rules); } + } static class CapabilityToStringConverter implements Converter<Capability, String> { @@ -697,6 +680,7 @@ public class Policy { public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(String.class); } + } static class StringToCapabilityConverter implements Converter<String, Capability> { @@ -718,6 +702,7 @@ public class Policy { public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(Capability.class); } + } static class DurationToStringConverter implements Converter<Duration, String> { @@ -736,6 +721,7 @@ public class Policy { public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(String.class); } + } static class StringToDurationConverter implements Converter<String, Duration> { @@ -767,8 +753,7 @@ public class Policy { return Duration.ofHours(Long.parseLong(matcher.group(1))); } - throw new IllegalArgumentException( - "Unsupported duration value: " + value); + throw new IllegalArgumentException("Unsupported duration value: " + value); } } @@ -781,5 +766,7 @@ public class Policy { public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(Capability.class); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/RawTransitKey.java b/spring-vault-core/src/main/java/org/springframework/vault/support/RawTransitKey.java index 108a5839..52fe4fbb 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/RawTransitKey.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/RawTransitKey.java @@ -33,4 +33,5 @@ public interface RawTransitKey { * @return name of the key */ String getName(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Signature.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Signature.java index 84268d77..861dbf14 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Signature.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Signature.java @@ -36,7 +36,6 @@ public class Signature { /** * Factory method to create a {@link Signature} from the given {@code signature}. - * * @param signature the signature, must not be {@literal null} or empty. * @return the {@link Signature} encapsulating {@code signature}. */ @@ -48,7 +47,7 @@ public class Signature { } public String getSignature() { - return signature; + return this.signature; } @Override @@ -58,20 +57,21 @@ public class Signature { if (!(o instanceof Signature)) return false; Signature that = (Signature) o; - return signature.equals(that.signature); + return this.signature.equals(that.signature); } @Override public int hashCode() { - return Objects.hash(signature); + return Objects.hash(this.signature); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [signature='").append(signature).append('\''); + sb.append(" [signature='").append(this.signature).append('\''); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/SignatureValidation.java b/spring-vault-core/src/main/java/org/springframework/vault/support/SignatureValidation.java index 6e0596c3..b1723d08 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/SignatureValidation.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/SignatureValidation.java @@ -38,7 +38,6 @@ public class SignatureValidation { /** * Factory method to create a {@link SignatureValidation} object representing a * successfully validated signature. - * * @return a {@link SignatureValidation} object representing a successfully validated * signature. */ @@ -49,7 +48,6 @@ public class SignatureValidation { /** * Factory method to create a {@link SignatureValidation} object representing a failed * signature validation. - * * @return a {@link SignatureValidation} object representing a failed signature * validation. */ @@ -58,7 +56,7 @@ public class SignatureValidation { } public boolean isValid() { - return state; + return this.state; } @Override @@ -68,20 +66,21 @@ public class SignatureValidation { if (!(o instanceof SignatureValidation)) return false; SignatureValidation that = (SignatureValidation) o; - return state == that.state; + return this.state == that.state; } @Override public int hashCode() { - return Objects.hash(state); + return Objects.hash(this.state); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); - sb.append(" [state=").append(state); + sb.append(" [state=").append(this.state); sb.append(']'); return sb.toString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/SslConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/support/SslConfiguration.java index 07aa101b..8c282991 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/SslConfiguration.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/SslConfiguration.java @@ -50,7 +50,6 @@ public class SslConfiguration { /** * Create a new {@link SslConfiguration} with the default {@link KeyStore} type. - * * @param keyStore the key store resource, must not be {@literal null}. * @param keyStorePassword the key store password. * @param trustStore the trust store resource, must not be {@literal null}. @@ -61,49 +60,42 @@ public class SslConfiguration { * GC than necessary. */ @Deprecated - public SslConfiguration(Resource keyStore, @Nullable String keyStorePassword, - Resource trustStore, @Nullable String trustStorePassword) { + public SslConfiguration(Resource keyStore, @Nullable String keyStorePassword, Resource trustStore, + @Nullable String trustStorePassword) { - this(new KeyStoreConfiguration(keyStore, charsOrNull(keyStorePassword), - DEFAULT_KEYSTORE_TYPE), - new KeyStoreConfiguration(trustStore, charsOrNull(trustStorePassword), - DEFAULT_KEYSTORE_TYPE)); + this(new KeyStoreConfiguration(keyStore, charsOrNull(keyStorePassword), DEFAULT_KEYSTORE_TYPE), + new KeyStoreConfiguration(trustStore, charsOrNull(trustStorePassword), DEFAULT_KEYSTORE_TYPE)); } /** * Create a new {@link SslConfiguration}. - * * @param keyStoreConfiguration the key store configuration, must not be - * {@literal null}. + * {@literal null}. * @param trustStoreConfiguration the trust store configuration, must not be - * {@literal null}. + * {@literal null}. * @since 1.1 */ public SslConfiguration(KeyStoreConfiguration keyStoreConfiguration, KeyStoreConfiguration trustStoreConfiguration) { - this(keyStoreConfiguration, KeyConfiguration.unconfigured(), - trustStoreConfiguration); + this(keyStoreConfiguration, KeyConfiguration.unconfigured(), trustStoreConfiguration); } /** * Create a new {@link SslConfiguration}. - * * @param keyStoreConfiguration the key store configuration, must not be - * {@literal null}. + * {@literal null}. * @param keyConfiguration the configuration for a specific key in - * {@code keyStoreConfiguration} to use. + * {@code keyStoreConfiguration} to use. * @param trustStoreConfiguration the trust store configuration, must not be - * {@literal null}. + * {@literal null}. * @since 2.2 */ - public SslConfiguration(KeyStoreConfiguration keyStoreConfiguration, - KeyConfiguration keyConfiguration, + public SslConfiguration(KeyStoreConfiguration keyStoreConfiguration, KeyConfiguration keyConfiguration, KeyStoreConfiguration trustStoreConfiguration) { Assert.notNull(keyStoreConfiguration, "KeyStore configuration must not be null"); Assert.notNull(keyConfiguration, "KeyConfiguration must not be null"); - Assert.notNull(trustStoreConfiguration, - "TrustStore configuration must not be null"); + Assert.notNull(trustStoreConfiguration, "TrustStore configuration must not be null"); this.keyStoreConfiguration = keyStoreConfiguration; this.keyConfiguration = keyConfiguration; @@ -113,9 +105,8 @@ public class SslConfiguration { /** * Create a new {@link SslConfiguration} for the given trust store with the default * {@link KeyStore} type. - * * @param trustStore resource pointing to an existing trust store, must not be - * {@literal null}. + * {@literal null}. * @param trustStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore @@ -124,37 +115,31 @@ public class SslConfiguration { * GC than necessary. */ @Deprecated - public static SslConfiguration forTrustStore(Resource trustStore, - @Nullable String trustStorePassword) { + public static SslConfiguration forTrustStore(Resource trustStore, @Nullable String trustStorePassword) { return forTrustStore(trustStore, charsOrNull(trustStorePassword)); } /** * Create a new {@link SslConfiguration} for the given trust store with the default * {@link KeyStore} type. - * * @param trustStore resource pointing to an existing trust store, must not be - * {@literal null}. + * {@literal null}. * @param trustStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore */ - public static SslConfiguration forTrustStore(Resource trustStore, - @Nullable char[] trustStorePassword) { + public static SslConfiguration forTrustStore(Resource trustStore, @Nullable char[] trustStorePassword) { Assert.notNull(trustStore, "TrustStore must not be null"); - Assert.isTrue(trustStore.exists(), - () -> String.format("TrustStore %s does not exist", trustStore)); + Assert.isTrue(trustStore.exists(), () -> String.format("TrustStore %s does not exist", trustStore)); - return new SslConfiguration(KeyStoreConfiguration.unconfigured(), - KeyConfiguration.unconfigured(), new KeyStoreConfiguration(trustStore, - trustStorePassword, DEFAULT_KEYSTORE_TYPE)); + return new SslConfiguration(KeyStoreConfiguration.unconfigured(), KeyConfiguration.unconfigured(), + new KeyStoreConfiguration(trustStore, trustStorePassword, DEFAULT_KEYSTORE_TYPE)); } /** * Create a new {@link SslConfiguration} for the given {@link KeyStoreConfiguration * trust store}. - * * @param trustStore must not be {@literal null}. * @return a new {@link SslConfiguration} with {@link KeyStoreConfiguration trust * store configuration} applied. @@ -168,9 +153,8 @@ public class SslConfiguration { /** * Create a new {@link SslConfiguration} for the given key store with the default * {@link KeyStore} type. - * * @param keyStore resource pointing to an existing key store, must not be - * {@literal null}. + * {@literal null}. * @param keyStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore @@ -179,33 +163,29 @@ public class SslConfiguration { * GC than necessary. */ @Deprecated - public static SslConfiguration forKeyStore(Resource keyStore, - @Nullable String keyStorePassword) { + public static SslConfiguration forKeyStore(Resource keyStore, @Nullable String keyStorePassword) { return forKeyStore(keyStore, charsOrNull(keyStorePassword)); } /** * Create a new {@link SslConfiguration} for the given key store with the default * {@link KeyStore} type. - * * @param keyStore resource pointing to an existing key store, must not be - * {@literal null}. + * {@literal null}. * @param keyStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore */ - public static SslConfiguration forKeyStore(Resource keyStore, - @Nullable char[] keyStorePassword) { - return forKeyStore(new KeyStoreConfiguration(keyStore, keyStorePassword, - DEFAULT_KEYSTORE_TYPE), KeyConfiguration.unconfigured()); + public static SslConfiguration forKeyStore(Resource keyStore, @Nullable char[] keyStorePassword) { + return forKeyStore(new KeyStoreConfiguration(keyStore, keyStorePassword, DEFAULT_KEYSTORE_TYPE), + KeyConfiguration.unconfigured()); } /** * Create a new {@link SslConfiguration} for the given {@link KeyStoreConfiguration * key store}. - * * @param keyStore resource pointing to an existing key store, must not be - * {@literal null}. + * {@literal null}. * @return the created {@link SslConfiguration}. * @since 2.2 * @see java.security.KeyStore @@ -217,56 +197,49 @@ public class SslConfiguration { /** * Create a new {@link SslConfiguration} for the given {@link KeyStoreConfiguration * key store} and {@link KeyConfiguration}. - * * @param keyStore resource pointing to an existing key store, must not be - * {@literal null}. + * {@literal null}. * @param keyConfiguration the configuration for a specific key in - * {@code keyStoreConfiguration} to use. + * {@code keyStoreConfiguration} to use. * @return the created {@link SslConfiguration}. * @since 2.2 * @see java.security.KeyStore */ - public static SslConfiguration forKeyStore(KeyStoreConfiguration keyStore, - KeyConfiguration keyConfiguration) { + public static SslConfiguration forKeyStore(KeyStoreConfiguration keyStore, KeyConfiguration keyConfiguration) { return unconfigured().withKeyStore(keyStore, keyConfiguration); } /** * Create a new {@link SslConfiguration} for the given key store with the default * {@link KeyStore} type. - * * @param keyStore resource pointing to an existing key store, must not be - * {@literal null}. + * {@literal null}. * @param keyStorePassword may be {@literal null}. * @param keyConfiguration the configuration for a specific key in - * {@code keyStoreConfiguration} to use. + * {@code keyStoreConfiguration} to use. * @return the created {@link SslConfiguration}. * @since 2.2 * @see java.security.KeyStore */ - public static SslConfiguration forKeyStore(Resource keyStore, - @Nullable char[] keyStorePassword, KeyConfiguration keyConfiguration) { + public static SslConfiguration forKeyStore(Resource keyStore, @Nullable char[] keyStorePassword, + KeyConfiguration keyConfiguration) { Assert.notNull(keyStore, "KeyStore must not be null"); - Assert.isTrue(keyStore.exists(), - () -> String.format("KeyStore %s does not exist", keyStore)); + Assert.isTrue(keyStore.exists(), () -> String.format("KeyStore %s does not exist", keyStore)); Assert.notNull(keyConfiguration, "KeyConfiguration must not be null"); - return new SslConfiguration( - new KeyStoreConfiguration(keyStore, keyStorePassword, - DEFAULT_KEYSTORE_TYPE), + return new SslConfiguration(new KeyStoreConfiguration(keyStore, keyStorePassword, DEFAULT_KEYSTORE_TYPE), keyConfiguration, KeyStoreConfiguration.unconfigured()); } /** * Create a new {@link SslConfiguration} for the given truststore with the default * {@link KeyStore} type. - * * @param keyStore resource pointing to an existing keystore, must not be - * {@literal null}. + * {@literal null}. * @param keyStorePassword may be {@literal null}. * @param trustStore resource pointing to an existing trust store, must not be - * {@literal null}. + * {@literal null}. * @param trustStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore @@ -275,53 +248,43 @@ public class SslConfiguration { * longer from GC than necessary. */ @Deprecated - public SslConfiguration create(Resource keyStore, @Nullable String keyStorePassword, - Resource trustStore, @Nullable String trustStorePassword) { - return create(keyStore, charsOrNull(keyStorePassword), trustStore, - charsOrNull(trustStorePassword)); + public SslConfiguration create(Resource keyStore, @Nullable String keyStorePassword, Resource trustStore, + @Nullable String trustStorePassword) { + return create(keyStore, charsOrNull(keyStorePassword), trustStore, charsOrNull(trustStorePassword)); } /** * Create a new {@link SslConfiguration} for the given truststore with the default * {@link KeyStore} type. - * * @param keyStore resource pointing to an existing keystore, must not be - * {@literal null}. + * {@literal null}. * @param keyStorePassword may be {@literal null}. * @param trustStore resource pointing to an existing trust store, must not be - * {@literal null}. + * {@literal null}. * @param trustStorePassword may be {@literal null}. * @return the created {@link SslConfiguration}. * @see java.security.KeyStore */ - public static SslConfiguration create(Resource keyStore, - @Nullable char[] keyStorePassword, Resource trustStore, + public static SslConfiguration create(Resource keyStore, @Nullable char[] keyStorePassword, Resource trustStore, @Nullable char[] trustStorePassword) { Assert.notNull(keyStore, "KeyStore must not be null"); - Assert.isTrue(keyStore.exists(), - () -> String.format("KeyStore %s does not exist", trustStore)); + Assert.isTrue(keyStore.exists(), () -> String.format("KeyStore %s does not exist", trustStore)); Assert.notNull(trustStore, "TrustStore must not be null"); - Assert.isTrue(trustStore.exists(), - String.format("TrustStore %s does not exist", trustStore)); + Assert.isTrue(trustStore.exists(), String.format("TrustStore %s does not exist", trustStore)); - return new SslConfiguration( - new KeyStoreConfiguration(keyStore, keyStorePassword, - DEFAULT_KEYSTORE_TYPE), - new KeyStoreConfiguration(trustStore, trustStorePassword, - DEFAULT_KEYSTORE_TYPE)); + return new SslConfiguration(new KeyStoreConfiguration(keyStore, keyStorePassword, DEFAULT_KEYSTORE_TYPE), + new KeyStoreConfiguration(trustStore, trustStorePassword, DEFAULT_KEYSTORE_TYPE)); } /** * Factory method returning an unconfigured {@link SslConfiguration} instance. - * * @return an unconfigured {@link SslConfiguration} instance. * @since 2.0 */ public static SslConfiguration unconfigured() { - return new SslConfiguration(KeyStoreConfiguration.unconfigured(), - KeyStoreConfiguration.unconfigured()); + return new SslConfiguration(KeyStoreConfiguration.unconfigured(), KeyStoreConfiguration.unconfigured()); } /** @@ -329,7 +292,7 @@ public class SslConfiguration { * not configured. */ public Resource getKeyStore() { - return keyStoreConfiguration.getResource(); + return this.keyStoreConfiguration.getResource(); } /** @@ -341,7 +304,7 @@ public class SslConfiguration { @Deprecated @Nullable public String getKeyStorePassword() { - return stringOrNull(keyStoreConfiguration.getStorePassword()); + return stringOrNull(this.keyStoreConfiguration.getStorePassword()); } /** @@ -349,7 +312,7 @@ public class SslConfiguration { * @since 1.1 */ public KeyStoreConfiguration getKeyStoreConfiguration() { - return keyStoreConfiguration; + return this.keyStoreConfiguration; } /** @@ -357,13 +320,12 @@ public class SslConfiguration { * @since 2.2 */ public KeyConfiguration getKeyConfiguration() { - return keyConfiguration; + return this.keyConfiguration; } /** * Create a new {@link SslConfiguration} with {@link KeyStoreConfiguration} applied * retaining the {@link #getTrustStoreConfiguration() trust store} configuration. - * * @param configuration must not be {@literal null}. * @return a new {@link SslConfiguration} with {@link KeyStoreConfiguration} applied. * @since 2.0 @@ -376,18 +338,15 @@ public class SslConfiguration { * Create a new {@link SslConfiguration} with {@link KeyStoreConfiguration} and * {@link KeyConfiguration} applied retaining the {@link #getTrustStoreConfiguration() * trust store} configuration. - * * @param configuration must not be {@literal null}. * @param keyConfiguration the configuration for a specific key in - * {@code keyStoreConfiguration} to use. + * {@code keyStoreConfiguration} to use. * @return a new {@link SslConfiguration} with {@link KeyStoreConfiguration} and * {@link KeyConfiguration} applied. * @since 2.2 */ - public SslConfiguration withKeyStore(KeyStoreConfiguration configuration, - KeyConfiguration keyConfiguration) { - return new SslConfiguration(configuration, keyConfiguration, - this.trustStoreConfiguration); + public SslConfiguration withKeyStore(KeyStoreConfiguration configuration, KeyConfiguration keyConfiguration) { + return new SslConfiguration(configuration, keyConfiguration, this.trustStoreConfiguration); } /** @@ -395,7 +354,7 @@ public class SslConfiguration { * not configured. */ public Resource getTrustStore() { - return trustStoreConfiguration.getResource(); + return this.trustStoreConfiguration.getResource(); } /** @@ -407,7 +366,7 @@ public class SslConfiguration { @Deprecated @Nullable public String getTrustStorePassword() { - return stringOrNull(trustStoreConfiguration.getStorePassword()); + return stringOrNull(this.trustStoreConfiguration.getStorePassword()); } /** @@ -415,22 +374,20 @@ public class SslConfiguration { * @since 1.1 */ public KeyStoreConfiguration getTrustStoreConfiguration() { - return trustStoreConfiguration; + return this.trustStoreConfiguration; } /** * Create a new {@link SslConfiguration} with {@link KeyStoreConfiguration trust store * configuration} applied retaining the {@link #getKeyStoreConfiguration()} key store} * configuration. - * * @param configuration must not be {@literal null}. * @return a new {@link SslConfiguration} with {@link KeyStoreConfiguration trust * store configuration} applied. * @since 2.0 */ public SslConfiguration withTrustStore(KeyStoreConfiguration configuration) { - return new SslConfiguration(this.keyStoreConfiguration, this.keyConfiguration, - configuration); + return new SslConfiguration(this.keyStoreConfiguration, this.keyConfiguration, configuration); } @Nullable @@ -450,8 +407,8 @@ public class SslConfiguration { */ public static class KeyStoreConfiguration { - private static final KeyStoreConfiguration UNCONFIGURED = new KeyStoreConfiguration( - AbsentResource.INSTANCE, null, DEFAULT_KEYSTORE_TYPE); + private static final KeyStoreConfiguration UNCONFIGURED = new KeyStoreConfiguration(AbsentResource.INSTANCE, + null, DEFAULT_KEYSTORE_TYPE); /** * Store that holds certificates, private keys. @@ -472,8 +429,7 @@ public class SslConfiguration { /** * Create a new {@link KeyStoreConfiguration}. */ - public KeyStoreConfiguration(Resource resource, @Nullable char[] storePassword, - String storeType) { + public KeyStoreConfiguration(Resource resource, @Nullable char[] storePassword, String storeType) { Assert.notNull(resource, "Resource must not be null"); Assert.isTrue(resource instanceof AbsentResource || resource.exists(), @@ -493,9 +449,8 @@ public class SslConfiguration { /** * Create a new {@link KeyStoreConfiguration} given {@link Resource}. - * * @param resource resource referencing the key store, must not be {@literal null} - * . + * . * @return the {@link KeyStoreConfiguration} for {@code resource}. * @since 2.0 */ @@ -506,22 +461,18 @@ public class SslConfiguration { /** * Create a new {@link KeyStoreConfiguration} given {@link Resource} and * {@code storePassword} using the default keystore type. - * * @param resource resource referencing the key store, must not be {@literal null} - * . + * . * @param storePassword key store password, may be {@literal null}. * @return the {@link KeyStoreConfiguration} for {@code resource}. * @since 2.0 */ - public static KeyStoreConfiguration of(Resource resource, - @Nullable char[] storePassword) { - return new KeyStoreConfiguration(resource, storePassword, - DEFAULT_KEYSTORE_TYPE); + public static KeyStoreConfiguration of(Resource resource, @Nullable char[] storePassword) { + return new KeyStoreConfiguration(resource, storePassword, DEFAULT_KEYSTORE_TYPE); } /** * Create an unconfigured, empty {@link KeyStoreConfiguration}. - * * @return unconfigured, empty {@link KeyStoreConfiguration}. * @since 2.0 */ @@ -534,7 +485,7 @@ public class SslConfiguration { * @since 2.0 */ public boolean isPresent() { - return !(resource instanceof AbsentResource); + return !(this.resource instanceof AbsentResource); } /** @@ -542,7 +493,7 @@ public class SslConfiguration { * {@literal null} if not configured. */ public Resource getResource() { - return resource; + return this.resource; } /** @@ -551,15 +502,16 @@ public class SslConfiguration { */ @Nullable public char[] getStorePassword() { - return storePassword; + return this.storePassword; } /** * @return the trust store type. */ public String getStoreType() { - return storeType; + return this.storeType; } + } /** @@ -570,15 +522,13 @@ public class SslConfiguration { */ public static class KeyConfiguration { - private static final KeyConfiguration UNCONFIGURED = new KeyConfiguration(null, - null); + private static final KeyConfiguration UNCONFIGURED = new KeyConfiguration(null, null); private final @Nullable char[] keyPassword; private final @Nullable String keyAlias; - private KeyConfiguration(@Nullable char[] keyPassword, - @Nullable String keyAlias) { + private KeyConfiguration(@Nullable char[] keyPassword, @Nullable String keyAlias) { if (keyPassword == null) { this.keyPassword = null; @@ -592,7 +542,6 @@ public class SslConfiguration { /** * Create an unconfigured, empty {@link KeyConfiguration}. - * * @return unconfigured, empty {@link KeyConfiguration}. */ public static KeyConfiguration unconfigured() { @@ -602,15 +551,13 @@ public class SslConfiguration { /** * Create a {@link KeyConfiguration} to configure a specific key within a * {@link KeyStore}. - * * @param keyPassword the key password to use. Uses - * {@link KeyStoreConfiguration#getStorePassword()} if left {@code null}. + * {@link KeyStoreConfiguration#getStorePassword()} if left {@code null}. * @param keyAlias the key alias to use. Uses the first alias if left {@code null} - * . + * . * @return the {@link KeyConfiguration}. */ - public static KeyConfiguration of(@Nullable char[] keyPassword, - @Nullable String keyAlias) { + public static KeyConfiguration of(@Nullable char[] keyPassword, @Nullable String keyAlias) { return new KeyConfiguration(keyPassword, keyAlias); } @@ -619,7 +566,7 @@ public class SslConfiguration { */ @Nullable public char[] getKeyPassword() { - return keyPassword; + return this.keyPassword; } /** @@ -627,8 +574,9 @@ public class SslConfiguration { */ @Nullable public String getKeyAlias() { - return keyAlias; + return this.keyAlias; } + } static class AbsentResource extends AbstractResource { @@ -647,5 +595,7 @@ public class SslConfiguration { public InputStream getInputStream() throws IOException { throw new UnsupportedOperationException("Empty resource"); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/TransitKeyType.java b/spring-vault-core/src/main/java/org/springframework/vault/support/TransitKeyType.java index 451000dd..ee3f36e6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/TransitKeyType.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/TransitKeyType.java @@ -35,4 +35,5 @@ public enum TransitKeyType { public String getValue() { return this.value; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateRequest.java index 9184c3c6..85b4b526 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateRequest.java @@ -64,9 +64,8 @@ public class VaultCertificateRequest { */ private final boolean excludeCommonNameFromSubjectAltNames; - private VaultCertificateRequest(String commonName, List<String> altNames, - List<String> ipSubjectAltNames, List<String> uriSubjectAltNames, - @Nullable Duration ttl, boolean excludeCommonNameFromSubjectAltNames) { + private VaultCertificateRequest(String commonName, List<String> altNames, List<String> ipSubjectAltNames, + List<String> uriSubjectAltNames, @Nullable Duration ttl, boolean excludeCommonNameFromSubjectAltNames) { this.commonName = commonName; this.altNames = altNames; @@ -85,7 +84,6 @@ public class VaultCertificateRequest { /** * Create a new {@link VaultCertificateRequest} given a {@code commonName}. - * * @param commonName must not be empty or {@literal null}. * @return the created {@link VaultCertificateRequest}. */ @@ -94,28 +92,28 @@ public class VaultCertificateRequest { } public String getCommonName() { - return commonName; + return this.commonName; } public List<String> getAltNames() { - return altNames; + return this.altNames; } public List<String> getIpSubjectAltNames() { - return ipSubjectAltNames; + return this.ipSubjectAltNames; } public List<String> getUriSubjectAltNames() { - return uriSubjectAltNames; + return this.uriSubjectAltNames; } @Nullable public Duration getTtl() { - return ttl; + return this.ttl; } public boolean isExcludeCommonNameFromSubjectAltNames() { - return excludeCommonNameFromSubjectAltNames; + return this.excludeCommonNameFromSubjectAltNames; } public static class VaultCertificateRequestBuilder { @@ -139,7 +137,6 @@ public class VaultCertificateRequest { /** * Configure the common name. - * * @param commonName must not be empty or {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. */ @@ -153,7 +150,6 @@ public class VaultCertificateRequest { /** * Configure alternative names. Replaces previously configured alt names. - * * @param altNames must not be {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. */ @@ -167,7 +163,6 @@ public class VaultCertificateRequest { /** * Add an alternative name. - * * @param altName must not be empty or {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. */ @@ -182,12 +177,10 @@ public class VaultCertificateRequest { /** * Configure IP subject alternative names. Replaces previously configured IP * subject alt names. - * * @param ipSubjectAltNames must not be {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. */ - public VaultCertificateRequestBuilder ipSubjectAltNames( - Iterable<String> ipSubjectAltNames) { + public VaultCertificateRequestBuilder ipSubjectAltNames(Iterable<String> ipSubjectAltNames) { Assert.notNull(ipSubjectAltNames, "IP subject alt names must not be null"); @@ -197,12 +190,10 @@ public class VaultCertificateRequest { /** * Add an IP subject alternative name. - * * @param ipSubjectAltName must not be empty or {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. */ - public VaultCertificateRequestBuilder withIpSubjectAltName( - String ipSubjectAltName) { + public VaultCertificateRequestBuilder withIpSubjectAltName(String ipSubjectAltName) { Assert.hasText(ipSubjectAltName, "IP subject alt name must not be empty"); @@ -213,13 +204,11 @@ public class VaultCertificateRequest { /** * Configure URI subject alternative names. Replaces previously configured URI * subject alt names. - * * @param uriSubjectAltNames must not be {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. * @since 2.2 */ - public VaultCertificateRequestBuilder uriSubjectAltNames( - Iterable<String> uriSubjectAltNames) { + public VaultCertificateRequestBuilder uriSubjectAltNames(Iterable<String> uriSubjectAltNames) { Assert.notNull(uriSubjectAltNames, "URI subject alt names must not be null"); @@ -229,13 +218,11 @@ public class VaultCertificateRequest { /** * Add an URI subject alternative name. - * * @param uriSubjectAltName must not be empty or {@literal null}. * @return {@code this} {@link VaultCertificateRequestBuilder}. * @since 2.2 */ - public VaultCertificateRequestBuilder withUriSubjectAltName( - String uriSubjectAltName) { + public VaultCertificateRequestBuilder withUriSubjectAltName(String uriSubjectAltName) { Assert.hasText(uriSubjectAltName, "URI subject alt name must not be empty"); @@ -245,7 +232,6 @@ public class VaultCertificateRequest { /** * Configure a TTL. - * * @param ttl the time to live, in seconds, must not be negative. * @return {@code this} {@link VaultCertificateRequestBuilder}. * @deprecated since 2.0, use {@link #ttl(Duration)} for time unit safety. @@ -261,7 +247,6 @@ public class VaultCertificateRequest { /** * Configure a TTL. - * * @param ttl the time to live, must not be negative. * @param timeUnit must not be {@literal null} * @return {@code this} {@link VaultCertificateRequestBuilder}. @@ -277,7 +262,6 @@ public class VaultCertificateRequest { /** * Configure a TTL. - * * @param ttl the time to live, must not be {@literal null} or negative. * @return {@code this} {@link VaultCertificateRequestBuilder}. * @since 2.0 @@ -295,7 +279,6 @@ public class VaultCertificateRequest { * Exclude the given common name from DNS or Email Subject Alternate Names (as * appropriate). Useful if the CN is not a hostname or email address, but is * instead some human-readable identifier. - * * @return {@code this} {@link VaultCertificateRequestBuilder}. */ public VaultCertificateRequestBuilder excludeCommonNameFromSubjectAltNames() { @@ -307,13 +290,12 @@ public class VaultCertificateRequest { /** * Build a new {@link VaultCertificateRequest} instance. Requires * {@link #commonName(String)} to be configured. - * * @return a new {@link VaultCertificateRequest}. */ public VaultCertificateRequest build() { - Assert.notNull(commonName, "Common name must not be null"); - Assert.hasText(commonName, "Common name must not be empty"); + Assert.notNull(this.commonName, "Common name must not be null"); + Assert.hasText(this.commonName, "Common name must not be empty"); List<String> altNames; switch (this.altNames.size()) { @@ -324,8 +306,7 @@ public class VaultCertificateRequest { altNames = java.util.Collections.singletonList(this.altNames.get(0)); break; default: - altNames = java.util.Collections - .unmodifiableList(new ArrayList<>(this.altNames)); + altNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.altNames)); } List<String> ipSubjectAltNames; @@ -334,12 +315,10 @@ public class VaultCertificateRequest { ipSubjectAltNames = java.util.Collections.emptyList(); break; case 1: - ipSubjectAltNames = java.util.Collections - .singletonList(this.ipSubjectAltNames.get(0)); + ipSubjectAltNames = java.util.Collections.singletonList(this.ipSubjectAltNames.get(0)); break; default: - ipSubjectAltNames = java.util.Collections - .unmodifiableList(new ArrayList<>(this.ipSubjectAltNames)); + ipSubjectAltNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.ipSubjectAltNames)); } List<String> uriSubjectAltNames; @@ -348,16 +327,14 @@ public class VaultCertificateRequest { uriSubjectAltNames = java.util.Collections.emptyList(); break; case 1: - uriSubjectAltNames = java.util.Collections - .singletonList(this.uriSubjectAltNames.get(0)); + uriSubjectAltNames = java.util.Collections.singletonList(this.uriSubjectAltNames.get(0)); break; default: - uriSubjectAltNames = java.util.Collections - .unmodifiableList(new ArrayList<>(this.uriSubjectAltNames)); + uriSubjectAltNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.uriSubjectAltNames)); } - return new VaultCertificateRequest(commonName, altNames, ipSubjectAltNames, - uriSubjectAltNames, ttl, excludeCommonNameFromSubjectAltNames); + return new VaultCertificateRequest(this.commonName, altNames, ipSubjectAltNames, uriSubjectAltNames, + this.ttl, this.excludeCommonNameFromSubjectAltNames); } private static <E> List<E> toList(Iterable<E> iter) { @@ -369,5 +346,7 @@ public class VaultCertificateRequest { return list; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateResponse.java index e0cbca43..3d4ef484 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultCertificateResponse.java @@ -21,4 +21,5 @@ package org.springframework.vault.support; * @author Mark Paluch */ public class VaultCertificateResponse extends VaultResponseSupport<CertificateBundle> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultDecryptionResult.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultDecryptionResult.java index 9ca80f25..cda0a20c 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultDecryptionResult.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultDecryptionResult.java @@ -33,7 +33,6 @@ public class VaultDecryptionResult extends AbstractResult<Plaintext> { /** * Create {@link VaultDecryptionResult} for a successfully decrypted {@link Plaintext} * . - * * @param plaintext must not be {@literal null}. */ public VaultDecryptionResult(Plaintext plaintext) { @@ -45,7 +44,6 @@ public class VaultDecryptionResult extends AbstractResult<Plaintext> { /** * Create {@link VaultDecryptionResult} for an error during decryption. - * * @param exception must not be {@literal null}. */ public VaultDecryptionResult(VaultException exception) { @@ -57,14 +55,13 @@ public class VaultDecryptionResult extends AbstractResult<Plaintext> { @Nullable @Override protected Plaintext get0() { - return plaintext; + return this.plaintext; } /** * Return the result as {@link String} or throw a {@link VaultException} if the * operation completed with an error. Use {@link #isSuccessful()} to verify the * success status of this result without throwing an exception. - * * @return the result value. * @throws VaultException if the operation completed with an error. */ @@ -74,4 +71,5 @@ public class VaultDecryptionResult extends AbstractResult<Plaintext> { Plaintext plaintext = get(); return plaintext == null ? null : plaintext.asString(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultEncryptionResult.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultEncryptionResult.java index 26f3f8b6..624849bd 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultEncryptionResult.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultEncryptionResult.java @@ -32,7 +32,6 @@ public class VaultEncryptionResult extends AbstractResult<Ciphertext> { /** * Create {@link VaultEncryptionResult} for a successfully encrypted * {@link Ciphertext} . - * * @param cipherText must not be {@literal null}. */ public VaultEncryptionResult(Ciphertext cipherText) { @@ -41,7 +40,6 @@ public class VaultEncryptionResult extends AbstractResult<Ciphertext> { /** * Create {@link VaultEncryptionResult} for an error during encryption. - * * @param exception must not be {@literal null}. */ public VaultEncryptionResult(VaultException exception) { @@ -53,6 +51,7 @@ public class VaultEncryptionResult extends AbstractResult<Ciphertext> { @Nullable @Override protected Ciphertext get0() { - return cipherText; + return this.cipherText; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHealth.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHealth.java index 4d3f959d..96f73c46 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHealth.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHealth.java @@ -68,4 +68,5 @@ public interface VaultHealth { */ @Nullable String getVersion(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHmacRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHmacRequest.java index 3fe7555f..51c5975e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHmacRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultHmacRequest.java @@ -33,8 +33,7 @@ public class VaultHmacRequest { private final @Nullable Integer keyVersion; - private VaultHmacRequest(Plaintext plaintext, @Nullable String algorithm, - @Nullable Integer keyVersion) { + private VaultHmacRequest(Plaintext plaintext, @Nullable String algorithm, @Nullable Integer keyVersion) { this.algorithm = algorithm; this.plaintext = plaintext; @@ -51,7 +50,6 @@ public class VaultHmacRequest { /** * Create a new {@link VaultHmacRequest} given {@link Plaintext}. Uses the default * signature algorithm. - * * @return a new {@link VaultHmacRequest} for the given {@link Plaintext input}. */ public static VaultHmacRequest create(Plaintext input) { @@ -62,7 +60,7 @@ public class VaultHmacRequest { * @return plain text input used as basis to generate the digest. */ public Plaintext getPlaintext() { - return plaintext; + return this.plaintext; } /** @@ -71,7 +69,7 @@ public class VaultHmacRequest { */ @Nullable public String getAlgorithm() { - return algorithm; + return this.algorithm; } /** @@ -79,7 +77,7 @@ public class VaultHmacRequest { */ @Nullable public Integer getKeyVersion() { - return keyVersion; + return this.keyVersion; } /** @@ -95,7 +93,6 @@ public class VaultHmacRequest { /** * Configure the input to be used to create the digest. - * * @param input base input to create the digest, must not be {@literal null}. * @return {@code this} {@link VaultHmacRequestBuilder}. */ @@ -109,11 +106,9 @@ public class VaultHmacRequest { /** * Configure the algorithm to be used for the operation. - * * @param algorithm Specify the algorithm to be used for the operation. Supported - * algorithms are: {@literal sha2-224}, {@literal sha2-256}, - * {@literal sha2-384}, {@literal sha2-512}. Defaults to {@literal sha2-256} - * if not set. + * algorithms are: {@literal sha2-224}, {@literal sha2-256}, {@literal sha2-384}, + * {@literal sha2-512}. Defaults to {@literal sha2-256} if not set. * @return {@code this} {@link VaultHmacRequestBuilder}. */ public VaultHmacRequestBuilder algorithm(String algorithm) { @@ -126,7 +121,6 @@ public class VaultHmacRequest { /** * Configure the key version to be used for the operation. - * * @param version key version to be used. If not set, uses the latest version. * @return {@code this} {@link VaultHmacRequestBuilder}. */ @@ -139,14 +133,15 @@ public class VaultHmacRequest { /** * Build a new {@link VaultHmacRequest} instance. Requires * {@link #plaintext(Plaintext)} to be configured. - * * @return a new {@link VaultHmacRequest}. */ public VaultHmacRequest build() { - Assert.notNull(plaintext, "Plaintext input must not be null"); + Assert.notNull(this.plaintext, "Plaintext input must not be null"); - return new VaultHmacRequest(plaintext, algorithm, keyVersion); + return new VaultHmacRequest(this.plaintext, this.algorithm, this.keyVersion); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationRequest.java index 1c59b6e8..4c07d3c2 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationRequest.java @@ -38,13 +38,11 @@ public class VaultInitializationRequest { /** * Create a new {@literal VaultInitializationRequest} given {@code secretShares} and * {@code secretThreshold}. - * * @param secretShares number of key shares. * @param secretThreshold number of required keys for unsealing. * @return a new {@link VaultInitializationRequest}. */ - public static VaultInitializationRequest create(int secretShares, - int secretThreshold) { + public static VaultInitializationRequest create(int secretShares, int secretThreshold) { return new VaultInitializationRequest(secretShares, secretThreshold); } @@ -52,14 +50,14 @@ public class VaultInitializationRequest { * @return number of secret shares. */ public int getSecretShares() { - return secretShares; + return this.secretShares; } /** * @return required number of secret shares to unseal Vault. */ public int getSecretThreshold() { - return secretThreshold; + return this.secretThreshold; } } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationResponse.java index b24af0fe..2a4406d6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultInitializationResponse.java @@ -33,4 +33,5 @@ public interface VaultInitializationResponse { * @return the root {@link VaultToken}. */ VaultToken getRootToken(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultMount.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultMount.java index 603bcf62..66adf234 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultMount.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultMount.java @@ -56,8 +56,7 @@ public class VaultMount { */ private final Map<String, String> options; - VaultMount(@JsonProperty("type") String type, - @Nullable @JsonProperty("description") String description, + VaultMount(@JsonProperty("type") String type, @Nullable @JsonProperty("description") String description, @Nullable @JsonProperty("config") Map<String, Object> config, @Nullable @JsonProperty("options") Map<String, String> options) { @@ -69,7 +68,6 @@ public class VaultMount { /** * Create a new {@link VaultMount} given a {@code type}. - * * @param type backend type, must not be empty or {@literal null}. * @return the created {@link VaultMount}. */ @@ -88,7 +86,7 @@ public class VaultMount { * @return the backend type. */ public String getType() { - return type; + return this.type; } /** @@ -96,7 +94,7 @@ public class VaultMount { */ @Nullable public String getDescription() { - return description; + return this.description; } /** @@ -104,7 +102,7 @@ public class VaultMount { */ @Nullable public Map<String, Object> getConfig() { - return config; + return this.config; } /** @@ -113,7 +111,7 @@ public class VaultMount { */ @Nullable public Map<String, String> getOptions() { - return options; + return this.options; } /** @@ -136,7 +134,6 @@ public class VaultMount { /** * Configure the backend type. - * * @param type the backend type, must not be empty or {@literal null}. * @return {@literal this} {@link VaultMountBuilder}. */ @@ -150,7 +147,6 @@ public class VaultMount { /** * Configure a human readable description of this mount. - * * @param description a human readable description of this mount. * @return {@literal this} {@link VaultMountBuilder}. */ @@ -162,7 +158,6 @@ public class VaultMount { /** * Set additional configuration details for this mount. - * * @param config additional configuration details for this mount. * @return {@literal this} {@link VaultMountBuilder}. */ @@ -176,7 +171,6 @@ public class VaultMount { /** * Set mount type specific options for this mount. - * * @param options mount type specific options for this mount. * @return {@literal this} {@link VaultMountBuilder}. * @since 2.2 @@ -192,15 +186,16 @@ public class VaultMount { /** * Build a new {@link VaultMount} instance. Requires {@link #type(String)} to be * configured. - * * @return a new {@link VaultMount}. */ public VaultMount build() { - Assert.notNull(type, "Type must not be null"); - Assert.hasText(type, "Type must not be empty or null"); + Assert.notNull(this.type, "Type must not be null"); + Assert.hasText(this.type, "Type must not be empty or null"); - return new VaultMount(type, description, config, options); + return new VaultMount(this.type, this.description, this.config, this.options); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponse.java index 808e6571..2fae3a2b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponse.java @@ -27,4 +27,5 @@ import java.util.Map; * @author Mark Paluch */ public class VaultResponse extends VaultResponseSupport<Map<String, Object>> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponseSupport.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponseSupport.java index eae8dfbd..08a41434 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponseSupport.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultResponseSupport.java @@ -68,7 +68,7 @@ public class VaultResponseSupport<T> { */ @Nullable public Map<String, Object> getAuth() { - return auth; + return this.auth; } /** @@ -77,8 +77,8 @@ public class VaultResponseSupport<T> { */ public Map<String, Object> getRequiredAuth() { - if (auth != null) { - return auth; + if (this.auth != null) { + return this.auth; } throw new IllegalStateException("Auth field is empty"); @@ -96,7 +96,7 @@ public class VaultResponseSupport<T> { */ @Nullable public T getData() { - return data; + return this.data; } /** @@ -105,8 +105,8 @@ public class VaultResponseSupport<T> { */ public T getRequiredData() { - if (data != null) { - return data; + if (this.data != null) { + return this.data; } throw new IllegalStateException("Data field is empty"); @@ -124,11 +124,10 @@ public class VaultResponseSupport<T> { */ @Nullable public Map<String, Object> getMetadata() { - return metadata; + return this.metadata; } /** - * * @param metadata request metadata. */ public void setMetadata(@Nullable Map<String, Object> metadata) { @@ -136,15 +135,13 @@ public class VaultResponseSupport<T> { } /** - * * @return the lease duration. */ public long getLeaseDuration() { - return leaseDuration; + return this.leaseDuration; } /** - * * @param leaseDuration the lease duration. */ public void setLeaseDuration(long leaseDuration) { @@ -152,16 +149,14 @@ public class VaultResponseSupport<T> { } /** - * * @return the lease Id. */ @Nullable public String getLeaseId() { - return leaseId; + return this.leaseId; } /** - * * @param leaseId the lease Id. */ public void setLeaseId(@Nullable String leaseId) { @@ -169,15 +164,13 @@ public class VaultResponseSupport<T> { } /** - * * @return {@literal true} if the lease is renewable. */ public boolean isRenewable() { - return renewable; + return this.renewable; } /** - * * @param renewable {@literal true} if the lease is renewable. */ public void setRenewable(boolean renewable) { @@ -185,16 +178,14 @@ public class VaultResponseSupport<T> { } /** - * * @return response wrapping details. */ @Nullable public Map<String, String> getWrapInfo() { - return wrapInfo; + return this.wrapInfo; } /** - * * @param wrapInfo response wrapping details. */ public void setWrapInfo(@Nullable Map<String, String> wrapInfo) { @@ -202,16 +193,14 @@ public class VaultResponseSupport<T> { } /** - * * @return the request Id. */ @Nullable public String getRequestId() { - return requestId; + return this.requestId; } /** - * * @param requestId the request Id. */ public void setRequestId(@Nullable String requestId) { @@ -219,19 +208,18 @@ public class VaultResponseSupport<T> { } /** - * * @return the warnings. */ @Nullable public List<String> getWarnings() { - return warnings; + return this.warnings; } /** - * * @param warnings the warnings. */ public void setWarnings(@Nullable List<String> warnings) { this.warnings = warnings; } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignCertificateRequestResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignCertificateRequestResponse.java index cff7154b..7795e680 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignCertificateRequestResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignCertificateRequestResponse.java @@ -20,6 +20,6 @@ package org.springframework.vault.support; * * @author Mark Paluch */ -public class VaultSignCertificateRequestResponse - extends VaultResponseSupport<Certificate> { +public class VaultSignCertificateRequestResponse extends VaultResponseSupport<Certificate> { + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignRequest.java index 01870afe..616c8cea 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignRequest.java @@ -47,7 +47,6 @@ public class VaultSignRequest { /** * Create a new {@link VaultSignRequest} given {@link Plaintext}. Uses the default * algorithm. - * * @return a new {@link VaultSignRequest} for the given {@link Plaintext input}. */ public static VaultSignRequest create(Plaintext input) { @@ -58,7 +57,7 @@ public class VaultSignRequest { * @return plain text input used as basis to generate the signature. */ public Plaintext getPlaintext() { - return plaintext; + return this.plaintext; } /** @@ -67,7 +66,7 @@ public class VaultSignRequest { */ @Nullable public String getAlgorithm() { - return algorithm; + return this.algorithm; } /** @@ -81,7 +80,6 @@ public class VaultSignRequest { /** * Configure the input to be used to create the signature. - * * @param input base input to create the signature, must not be {@literal null}. * @return {@code this} {@link VaultSignRequestBuilder}. */ @@ -95,11 +93,9 @@ public class VaultSignRequest { /** * Configure the algorithm to be used for the operation. - * * @param algorithm Specify the algorithm to be used for the operation. Supported - * algorithms are: {@literal sha2-224}, {@literal sha2-256}, - * {@literal sha2-384}, {@literal sha2-512}. Defaults to {@literal sha2-256} - * if not set. + * algorithms are: {@literal sha2-224}, {@literal sha2-256}, {@literal sha2-384}, + * {@literal sha2-512}. Defaults to {@literal sha2-256} if not set. * @return {@code this} {@link VaultSignRequestBuilder}. */ public VaultSignRequestBuilder algorithm(String algorithm) { @@ -113,14 +109,15 @@ public class VaultSignRequest { /** * Build a new {@link VaultSignRequest} instance. Requires * {@link #plaintext(Plaintext)} to be configured. - * * @return a new {@link VaultSignRequest}. */ public VaultSignRequest build() { - Assert.notNull(plaintext, "Plaintext input must not be null"); + Assert.notNull(this.plaintext, "Plaintext input must not be null"); - return new VaultSignRequest(plaintext, algorithm); + return new VaultSignRequest(this.plaintext, this.algorithm); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignatureVerificationRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignatureVerificationRequest.java index 3db21e39..1132ec7b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignatureVerificationRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultSignatureVerificationRequest.java @@ -35,8 +35,7 @@ public class VaultSignatureVerificationRequest { private final @Nullable String algorithm; - private VaultSignatureVerificationRequest(Plaintext plaintext, - @Nullable Signature signature, @Nullable Hmac hmac, + private VaultSignatureVerificationRequest(Plaintext plaintext, @Nullable Signature signature, @Nullable Hmac hmac, @Nullable String algorithm) { this.plaintext = plaintext; @@ -55,28 +54,24 @@ public class VaultSignatureVerificationRequest { /** * Create a new {@link VaultSignatureVerificationRequest} given {@link Plaintext} and * {@link Signature}. - * * @param plaintext the plaintext, must not be {@literal null}. * @param signature the signature, must not be {@literal null}. * @return a new {@link VaultSignatureVerificationRequest} for {@link Plaintext} and * {@link Signature}. */ - public static VaultSignatureVerificationRequest create(Plaintext plaintext, - Signature signature) { + public static VaultSignatureVerificationRequest create(Plaintext plaintext, Signature signature) { return builder().plaintext(plaintext).signature(signature).build(); } /** * Create a new {@link VaultSignatureVerificationRequest} given {@link Plaintext} and * {@link Hmac}. - * * @param plaintext the plaintext, must not be {@literal null}. * @param hmac the hmac, must not be {@literal null}. * @return a new {@link VaultSignatureVerificationRequest} for {@link Plaintext} and * {@link Hmac}. */ - public static VaultSignatureVerificationRequest create(Plaintext plaintext, - Hmac hmac) { + public static VaultSignatureVerificationRequest create(Plaintext plaintext, Hmac hmac) { return builder().plaintext(plaintext).hmac(hmac).build(); } @@ -84,7 +79,7 @@ public class VaultSignatureVerificationRequest { * @return plain text input used as basis to verify the signature. */ public Plaintext getPlaintext() { - return plaintext; + return this.plaintext; } /** @@ -93,7 +88,7 @@ public class VaultSignatureVerificationRequest { */ @Nullable public Signature getSignature() { - return signature; + return this.signature; } /** @@ -102,7 +97,7 @@ public class VaultSignatureVerificationRequest { */ @Nullable public Hmac getHmac() { - return hmac; + return this.hmac; } /** @@ -111,7 +106,7 @@ public class VaultSignatureVerificationRequest { */ @Nullable public String getAlgorithm() { - return algorithm; + return this.algorithm; } /** @@ -129,7 +124,6 @@ public class VaultSignatureVerificationRequest { /** * Configure the {@link Plaintext} input to be used to verify the signature. - * * @param input base input, must not be {@literal null}. * @return {@code this} {@link VaultSignatureVerificationRequestBuilder}. */ @@ -145,7 +139,6 @@ public class VaultSignatureVerificationRequest { * Configure the {@link Signature} to be verified. Signature verification requires * either a {@link Signature} or a {@link #hmac(Hmac)} to be configured. Clears * any previously configured {@link #hmac(Hmac)}. - * * @param signature to be verified, must not be {@literal null}. * @return {@code this} {@link VaultSignatureVerificationRequestBuilder}. */ @@ -162,7 +155,6 @@ public class VaultSignatureVerificationRequest { * Configure the {@link Hmac} to be verified. Signature verification requires * either a {@link Hmac} or a {@link #signature(Signature)} to be configured. * Clears any previously configured {@link Signature}. - * * @param hmac to be verified, must not be {@literal null}. * @return {@code this} {@link VaultSignatureVerificationRequestBuilder}. */ @@ -177,11 +169,9 @@ public class VaultSignatureVerificationRequest { /** * Configure the algorithm to be used for the operation. - * * @param algorithm Specify the algorithm to be used for the operation. Supported - * algorithms are: {@literal sha2-224}, {@literal sha2-256}, - * {@literal sha2-384}, {@literal sha2-512}. Defaults to {@literal sha2-256} - * if not set. + * algorithms are: {@literal sha2-224}, {@literal sha2-256}, {@literal sha2-384}, + * {@literal sha2-512}. Defaults to {@literal sha2-256} if not set. * @return {@code this} {@link VaultSignatureVerificationRequestBuilder}. */ public VaultSignatureVerificationRequestBuilder algorithm(String algorithm) { @@ -196,17 +186,16 @@ public class VaultSignatureVerificationRequest { * Build a new {@link VaultSignatureVerificationRequest} instance. Requires * {@link #plaintext(Plaintext)} and one of {@link #hmac(Hmac)}, * {@link #signature(Signature)} to be configured. - * * @return a new {@link VaultHmacRequest}. */ public VaultSignatureVerificationRequest build() { - Assert.notNull(input, "Plaintext input must not be null"); - Assert.isTrue(hmac != null || signature != null, - "Either Signature or Hmac must not be null"); + Assert.notNull(this.input, "Plaintext input must not be null"); + Assert.isTrue(this.hmac != null || this.signature != null, "Either Signature or Hmac must not be null"); - return new VaultSignatureVerificationRequest(input, signature, hmac, - algorithm); + return new VaultSignatureVerificationRequest(this.input, this.signature, this.hmac, this.algorithm); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultToken.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultToken.java index f56cb302..8465f043 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultToken.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultToken.java @@ -39,7 +39,6 @@ public class VaultToken { /** * Create a new {@link VaultToken}. - * * @param token must not be empty or {@literal null}. * @return the created {@link VaultToken} */ @@ -52,7 +51,6 @@ public class VaultToken { /** * Create a new {@link VaultToken}. - * * @param token must not be empty or {@literal null}. * @return the created {@link VaultToken} * @since 1.1 @@ -65,7 +63,7 @@ public class VaultToken { * @return the token value. */ public String getToken() { - return new String(token); + return new String(this.token); } /** @@ -73,7 +71,7 @@ public class VaultToken { * @since 1.1 */ public char[] toCharArray() { - return token; + return this.token; } @Override @@ -83,15 +81,16 @@ public class VaultToken { if (!(o instanceof VaultToken)) return false; VaultToken that = (VaultToken) o; - return Arrays.equals(token, that.token); + return Arrays.equals(this.token, that.token); } @Override public int hashCode() { - return Arrays.hashCode(token); + return Arrays.hashCode(this.token); } public String toString() { return getClass().getSimpleName(); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenRequest.java index bc882f2f..e39636c9 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenRequest.java @@ -63,9 +63,8 @@ public class VaultTokenRequest { @JsonProperty("num_uses") private final int numUses; - VaultTokenRequest(@Nullable String id, List<String> policies, - Map<String, String> meta, boolean noParent, boolean noDefaultPolicy, - boolean renewable, @Nullable String ttl, @Nullable String explicitMaxTtl, + VaultTokenRequest(@Nullable String id, List<String> policies, Map<String, String> meta, boolean noParent, + boolean noDefaultPolicy, boolean renewable, @Nullable String ttl, @Nullable String explicitMaxTtl, String displayName, int numUses) { this.id = id; @@ -88,20 +87,18 @@ public class VaultTokenRequest { } /** - * * @return Id of the client token. */ @Nullable public String getId() { - return id; + return this.id; } /** - * * @return policies for the token. */ public List<String> getPolicies() { - return policies; + return this.policies; } /** @@ -109,28 +106,28 @@ public class VaultTokenRequest { * backends. */ public Map<String, String> getMeta() { - return meta; + return this.meta; } /** * @return {@literal true} if the token should not have the parent. */ public boolean getNoParent() { - return noParent; + return this.noParent; } /** * @return {@literal true} if the default policy should not be be applied. */ public boolean getNoDefaultPolicy() { - return noDefaultPolicy; + return this.noDefaultPolicy; } /** * @return {@literal true} if then the token should be renewable. */ public boolean getRenewable() { - return renewable; + return this.renewable; } /** @@ -138,7 +135,7 @@ public class VaultTokenRequest { */ @Nullable public String getTtl() { - return ttl; + return this.ttl; } /** @@ -146,21 +143,21 @@ public class VaultTokenRequest { */ @Nullable public String getExplicitMaxTtl() { - return explicitMaxTtl; + return this.explicitMaxTtl; } /** * @return the display name. */ public String getDisplayName() { - return displayName; + return this.displayName; } /** * @return the number of allowed token uses. */ public int getNumUses() { - return numUses; + return this.numUses; } /** @@ -197,7 +194,6 @@ public class VaultTokenRequest { /** * Configure a the Id of the client token. Can only be specified by a root token. * Otherwise, the token Id is a randomly generated UUID. - * * @param id the token Id. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -208,7 +204,6 @@ public class VaultTokenRequest { /** * Configure policies. Replaces previously configured policies. - * * @param policies must not be {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -222,7 +217,6 @@ public class VaultTokenRequest { /** * Add a policy. - * * @param policy must not be empty or {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -236,7 +230,6 @@ public class VaultTokenRequest { /** * Configure meta. Replaces previously meta. - * * @param meta must not be {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -251,7 +244,6 @@ public class VaultTokenRequest { /** * Configure the token to not have the parent token of the caller. This creates a * token with no parent. Requires a root caller. - * * @return {@code this} {@link VaultTokenRequestBuilder}. */ public VaultTokenRequestBuilder noParent() { @@ -261,7 +253,6 @@ public class VaultTokenRequest { /** * Configure the token to not have the parent token of the caller. This creates a * token with no parent. Requires a root caller. - * * @param noParent {@literal true} to not have the parent token of the caller. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -273,7 +264,6 @@ public class VaultTokenRequest { /** * Omit the default policy in the token's policy set - * * @return {@code this} {@link VaultTokenRequestBuilder}. */ public VaultTokenRequestBuilder noDefaultPolicy() { @@ -282,9 +272,8 @@ public class VaultTokenRequest { /** * Configure whether the default policy should be part of the token's policy set. - * * @param noDefaultPolicy {@literal true} to omit the default policy in the - * token's policy set. + * token's policy set. * @return {@code this} {@link VaultTokenRequestBuilder}. */ public VaultTokenRequestBuilder noDefaultPolicy(boolean noDefaultPolicy) { @@ -294,7 +283,6 @@ public class VaultTokenRequest { /** * Enable TTL extension/renewal for the token. - * * @return {@code this} {@link VaultTokenRequestBuilder}. */ public VaultTokenRequestBuilder renewable() { @@ -303,10 +291,9 @@ public class VaultTokenRequest { /** * Configure TTL extension/renewal for the token. - * * @param renewable {@literal false} to disable the ability of the token to be - * renewed past its initial TTL. {@literal true}, or omitting this option, - * will allow the token to be renewable up to the system/mount maximum TTL. + * renewed past its initial TTL. {@literal true}, or omitting this option, will + * allow the token to be renewable up to the system/mount maximum TTL. * @return {@code this} {@link VaultTokenRequestBuilder}. */ public VaultTokenRequestBuilder renewable(boolean renewable) { @@ -317,7 +304,6 @@ public class VaultTokenRequest { /** * Configure a TTL (seconds) for the token. - * * @param ttl the time to live in seconds, must not be negative. * @return {@code this} {@link VaultTokenRequestBuilder}. * @deprecated since 2.0, use {@link #ttl(Duration)} for time unit safety. @@ -329,7 +315,6 @@ public class VaultTokenRequest { /** * Configure a TTL (seconds) for the token. - * * @param ttl the time to live, must not be negative. * @param timeUnit the time to live time unit, must not be {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. @@ -346,7 +331,6 @@ public class VaultTokenRequest { /** * Configure a TTL for the token using * {@link java.time.temporal.ChronoUnit#SECONDS} resolution. - * * @param ttl the time to live, must not be {@literal null} or negative. * @return {@code this} {@link VaultTokenRequestBuilder}. * @since 2.0 @@ -365,7 +349,6 @@ public class VaultTokenRequest { * TTL cannot be changed later, and unlike with normal tokens, updates to the * system/mount max TTL value will have no effect at renewal time - the token will * never be able to be renewed or used past the value set at issue time. - * * @param explicitMaxTtl the time to live in seconds, must not be negative. * @return {@code this} {@link VaultTokenRequestBuilder}. * @deprecated since 2.0, use {@link #explicitMaxTtl(Duration)} for time unit @@ -381,19 +364,16 @@ public class VaultTokenRequest { * be changed later, and unlike with normal tokens, updates to the system/mount * max TTL value will have no effect at renewal time - the token will never be * able to be renewed or used past the value set at issue time. - * * @param explicitMaxTtl the time to live, must not be negative. * @param timeUnit the time to live, must not be {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. */ - public VaultTokenRequestBuilder explicitMaxTtl(long explicitMaxTtl, - TimeUnit timeUnit) { + public VaultTokenRequestBuilder explicitMaxTtl(long explicitMaxTtl, TimeUnit timeUnit) { Assert.isTrue(explicitMaxTtl >= 0, "TTL must not be negative"); Assert.notNull(timeUnit, "TimeUnit must not be null"); - this.explicitMaxTtl = String.format("%ss", - timeUnit.toSeconds(explicitMaxTtl)); + this.explicitMaxTtl = String.format("%ss", timeUnit.toSeconds(explicitMaxTtl)); return this; } @@ -402,9 +382,8 @@ public class VaultTokenRequest { * be changed later, and unlike with normal tokens, updates to the system/mount * max TTL value will have no effect at renewal time - the token will never be * able to be renewed or used past the value set at issue time. - * * @param explicitMaxTtl the time to live, must not be {@literal null} or - * negative. + * negative. * @return {@code this} {@link VaultTokenRequestBuilder}. * @since 2.0 */ @@ -421,7 +400,6 @@ public class VaultTokenRequest { * Configure the maximum uses for the token. This can be used to create a * one-time-token or limited use token. Defaults to {@literal 0}, which has no * limit to the number of uses. - * * @param numUses number of uses, must not be negative. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -435,7 +413,6 @@ public class VaultTokenRequest { /** * Configure a display name for the token, defaults to "token". - * * @param displayName must not be empty or {@literal null}. * @return {@code this} {@link VaultTokenRequestBuilder}. */ @@ -449,7 +426,6 @@ public class VaultTokenRequest { /** * Build a new {@link VaultTokenRequest} instance. - * * @return a new {@link VaultCertificateRequest}. */ public VaultTokenRequest build() { @@ -475,8 +451,8 @@ public class VaultTokenRequest { meta = Collections.unmodifiableMap(new LinkedHashMap<>(this.meta)); } - return new VaultTokenRequest(id, policies, meta, noParent, noDefaultPolicy, - renewable, ttl, explicitMaxTtl, displayName, numUses); + return new VaultTokenRequest(this.id, policies, meta, this.noParent, this.noDefaultPolicy, this.renewable, + this.ttl, this.explicitMaxTtl, this.displayName, this.numUses); } private static <E> List<E> toList(Iterable<E> iter) { @@ -488,5 +464,7 @@ public class VaultTokenRequest { return list; } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenResponse.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenResponse.java index 4d765b2f..85122e9b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenResponse.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTokenResponse.java @@ -24,10 +24,10 @@ public class VaultTokenResponse extends VaultResponse { /** * Return a {@link VaultToken} from the {@link VaultResponse}. - * * @return the {@link VaultToken}. */ public VaultToken getToken() { return VaultToken.of((String) getRequiredAuth().get("client_token")); } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitContext.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitContext.java index 02a98ad5..5466f56f 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitContext.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitContext.java @@ -30,8 +30,7 @@ public class VaultTransitContext { * Empty (default) {@link VaultTransitContext} without a {@literal context} and * {@literal nonce}. */ - private static final VaultTransitContext EMPTY = new VaultTransitContext(new byte[0], - new byte[0]); + private static final VaultTransitContext EMPTY = new VaultTransitContext(new byte[0], new byte[0]); private final byte[] context; @@ -58,7 +57,6 @@ public class VaultTransitContext { /** * Create a {@link VaultTransitContext} given {@code context} bytes. - * * @param context context bytes, must not be {@literal null}. * @return a {@link VaultTransitContext} for {@code context}. * @since 2.0 @@ -69,7 +67,6 @@ public class VaultTransitContext { /** * Create a {@link VaultTransitContext} given {@code nonce} bytes. - * * @param nonce nonce bytes, must not be {@literal null}. * @return a {@link VaultTransitContext} for {@code nonce}. * @since 2.0 @@ -82,14 +79,14 @@ public class VaultTransitContext { * @return the key derivation context. */ public byte[] getContext() { - return context; + return this.context; } /** * @return the */ public byte[] getNonce() { - return nonce; + return this.nonce; } @Override @@ -99,13 +96,13 @@ public class VaultTransitContext { if (!(o instanceof VaultTransitContext)) return false; VaultTransitContext that = (VaultTransitContext) o; - return Arrays.equals(context, that.context) && Arrays.equals(nonce, that.nonce); + return Arrays.equals(this.context, that.context) && Arrays.equals(this.nonce, that.nonce); } @Override public int hashCode() { - int result = Arrays.hashCode(context); - result = 31 * result + Arrays.hashCode(nonce); + int result = Arrays.hashCode(this.context); + result = 31 * result + Arrays.hashCode(this.nonce); return result; } @@ -115,6 +112,7 @@ public class VaultTransitContext { public static class VaultTransitRequestBuilder { private byte[] context = new byte[0]; + private byte[] nonce = new byte[0]; VaultTransitRequestBuilder() { @@ -122,9 +120,8 @@ public class VaultTransitContext { /** * Configure a key derivation context for the {@code transit} operation. - * * @param context key derivation context, provided as a binary data. Must be - * provided if derivation is enabled. + * provided if derivation is enabled. * @return {@code this} {@link VaultTransitRequestBuilder}. */ public VaultTransitRequestBuilder context(byte[] context) { @@ -139,10 +136,9 @@ public class VaultTransitContext { * Configure the nonce value for a {@code transit} operation. Must be provided if * convergent encryption is enabled for this key and the key was generated with * Vault 0.6.1. Not required for keys created in 0.6.2+. - * * @param nonce value must be exactly 96 bits (12 bytes) long and the user must - * ensure that for any given context (and thus, any given encryption key) this - * nonce value is never reused + * ensure that for any given context (and thus, any given encryption key) this + * nonce value is never reused * @return {@code this} {@link VaultTransitRequestBuilder}. */ public VaultTransitRequestBuilder nonce(byte[] nonce) { @@ -155,11 +151,12 @@ public class VaultTransitContext { /** * Build a new {@link VaultTransitContext} instance. - * * @return a new {@link VaultTransitContext}. */ public VaultTransitContext build() { - return new VaultTransitContext(context, nonce); + return new VaultTransitContext(this.context, this.nonce); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKey.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKey.java index 5d932d20..b30dedf6 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKey.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKey.java @@ -95,4 +95,5 @@ public interface VaultTransitKey { * @since 1.1 */ boolean supportsSigning(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyConfiguration.java index a5ff08f2..41e3147b 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyConfiguration.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyConfiguration.java @@ -38,8 +38,7 @@ public class VaultTransitKeyConfiguration { @Nullable private final Integer minEncryptionVersion; - private VaultTransitKeyConfiguration(@Nullable Boolean deletionAllowed, - @Nullable Integer minDecryptionVersion, + private VaultTransitKeyConfiguration(@Nullable Boolean deletionAllowed, @Nullable Integer minDecryptionVersion, @Nullable Integer minEncryptionVersion) { this.deletionAllowed = deletionAllowed; @@ -59,7 +58,7 @@ public class VaultTransitKeyConfiguration { */ @Nullable public Boolean getDeletionAllowed() { - return deletionAllowed; + return this.deletionAllowed; } /** @@ -68,7 +67,7 @@ public class VaultTransitKeyConfiguration { */ @Nullable public Integer getMinDecryptionVersion() { - return minDecryptionVersion; + return this.minDecryptionVersion; } /** @@ -78,7 +77,7 @@ public class VaultTransitKeyConfiguration { */ @Nullable public Integer getMinEncryptionVersion() { - return minEncryptionVersion; + return this.minEncryptionVersion; } /** @@ -100,12 +99,10 @@ public class VaultTransitKeyConfiguration { /** * Set whether key deletion is allowed. - * * @param deletionAllowed {@literal true} if key deletion should be allowed. * @return {@code this} {@link VaultTransitKeyConfigurationBuilder}. */ - public VaultTransitKeyConfigurationBuilder deletionAllowed( - boolean deletionAllowed) { + public VaultTransitKeyConfigurationBuilder deletionAllowed(boolean deletionAllowed) { this.deletionAllowed = deletionAllowed; return this; } @@ -117,13 +114,11 @@ public class VaultTransitKeyConfiguration { * value controls the minimum version of signature that can be verified against. * For HMACs, this controls the minimum version of a key allowed to be used as the * key for verification. - * * @param minDecryptionVersion key version. * @return {@code this} {@link VaultTransitKeyConfigurationBuilder}. * @since 1.1 */ - public VaultTransitKeyConfigurationBuilder minDecryptionVersion( - int minDecryptionVersion) { + public VaultTransitKeyConfigurationBuilder minDecryptionVersion(int minDecryptionVersion) { this.minDecryptionVersion = minDecryptionVersion; return this; } @@ -132,25 +127,24 @@ public class VaultTransitKeyConfiguration { * Specifies the minimum version of the key that can be used to encrypt plaintext, * sign payloads, or generate HMACs. Must be 0 (which will use the latest version) * or a value greater or equal to {@link #minDecryptionVersion(int)}. - * * @param minEncryptionVersion key version. * @return {@code this} {@link VaultTransitKeyConfigurationBuilder}. * @since 1.1 */ - public VaultTransitKeyConfigurationBuilder minEncryptionVersion( - int minEncryptionVersion) { + public VaultTransitKeyConfigurationBuilder minEncryptionVersion(int minEncryptionVersion) { this.minEncryptionVersion = minEncryptionVersion; return this; } /** * Build a new {@link VaultTransitKeyConfiguration} instance. - * * @return a new {@link VaultTransitKeyConfiguration}. */ public VaultTransitKeyConfiguration build() { - return new VaultTransitKeyConfiguration(deletionAllowed, minDecryptionVersion, - minEncryptionVersion); + return new VaultTransitKeyConfiguration(this.deletionAllowed, this.minDecryptionVersion, + this.minEncryptionVersion); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyCreationRequest.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyCreationRequest.java index fa54d7a7..0dbeebf8 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyCreationRequest.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultTransitKeyCreationRequest.java @@ -37,8 +37,8 @@ public class VaultTransitKeyCreationRequest { private final boolean exportable; - private VaultTransitKeyCreationRequest(boolean derived, String type, - boolean convergentEncryption, boolean exportable) { + private VaultTransitKeyCreationRequest(boolean derived, String type, boolean convergentEncryption, + boolean exportable) { this.derived = derived; this.type = type; this.convergentEncryption = convergentEncryption; @@ -65,32 +65,28 @@ public class VaultTransitKeyCreationRequest { } /** - * * @return {@literal true} if key derivation MUST be used. */ public boolean getDerived() { - return derived; + return this.derived; } /** - * * @return {@literal true} if convergent encryption should be used (where the same * plaintext creates the same cipher text). */ public boolean getConvergentEncryption() { - return convergentEncryption; + return this.convergentEncryption; } /** - * * @return the key type. */ public String getType() { - return type; + return this.type; } /** - * * @return {@literal true} if key MUST be exportable. */ public boolean getExportable() { @@ -103,8 +99,11 @@ public class VaultTransitKeyCreationRequest { public static class VaultTransitKeyCreationRequestBuilder { private boolean derived; + private String type = "aes256-gcm96"; + private boolean convergentEncryption; + private boolean exportable; VaultTransitKeyCreationRequestBuilder() { @@ -112,7 +111,6 @@ public class VaultTransitKeyCreationRequest { /** * Configure the key type. - * * @param type the type of key to create, must not be empty or {@literal null}. * @return {@code this} {@link VaultTransitKeyCreationRequestBuilder}. */ @@ -126,10 +124,9 @@ public class VaultTransitKeyCreationRequest { /** * Configure key derivation. - * * @param derived {@literal true} if key derivation MUST be used. If enabled, all - * encrypt/decrypt requests to this named key must provide a context which is - * used for key derivation. Defaults to {@literal false}. + * encrypt/decrypt requests to this named key must provide a context which is used + * for key derivation. Defaults to {@literal false}. * @return {@code this} {@link VaultTransitKeyCreationRequestBuilder}. */ public VaultTransitKeyCreationRequestBuilder derived(boolean derived) { @@ -141,13 +138,11 @@ public class VaultTransitKeyCreationRequest { /** * Configure convergent encryption where the same plaintext creates the same * ciphertext. Requires {@link #derived(boolean)} to be {@literal true}. - * * @param convergentEncryption {@literal true} the same plaintext creates the same - * ciphertext. Defaults to {@literal false}. + * ciphertext. Defaults to {@literal false}. * @return {@code this} {@link VaultTransitKeyCreationRequestBuilder}. */ - public VaultTransitKeyCreationRequestBuilder convergentEncryption( - boolean convergentEncryption) { + public VaultTransitKeyCreationRequestBuilder convergentEncryption(boolean convergentEncryption) { this.convergentEncryption = convergentEncryption; return this; @@ -155,9 +150,8 @@ public class VaultTransitKeyCreationRequest { /** * Configure if the raw key is exportable. - * * @param exportable {@literal true} the raw key is exportable. Defaults to - * {@literal false}. + * {@literal false}. * @return {@code this} {@link VaultTransitKeyCreationRequestBuilder}. */ public VaultTransitKeyCreationRequestBuilder exportable(boolean exportable) { @@ -169,15 +163,16 @@ public class VaultTransitKeyCreationRequest { /** * Build a new {@link VaultTransitKeyCreationRequest} instance. Requires * {@link #type(String)} to be configured. - * * @return a new {@link VaultTransitKeyCreationRequest}. */ public VaultTransitKeyCreationRequest build() { - Assert.hasText(type, "Type must not be empty"); + Assert.hasText(this.type, "Type must not be empty"); - return new VaultTransitKeyCreationRequest(derived, type, convergentEncryption, - exportable); + return new VaultTransitKeyCreationRequest(this.derived, this.type, this.convergentEncryption, + this.exportable); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultUnsealStatus.java b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultUnsealStatus.java index c6e011c1..9caab80e 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/VaultUnsealStatus.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/VaultUnsealStatus.java @@ -41,4 +41,5 @@ public interface VaultUnsealStatus { * @return number of remaining required keyshares to unseal Vault. */ int getProgress(); + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/Versioned.java b/spring-vault-core/src/main/java/org/springframework/vault/support/Versioned.java index bb6e28c3..4b40b6ad 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/Versioned.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/Versioned.java @@ -72,7 +72,6 @@ public class Versioned<T> { /** * Create a {@link Version#unversioned() unversioned} given secret. - * * @param secret must not be {@literal null}. * @return the {@link Versioned} object for {@code secret} */ @@ -87,7 +86,6 @@ public class Versioned<T> { * Create a versioned secret object given {@code secret} and {@link Version}. * Versioned secret may contain no actual data as they can be in a deleted/destroyed * state. - * * @param secret can be {@literal null}. * @param version must not be {@literal null}. * @return the {@link Versioned} object for {@code secret} and {@code Version}. @@ -103,7 +101,6 @@ public class Versioned<T> { * Create a versioned secret object given {@code secret} and {@link Metadata}. * Versioned secret may contain no actual data as they can be in a deleted/destroyed * state. - * * @param secret can be {@literal null}. * @param metadata must not be {@literal null}. * @return the {@link Versioned} object for {@code secret} and {@link Metadata}. @@ -119,7 +116,7 @@ public class Versioned<T> { * @return the {@link Version} associated with this {@link Versioned} object. */ public Version getVersion() { - return version; + return this.version; } /** @@ -127,18 +124,17 @@ public class Versioned<T> { * otherwise {@code false} */ public boolean hasMetadata() { - return metadata != null; + return this.metadata != null; } @Nullable public Metadata getMetadata() { - return metadata; + return this.metadata; } /** * Returns the required {@link Metadata} for this versioned object. Throws * {@link IllegalStateException} if no metadata is associated. - * * @return the non-null {@link Metadata} held by this for this versioned object. * @throws IllegalStateException if no metadata is present. */ @@ -158,7 +154,7 @@ public class Versioned<T> { * {@code false}, of the version is deleted or destroyed. */ public boolean hasData() { - return data != null; + return this.data != null; } /** @@ -167,13 +163,12 @@ public class Versioned<T> { */ @Nullable public T getData() { - return data; + return this.data; } /** * Returns the required data for this versioned object. Throws * {@link IllegalStateException} if no data is associated. - * * @return the non-null value held by this for this versioned object. * @throws IllegalStateException if no data is present. */ @@ -190,13 +185,12 @@ public class Versioned<T> { /** * Convert the data element of this versioned object to an {@link Optional}. - * * @return {@link Optional#of(Object) Optional} holding the actual value of this * versioned object if {@link #hasData() data is present}, {@link Optional#empty()} if * no data is associated. */ public Optional<T> toOptional() { - return Optional.ofNullable(data); + return Optional.ofNullable(this.data); } @Override @@ -206,15 +200,14 @@ public class Versioned<T> { if (!(o instanceof Versioned)) return false; Versioned<?> versioned = (Versioned<?>) o; - return Objects.equals(data, versioned.data) - && Objects.equals(version, versioned.version) - && Objects.equals(metadata, versioned.metadata); + return Objects.equals(this.data, versioned.data) && Objects.equals(this.version, versioned.version) + && Objects.equals(this.metadata, versioned.metadata); } @Override public int hashCode() { - return Objects.hash(data, version, metadata); + return Objects.hash(this.data, this.version, this.metadata); } /** @@ -230,8 +223,7 @@ public class Versioned<T> { private final Version version; - private Metadata(Instant createdAt, @Nullable Instant deletedAt, - boolean destroyed, Version version) { + private Metadata(Instant createdAt, @Nullable Instant deletedAt, boolean destroyed, Version version) { this.createdAt = createdAt; this.deletedAt = deletedAt; this.destroyed = destroyed; @@ -240,7 +232,6 @@ public class Versioned<T> { /** * Creates a new {@link MetadataBuilder} to build {@link Metadata} objects. - * * @return a new {@link MetadataBuilder} to build {@link Metadata} objects. */ public static MetadataBuilder builder() { @@ -251,14 +242,14 @@ public class Versioned<T> { * @return {@link Instant} at which the version was created. */ public Instant getCreatedAt() { - return createdAt; + return this.createdAt; } /** * @return {@literal true} if the version was deleted. */ public boolean isDeleted() { - return deletedAt != null; + return this.deletedAt != null; } /** @@ -267,29 +258,28 @@ public class Versioned<T> { */ @Nullable public Instant getDeletedAt() { - return deletedAt; + return this.deletedAt; } /** * @return the version number. */ public Version getVersion() { - return version; + return this.version; } /** * @return {@literal true} if the version was destroyed. */ public boolean isDestroyed() { - return destroyed; + return this.destroyed; } @Override public String toString() { - return getClass().getSimpleName() + " [createdAt=" + createdAt - + ", deletedAt=" + deletedAt + ", destroyed=" + destroyed - + ", version=" + version + ']'; + return getClass().getSimpleName() + " [createdAt=" + this.createdAt + ", deletedAt=" + this.deletedAt + + ", destroyed=" + this.destroyed + ", version=" + this.version + ']'; } /** @@ -310,9 +300,8 @@ public class Versioned<T> { /** * Configure a created at {@link Instant}. - * * @param createdAt timestamp at which the version was created, must not be - * {@literal null}. + * {@literal null}. * @return {@code this} {@link MetadataBuilder}. */ public MetadataBuilder createdAt(Instant createdAt) { @@ -325,9 +314,8 @@ public class Versioned<T> { /** * Configure a deleted at {@link Instant}. - * * @param deletedAt timestamp at which the version was deleted, must not be - * {@literal null}. + * {@literal null}. * @return {@code this} {@link MetadataBuilder}. */ public MetadataBuilder deletedAt(Instant deletedAt) { @@ -340,7 +328,6 @@ public class Versioned<T> { /** * Configure the version was destroyed. - * * @return {@code this} {@link MetadataBuilder}. */ public MetadataBuilder destroyed() { @@ -349,7 +336,6 @@ public class Versioned<T> { /** * Configure the version was destroyed. - * * @param destroyed * @return {@code this} {@link MetadataBuilder}. */ @@ -360,7 +346,6 @@ public class Versioned<T> { /** * Configure the {@link Version}. - * * @param version must not be {@literal null}. * @return {@code this} {@link MetadataBuilder}. */ @@ -373,19 +358,21 @@ public class Versioned<T> { } /** - * Build the {@link Versioned.Metadata} object. Requires {@link #createdAt(Instant)} and - * {@link #version(Versioned.Version)} to be set. - * + * Build the {@link Versioned.Metadata} object. Requires + * {@link #createdAt(Instant)} and {@link #version(Versioned.Version)} to be + * set. * @return the {@link Versioned.Metadata} object. */ public Metadata build() { - Assert.notNull(createdAt, "CreatedAt must not be null"); - Assert.notNull(version, "Version must not be null"); + Assert.notNull(this.createdAt, "CreatedAt must not be null"); + Assert.notNull(this.version, "Version must not be null"); - return new Metadata(createdAt, deletedAt, destroyed, version); + return new Metadata(this.createdAt, this.deletedAt, this.destroyed, this.version); } + } + } /** @@ -417,7 +404,6 @@ public class Versioned<T> { /** * Create a {@link Version} given a {@code versionNumber}. - * * @param versionNumber the version number. * @return the {@link Version} for {@code versionNumber}. */ @@ -438,14 +424,14 @@ public class Versioned<T> { * latest versions in the context of particular versioning operations. */ public boolean isVersioned() { - return version > 0; + return this.version > 0; } /** * @return the version number. */ public int getVersion() { - return version; + return this.version; } @Override @@ -455,17 +441,19 @@ public class Versioned<T> { if (!(o instanceof Version)) return false; Version version1 = (Version) o; - return version == version1.version; + return this.version == version1.version; } @Override public int hashCode() { - return Objects.hash(version); + return Objects.hash(this.version); } @Override public String toString() { - return String.format("Version[%d]", version); + return String.format("Version[%d]", this.version); } + } + } diff --git a/spring-vault-core/src/main/java/org/springframework/vault/support/WrappedMetadata.java b/spring-vault-core/src/main/java/org/springframework/vault/support/WrappedMetadata.java index a5f0ff0c..e287550d 100644 --- a/spring-vault-core/src/main/java/org/springframework/vault/support/WrappedMetadata.java +++ b/spring-vault-core/src/main/java/org/springframework/vault/support/WrappedMetadata.java @@ -44,8 +44,7 @@ public class WrappedMetadata { * @param creationTime must not be {@literal null}. * @param path can be {@literal null}. */ - public WrappedMetadata(VaultToken token, Duration ttl, Instant creationTime, - @Nullable String path) { + public WrappedMetadata(VaultToken token, Duration ttl, Instant creationTime, @Nullable String path) { Assert.notNull(token, "VaultToken must not be null"); Assert.notNull(ttl, "TTL duration must not be null"); @@ -58,19 +57,20 @@ public class WrappedMetadata { } public VaultToken getToken() { - return token; + return this.token; } public Duration getTtl() { - return ttl; + return this.ttl; } public Instant getCreationTime() { - return creationTime; + return this.creationTime; } @Nullable public String getPath() { - return path; + return this.path; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/annotation/LeaseAwareVaultPropertySourceIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/annotation/LeaseAwareVaultPropertySourceIntegrationTests.java index 3a2d07a1..36bf8b0a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/annotation/LeaseAwareVaultPropertySourceIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/annotation/LeaseAwareVaultPropertySourceIntegrationTests.java @@ -43,17 +43,17 @@ import static org.assertj.core.api.Assertions.fail; @ExtendWith(VaultExtension.class) class LeaseAwareVaultPropertySourceIntegrationTests { - @VaultPropertySource(value = { "secret/myapp", - "secret/myapp/profile" }, renewal = Renewal.RENEW) + @VaultPropertySource(value = { "secret/myapp", "secret/myapp/profile" }, renewal = Renewal.RENEW) static class Config extends VaultIntegrationTestConfiguration { + } @VaultPropertySource(value = { "unknown" }, ignoreSecretNotFound = false) static class FailingConfig extends VaultIntegrationTestConfiguration { + } - @VaultPropertySource(value = { - "unknown" }, ignoreSecretNotFound = false, renewal = Renewal.RENEW) + @VaultPropertySource(value = { "unknown" }, ignoreSecretNotFound = false, renewal = Renewal.RENEW) static class FailingRenewableConfig extends VaultIntegrationTestConfiguration { } @@ -63,17 +63,15 @@ class LeaseAwareVaultPropertySourceIntegrationTests { VaultOperations vaultOperations = vaultInitializer.prepare().getVaultOperations(); - vaultOperations.write("secret/myapp", - Collections.singletonMap("myapp", "myvalue")); - vaultOperations.write("secret/myapp/profile", - Collections.singletonMap("myprofile", "myprofilevalue")); + vaultOperations.write("secret/myapp", Collections.singletonMap("myapp", "myvalue")); + vaultOperations.write("secret/myapp/profile", Collections.singletonMap("myprofile", "myprofilevalue")); } @Test void shouldLoadProperties() { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, PropertyConsumer.class)) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class, + PropertyConsumer.class)) { ConfigurableEnvironment env = context.getEnvironment(); PropertyConsumer consumer = context.getBean(PropertyConsumer.class); @@ -86,13 +84,11 @@ class LeaseAwareVaultPropertySourceIntegrationTests { @Test void shouldFailIfPropertiesNotFound() { - try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - FailingConfig.class)) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FailingConfig.class)) { fail("AnnotationConfigApplicationContext startup did not fail"); } catch (Exception e) { - assertThat(e) - .hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class) + assertThat(e).hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class) .hasMessageContaining("Vault location [unknown] not resolvable"); } } @@ -106,15 +102,17 @@ class LeaseAwareVaultPropertySourceIntegrationTests { fail("AnnotationConfigApplicationContext startup did not fail"); } catch (Exception e) { - assertThat(e) - .hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class) + assertThat(e).hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class) .hasMessageContaining("Vault location [unknown] not resolvable"); } } @Component static class PropertyConsumer { + @Value("${myapp}") String myapp; + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceInBeanConfigurationIntegrationTest.java b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceInBeanConfigurationIntegrationTest.java index cd310ebc..66e608e3 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceInBeanConfigurationIntegrationTest.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceInBeanConfigurationIntegrationTest.java @@ -50,6 +50,7 @@ class VaultPropertySourceInBeanConfigurationIntegrationTest { ClientClass clientClass(@Value("${myapp}") String myapp) { return new ClientClass(myapp); } + } @Autowired @@ -60,16 +61,16 @@ class VaultPropertySourceInBeanConfigurationIntegrationTest { VaultOperations vaultOperations = initializer.prepare().getVaultOperations(); - vaultOperations.write("secret/myapp", - Collections.singletonMap("myapp", "myvalue")); + vaultOperations.write("secret/myapp", Collections.singletonMap("myapp", "myvalue")); } @Test void clientClassShouldContainResolvedProperty() { - assertThat(clientClass.getMyapp()).isEqualTo("myvalue"); + assertThat(this.clientClass.getMyapp()).isEqualTo("myvalue"); } static class ClientClass { + String myapp; public ClientClass(String myapp) { @@ -83,5 +84,7 @@ class VaultPropertySourceInBeanConfigurationIntegrationTest { public void setMyapp(String myapp) { this.myapp = myapp; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceIntegrationTests.java index 11f1a12d..d9dde683 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceIntegrationTests.java @@ -47,20 +47,25 @@ class VaultPropertySourceIntegrationTests { @Import({ Partial1.class, Partial2.class }) static class Config extends VaultIntegrationTestConfiguration { + } @VaultPropertySource({ "secret/myapp", "secret/myapp/profile" }) static class Partial1 { + } @VaultPropertySource("secret/generic") static class Partial2 { + } @Autowired Environment env; + @Autowired ApplicationContext context; + @Value("${myapp}") String myapp; @@ -69,24 +74,22 @@ class VaultPropertySourceIntegrationTests { VaultOperations vaultOperations = initializer.prepare().getVaultOperations(); - vaultOperations.write("secret/myapp", - Collections.singletonMap("myapp", "myvalue")); - vaultOperations.write("secret/generic", - Collections.singletonMap("generic", "generic-value")); - vaultOperations.write("secret/myapp/profile", - Collections.singletonMap("myprofile", "myprofilevalue")); + vaultOperations.write("secret/myapp", Collections.singletonMap("myapp", "myvalue")); + vaultOperations.write("secret/generic", Collections.singletonMap("generic", "generic-value")); + vaultOperations.write("secret/myapp/profile", Collections.singletonMap("myprofile", "myprofilevalue")); } @Test void environmentShouldResolveProperties() { - assertThat(env.getProperty("myapp")).isEqualTo("myvalue"); - assertThat(env.getProperty("myprofile")).isEqualTo("myprofilevalue"); - assertThat(env.getProperty("generic")).isEqualTo("generic-value"); + assertThat(this.env.getProperty("myapp")).isEqualTo("myvalue"); + assertThat(this.env.getProperty("myprofile")).isEqualTo("myprofilevalue"); + assertThat(this.env.getProperty("generic")).isEqualTo("generic-value"); } @Test void valueShouldInjectProperty() { - assertThat(myapp).isEqualTo("myvalue"); + assertThat(this.myapp).isEqualTo("myvalue"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceMultipleIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceMultipleIntegrationTests.java index fe48e653..4eb63f42 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceMultipleIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceMultipleIntegrationTests.java @@ -47,6 +47,7 @@ class VaultPropertySourceMultipleIntegrationTests { @VaultPropertySource(value = "secret/myapp/profile", propertyNamePrefix = "database.") @VaultPropertySource("secret/myapp") static class Config extends VaultIntegrationTestConfiguration { + } @Autowired @@ -63,21 +64,20 @@ class VaultPropertySourceMultipleIntegrationTests { VaultOperations vaultOperations = initializer.prepare().getVaultOperations(); - vaultOperations.write("secret/myapp", - Collections.singletonMap("myapp", "myvalue")); - vaultOperations.write("secret/myapp/profile", - Collections.singletonMap("myprofile", "myprofilevalue")); + vaultOperations.write("secret/myapp", Collections.singletonMap("myapp", "myvalue")); + vaultOperations.write("secret/myapp/profile", Collections.singletonMap("myprofile", "myprofilevalue")); } @Test void environmentShouldResolveProperties() { - assertThat(env.getProperty("myapp")).isEqualTo("myvalue"); - assertThat(env.getProperty("database.myprofile")).isEqualTo("myprofilevalue"); + assertThat(this.env.getProperty("myapp")).isEqualTo("myvalue"); + assertThat(this.env.getProperty("database.myprofile")).isEqualTo("myprofilevalue"); } @Test void valueShouldInjectProperty() { - assertThat(myapp).isEqualTo("myvalue"); + assertThat(this.myapp).isEqualTo("myvalue"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceUnitTests.java index 89edc7ac..991fa660 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/annotation/VaultPropertySourceUnitTests.java @@ -52,28 +52,33 @@ class VaultPropertySourceUnitTests { SecretLeaseContainer secretLeaseContainer() { return Mockito.mock(SecretLeaseContainer.class); } + } @Configuration @Profile("demo") @VaultPropertySource("foo") static class DemoProfile { + } @Configuration @Profile("dev") @VaultPropertySource("bar") static class DevProfile { + } @Configuration @VaultPropertySource("foo/${my_property}") static class NonRenewableConfig { + } @Configuration @VaultPropertySource(value = "foo/${my_property}", renewal = RENEW) static class RenewableConfig { + } @AfterEach @@ -151,8 +156,8 @@ class VaultPropertySourceUnitTests { verify(leaseContainerMock).afterPropertiesSet(); verify(leaseContainerMock).addLeaseListener(any()); verify(leaseContainerMock).addErrorListener(any()); - verify(leaseContainerMock) - .addRequestedSecret(RequestedSecret.renewable("foo/renewable")); + verify(leaseContainerMock).addRequestedSecret(RequestedSecret.renewable("foo/renewable")); verifyNoMoreInteractions(leaseContainerMock); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTestBase.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTestBase.java index 9ab57ec5..30ba6191 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTestBase.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTestBase.java @@ -27,8 +27,7 @@ import org.springframework.vault.util.IntegrationTestSupport; * * @author Mark Paluch */ -public abstract class AppIdAuthenticationIntegrationTestBase - extends IntegrationTestSupport { +public abstract class AppIdAuthenticationIntegrationTestBase extends IntegrationTestSupport { @BeforeEach public void before() { @@ -43,15 +42,13 @@ public abstract class AppIdAuthenticationIntegrationTestBase appIdData.put("value", "dummy"); // policy appIdData.put("display_name", "this is my test application"); - restOperations.postForEntity("auth/app-id/map/app-id/myapp", appIdData, - Map.class); + restOperations.postForEntity("auth/app-id/map/app-id/myapp", appIdData, Map.class); Map<String, String> userIdData = new HashMap<String, String>(); userIdData.put("value", "myapp"); // name of the app-id userIdData.put("cidr_block", "0.0.0.0/0"); - restOperations.postForEntity("auth/app-id/map/user-id/static-userid-value", - userIdData, Map.class); + restOperations.postForEntity("auth/app-id/map/user-id/static-userid-value", userIdData, Map.class); return null; }); diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTests.java index 971e6d4a..81be9915 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationIntegrationTests.java @@ -36,16 +36,13 @@ class AppIdAuthenticationIntegrationTests extends AppIdAuthenticationIntegration @Test void shouldLoginSuccessfully() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("myapp") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") // .userIdMechanism(new StaticUserId("static-userid-value")) // .build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); - AppIdAuthentication authentication = new AppIdAuthentication(options, - restTemplate); + AppIdAuthentication authentication = new AppIdAuthentication(options, restTemplate); VaultToken login = authentication.login(); assertThat(login.getToken()).isNotEmpty(); @@ -54,16 +51,15 @@ class AppIdAuthenticationIntegrationTests extends AppIdAuthenticationIntegration @Test void loginShouldFail() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("wrong") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") // .userIdMechanism(new StaticUserId("wrong")) // .build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); assertThatExceptionOfType(VaultException.class) .isThrownBy(() -> new AppIdAuthentication(options, restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationOperatorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationOperatorIntegrationTests.java index a989d394..a97240b9 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationOperatorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationOperatorIntegrationTests.java @@ -28,21 +28,19 @@ import org.springframework.web.reactive.function.client.WebClient; * * @author Mark Paluch */ -class AppIdAuthenticationOperatorIntegrationTests - extends AppIdAuthenticationIntegrationTestBase { +class AppIdAuthenticationOperatorIntegrationTests extends AppIdAuthenticationIntegrationTestBase { WebClient webClient = TestWebClientFactory.create(Settings.createSslConfiguration()); @Test void authenticationStepsShouldLoginSuccessfully() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("myapp") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") // .userIdMechanism(new StaticUserId("static-userid-value")) // .build(); AuthenticationStepsOperator supplier = new AuthenticationStepsOperator( - AppIdAuthentication.createAuthenticationSteps(options), webClient); + AppIdAuthentication.createAuthenticationSteps(options), this.webClient); supplier.getVaultToken() // .as(StepVerifier::create) // @@ -53,17 +51,17 @@ class AppIdAuthenticationOperatorIntegrationTests @Test void authenticationStepsLoginShouldFail() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("wrong") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") // .userIdMechanism(new StaticUserId("wrong")) // .build(); AuthenticationStepsOperator supplier = new AuthenticationStepsOperator( - AppIdAuthentication.createAuthenticationSteps(options), webClient); + AppIdAuthentication.createAuthenticationSteps(options), this.webClient); supplier.getVaultToken() // .as(StepVerifier::create) // .expectError() // .verify(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationStepsIntegrationTests.java index f6abc28d..174f9bd3 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationStepsIntegrationTests.java @@ -32,19 +32,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Mark Paluch */ -class AppIdAuthenticationStepsIntegrationTests - extends AppIdAuthenticationIntegrationTestBase { +class AppIdAuthenticationStepsIntegrationTests extends AppIdAuthenticationIntegrationTestBase { @Test void authenticationStepsShouldLoginSuccessfully() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("myapp") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") // .userIdMechanism(new StaticUserId("static-userid-value")) // .build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppIdAuthentication.createAuthenticationSteps(options), restTemplate); @@ -57,17 +54,16 @@ class AppIdAuthenticationStepsIntegrationTests @Test void authenticationStepsLoginShouldFail() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("wrong") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") // .userIdMechanism(new StaticUserId("wrong")) // .build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppIdAuthentication.createAuthenticationSteps(options), restTemplate); assertThatExceptionOfType(VaultException.class).isThrownBy(executor::login); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationUnitTests.java index 1c02efe0..3a138404 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppIdAuthenticationUnitTests.java @@ -58,20 +58,16 @@ class AppIdAuthenticationUnitTests { @Test void loginShouldObtainTokenWithStaticUserId() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("hello") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("hello") // .userIdMechanism(new StaticUserId("world")) // .build(); - mockRest.expect(requestTo("/auth/app-id/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.app_id").value("hello")) - .andExpect(jsonPath("$.user_id").value("world")) + this.mockRest.expect(requestTo("/auth/app-id/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.app_id").value("hello")).andExpect(jsonPath("$.user_id").value("world")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); - AppIdAuthentication authentication = new AppIdAuthentication(options, - restTemplate); + AppIdAuthentication authentication = new AppIdAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -81,15 +77,15 @@ class AppIdAuthenticationUnitTests { @Test void loginShouldFail() { - AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder() - .appId("hello") // + AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("hello") // .userIdMechanism(new StaticUserId("world")) // .build(); - mockRest.expect(requestTo("/auth/app-id/login")) // + this.mockRest.expect(requestTo("/auth/app-id/login")) // .andRespond(withServerError()); assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> new AppIdAuthentication(options, restTemplate).login()); + .isThrownBy(() -> new AppIdAuthentication(options, this.restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTestBase.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTestBase.java index 4be51c86..ce7c9d1f 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTestBase.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTestBase.java @@ -59,8 +59,7 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { withSecretId.put("token_ttl", "60s"); withSecretId.put("token_max_ttl", "60s"); - restOperations.postForEntity("auth/approle/role/with-secret-id", withSecretId, - Map.class); + restOperations.postForEntity("auth/approle/role/with-secret-id", withSecretId, Map.class); Map<String, String> noSecretIdRole = new HashMap<>(); noSecretIdRole.put("policies", "dummy"); // policy @@ -68,8 +67,7 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { noSecretIdRole.put("bind_secret_id", "false"); noSecretIdRole.put("max_ttl", "60s"); - restOperations.postForEntity("auth/approle/role/no-secret-id", noSecretIdRole, - Map.class); + restOperations.postForEntity("auth/approle/role/no-secret-id", noSecretIdRole, Map.class); return null; }); @@ -80,8 +78,7 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { } String getRoleId(String roleName) { - return (String) getVaultOperations() - .read(String.format("auth/approle/role/%s/role-id", roleName)) + return (String) getVaultOperations().read(String.format("auth/approle/role/%s/role-id", roleName)) .getRequiredData().get("role_id"); } @@ -91,10 +88,8 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { HttpEntity<String> httpEntity = getWrappingHeaders(); - VaultResponse response = restOperations - .exchange("auth/approle/role/with-secret-id/secret-id", - HttpMethod.PUT, httpEntity, VaultResponse.class) - .getBody(); + VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/secret-id", + HttpMethod.PUT, httpEntity, VaultResponse.class).getBody(); return VaultToken.of(response.getWrapInfo().get("token")); }); @@ -106,18 +101,15 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { HttpEntity<String> httpEntity = getWrappingHeaders(); - VaultResponse response = restOperations - .exchange("auth/approle/role/with-secret-id/role-id", HttpMethod.GET, - httpEntity, VaultResponse.class) - .getBody(); + VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/role-id", HttpMethod.GET, + httpEntity, VaultResponse.class).getBody(); return VaultToken.of(response.getWrapInfo().get("token")); }); } UnwrappingEndpoints getUnwrappingEndpoints() { - return useSysWrapping() ? UnwrappingEndpoints.SysWrapping - : UnwrappingEndpoints.Cubbyhole; + return useSysWrapping() ? UnwrappingEndpoints.SysWrapping : UnwrappingEndpoints.Cubbyhole; } private boolean useSysWrapping() { @@ -131,4 +123,5 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport { headers.set("X-Vault-Token", Settings.token().getToken()); return new HttpEntity<>(null, headers); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTests.java index c5dedd99..6e659356 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationIntegrationTests.java @@ -35,17 +35,15 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Mark Paluch * @author Christophe Tafani-Dereeper */ -class AppRoleAuthenticationIntegrationTests - extends AppRoleAuthenticationIntegrationTestBase { +class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegrationTestBase { @Test void shouldAuthenticateWithRoleIdOnly() { String roleId = getRoleId("no-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -53,11 +51,9 @@ class AppRoleAuthenticationIntegrationTests @Test void shouldAuthenticateWithFullPullMode() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .appRole("with-secret-id").roleId(RoleId.pull(Settings.token())) - .secretId(SecretId.pull(Settings.token())).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id") + .roleId(RoleId.pull(Settings.token())).secretId(SecretId.pull(Settings.token())).build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -66,11 +62,9 @@ class AppRoleAuthenticationIntegrationTests void shouldAuthenticateWithPullMode() { AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(getRoleId("with-secret-id"))) - .appRole("with-secret-id").secretId(SecretId.pull(Settings.token())) - .build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + .roleId(RoleId.provided(getRoleId("with-secret-id"))).appRole("with-secret-id") + .secretId(SecretId.pull(Settings.token())).build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -80,15 +74,12 @@ class AppRoleAuthenticationIntegrationTests String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() - .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), - null) - .getRequiredData().get("secret_id"); + .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData() + .get("secret_id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) - .build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .secretId(SecretId.provided(secretId)).build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -100,12 +91,10 @@ class AppRoleAuthenticationIntegrationTests VaultToken unwrappingToken = generateWrappedSecretIdResponse(); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .secretId(SecretId.wrapped(unwrappingToken)) - .roleId(RoleId.provided(roleId)) + .secretId(SecretId.wrapped(unwrappingToken)).roleId(RoleId.provided(roleId)) .unwrappingEndpoints(getUnwrappingEndpoints()).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -117,12 +106,10 @@ class AppRoleAuthenticationIntegrationTests VaultToken roleIdToken = generateWrappedRoleIdResponse(); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .secretId(SecretId.wrapped(secretIdToken)) - .roleId(RoleId.wrapped(roleIdToken)) + .secretId(SecretId.wrapped(secretIdToken)).roleId(RoleId.wrapped(roleIdToken)) .unwrappingEndpoints(getUnwrappingEndpoints()).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } @@ -134,12 +121,10 @@ class AppRoleAuthenticationIntegrationTests String unwrappingToken = "incorrect-unwrapping-token"; AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .secretId(SecretId.wrapped(VaultToken.of(unwrappingToken))) - .roleId(RoleId.provided(roleId)) + .secretId(SecretId.wrapped(VaultToken.of(unwrappingToken))).roleId(RoleId.provided(roleId)) .unwrappingEndpoints(getUnwrappingEndpoints()).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login); } @@ -149,10 +134,9 @@ class AppRoleAuthenticationIntegrationTests String roleId = getRoleId("with-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login); } @@ -162,11 +146,9 @@ class AppRoleAuthenticationIntegrationTests String roleId = getRoleId("with-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)) + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) .secretId(SecretId.provided("this-is-a-wrong-secret-id")).build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login); } @@ -178,19 +160,16 @@ class AppRoleAuthenticationIntegrationTests String secretId = "hello_world"; VaultResponse customSecretIdResponse = getVaultOperations().write( - "auth/approle/role/with-secret-id/custom-secret-id", - Collections.singletonMap("secret_id", secretId)); + "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) - .build(); - AppRoleAuthentication authentication = new AppRoleAuthentication(options, - prepare().getRestTemplate()); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .secretId(SecretId.provided(secretId)).build(); + AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); - getVaultOperations().write( - "auth/approle/role/with-secret-id/secret-id-accessor/destroy", + getVaultOperations().write("auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationStepsIntegrationTests.java index 05edcb78..d29274bf 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationStepsIntegrationTests.java @@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * @author Mark Paluch * @author Christophe Tafani-Dereeper */ -class AppRoleAuthenticationStepsIntegrationTests - extends AppRoleAuthenticationIntegrationTestBase { +class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIntegrationTestBase { @Test void authenticationStepsShouldAuthenticateWithWrappedSecretId() { @@ -46,13 +45,11 @@ class AppRoleAuthenticationStepsIntegrationTests VaultToken unwrappingToken = generateWrappedSecretIdResponse(); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .secretId(SecretId.wrapped(unwrappingToken)) - .roleId(RoleId.provided(roleId)) + .secretId(SecretId.wrapped(unwrappingToken)).roleId(RoleId.provided(roleId)) .unwrappingEndpoints(getUnwrappingEndpoints()).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } @@ -61,9 +58,8 @@ class AppRoleAuthenticationStepsIntegrationTests void authenticationStepsShouldAuthenticateWithWrappedRoleId() { String secretId = (String) getVaultOperations() - .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), - null) - .getRequiredData().get("secret_id"); + .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData() + .get("secret_id"); VaultToken roleIdToken = generateWrappedRoleIdResponse(); @@ -72,8 +68,7 @@ class AppRoleAuthenticationStepsIntegrationTests .unwrappingEndpoints(getUnwrappingEndpoints()).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } @@ -81,13 +76,11 @@ class AppRoleAuthenticationStepsIntegrationTests @Test void shouldAuthenticateWithFullPullMode() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .appRole("with-secret-id").roleId(RoleId.pull(Settings.token())) - .secretId(SecretId.pull(Settings.token())).build(); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id") + .roleId(RoleId.pull(Settings.token())).secretId(SecretId.pull(Settings.token())).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } @@ -97,13 +90,11 @@ class AppRoleAuthenticationStepsIntegrationTests String roleId = getRoleId("with-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .appRole("with-secret-id").secretId(SecretId.pull(Settings.token())) - .roleId(RoleId.provided(roleId)).build(); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id") + .secretId(SecretId.pull(Settings.token())).roleId(RoleId.provided(roleId)).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } @@ -112,17 +103,15 @@ class AppRoleAuthenticationStepsIntegrationTests void authenticationStepsShouldAuthenticateWithPullRoleId() { String secretId = (String) getVaultOperations() - .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), - null) - .getRequiredData().get("secret_id"); + .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData() + .get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .secretId(SecretId.provided(secretId)).appRole("with-secret-id") - .roleId(RoleId.pull(Settings.token())).build(); + .secretId(SecretId.provided(secretId)).appRole("with-secret-id").roleId(RoleId.pull(Settings.token())) + .build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } @@ -132,13 +121,11 @@ class AppRoleAuthenticationStepsIntegrationTests String roleId = getRoleId("with-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)) + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) .secretId(SecretId.provided("this-is-a-wrong-secret-id")).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThatExceptionOfType(VaultException.class).isThrownBy(executor::login); } @@ -150,21 +137,17 @@ class AppRoleAuthenticationStepsIntegrationTests String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( - "auth/approle/role/with-secret-id/custom-secret-id", - Collections.singletonMap("secret_id", secretId)); + "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) - .build(); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .secretId(SecretId.provided(secretId)).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); - getVaultOperations().write( - "auth/approle/role/with-secret-id/secret-id-accessor/destroy", + getVaultOperations().write("auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); } @@ -173,14 +156,13 @@ class AppRoleAuthenticationStepsIntegrationTests String roleId = getRoleId("with-secret-id"); - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided(roleId)).appRole("with-secret-id") - .secretId(SecretId.pull(Settings.token())).build(); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId)) + .appRole("with-secret-id").secretId(SecretId.pull(Settings.token())).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AppRoleAuthentication.createAuthenticationSteps(options), - prepare().getRestTemplate()); + AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate()); assertThat(executor.login()).isNotNull(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationUnitTests.java index 1da12ee2..8b83dda8 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AppRoleAuthenticationUnitTests.java @@ -71,19 +71,16 @@ class AppRoleAuthenticationUnitTests { @Test void loginShouldObtainToken() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided("hello")) // + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) // .secretId(SecretId.provided("world")) // .build(); - mockRest.expect(requestTo("/auth/approle/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role_id").value("hello")) - .andExpect(jsonPath("$.secret_id").value("world")) + this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").value("world")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); - AppRoleAuthentication sut = new AppRoleAuthentication(options, restTemplate); + AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate); VaultToken login = sut.login(); @@ -94,29 +91,23 @@ class AppRoleAuthenticationUnitTests { @Test void loginShouldPullRoleIdAndSecretId() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .appRole("app_role").initialToken(VaultToken.of("initial_token")).build(); + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("app_role") + .initialToken(VaultToken.of("initial_token")).build(); - mockRest.expect(requestTo("/auth/approle/role/app_role/role-id")) - .andExpect(method(HttpMethod.GET)) - .andExpect(header("X-Vault-token", "initial_token")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\": {\"role_id\": \"hello\"}}")); + this.mockRest.expect(requestTo("/auth/approle/role/app_role/role-id")).andExpect(method(HttpMethod.GET)) + .andExpect(header("X-Vault-token", "initial_token")).andRespond(withSuccess() + .contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\"role_id\": \"hello\"}}")); - mockRest.expect(requestTo("/auth/approle/role/app_role/secret-id")) - .andExpect(method(HttpMethod.POST)) - .andExpect(header("X-Vault-token", "initial_token")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\": {\"secret_id\": \"world\"}}")); + this.mockRest.expect(requestTo("/auth/approle/role/app_role/secret-id")).andExpect(method(HttpMethod.POST)) + .andExpect(header("X-Vault-token", "initial_token")).andRespond(withSuccess() + .contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\"secret_id\": \"world\"}}")); - mockRest.expect(requestTo("/auth/approle/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role_id").value("hello")) - .andExpect(jsonPath("$.secret_id").value("world")) + this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").value("world")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); - AppRoleAuthentication sut = new AppRoleAuthentication(options, restTemplate); + AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate); VaultToken login = sut.login(); @@ -126,105 +117,89 @@ class AppRoleAuthenticationUnitTests { @Test void optionsShouldRequireTokenOrRoleIdIfNothingIsSet() { - assertThatIllegalArgumentException() - .isThrownBy(() -> AppRoleAuthenticationOptions.builder().build()); + assertThatIllegalArgumentException().isThrownBy(() -> AppRoleAuthenticationOptions.builder().build()); } @Test void optionsShouldRequireTokenOrRoleIdIfTokenIsSet() { - assertThatIllegalArgumentException().isThrownBy(() -> AppRoleAuthenticationOptions - .builder().initialToken(VaultToken.of("foo")).build()); + assertThatIllegalArgumentException() + .isThrownBy(() -> AppRoleAuthenticationOptions.builder().initialToken(VaultToken.of("foo")).build()); } @Test void optionsShouldRequireTokenOrRoleIdIfAppRoleIdIsSet() { - assertThatIllegalArgumentException().isThrownBy( - () -> AppRoleAuthenticationOptions.builder().appRole("app_role").build()); + assertThatIllegalArgumentException() + .isThrownBy(() -> AppRoleAuthenticationOptions.builder().appRole("app_role").build()); } @Test void loginShouldObtainTokenWithoutSecretId() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided("hello")) // + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) // .build(); - mockRest.expect(requestTo("/auth/approle/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role_id").value("hello")) - .andExpect(jsonPath("$.secret_id").doesNotExist()) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" - + "}")); + this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").doesNotExist()) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" + + "}")); - AppRoleAuthentication sut = new AppRoleAuthentication(options, restTemplate); + AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate); VaultToken login = sut.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } @Test void loginShouldFail() { - AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided("hello")) // + AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) // .build(); - mockRest.expect(requestTo("/auth/approle/login")) // + this.mockRest.expect(requestTo("/auth/approle/login")) // .andRespond(withServerError()); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> new AppRoleAuthentication(options, restTemplate).login()); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> new AppRoleAuthentication(options, this.restTemplate).login()); } @Test void loginShouldUnwrapCubbyholeSecretIdResponse() throws Exception { AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided("my_role_id")) - .secretId(SecretId.wrapped(VaultToken.of("unwrapping_token"))) + .roleId(RoleId.provided("my_role_id")).secretId(SecretId.wrapped(VaultToken.of("unwrapping_token"))) .unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).build(); - String wrappedResponse = "{" - + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\"," - + " \"lease_id\": \"\"," + " \"renewable\": false," - + " \"lease_duration\": 0," + " \"data\": {" - + " \"secret_id\": \"my_secret_id\"," - + " \"secret_id_accessor\": \"my_secret_id_accessor\"" + " }," - + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" - + "}"; + String wrappedResponse = "{" + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\"," + + " \"lease_id\": \"\"," + " \"renewable\": false," + " \"lease_duration\": 0," + " \"data\": {" + + " \"secret_id\": \"my_secret_id\"," + " \"secret_id_accessor\": \"my_secret_id_accessor\"" + + " }," + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" + "}"; // Expect a first request to unwrap the response - mockRest.expect(requestTo("/cubbyhole/response")) - .andExpect(header("X-Vault-Token", "unwrapping_token")) + this.mockRest.expect(requestTo("/cubbyhole/response")).andExpect(header("X-Vault-Token", "unwrapping_token")) .andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\":{\"response\":" - + OBJECT_MAPPER.writeValueAsString(wrappedResponse) - + "} }")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }")); // Also expect a second request to retrieve a token - mockRest.expect(requestTo("/auth/approle/login")) - .andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.role_id").value("my_role_id")) .andExpect(jsonPath("$.secret_id").value("my_secret_id")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" - + "}")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" + + "}")); - AppRoleAuthentication auth = new AppRoleAuthentication(options, restTemplate); + AppRoleAuthentication auth = new AppRoleAuthentication(options, this.restTemplate); VaultToken login = auth.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } @@ -232,41 +207,35 @@ class AppRoleAuthenticationUnitTests { void loginShouldUnwrapSecretIdResponse() throws Exception { AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() - .roleId(RoleId.provided("my_role_id")) - .secretId(SecretId.wrapped(VaultToken.of("unwrapping_token"))).build(); + .roleId(RoleId.provided("my_role_id")).secretId(SecretId.wrapped(VaultToken.of("unwrapping_token"))) + .build(); - String wrappedResponse = "{" - + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\"," - + " \"lease_id\": \"\"," + " \"renewable\": false," - + " \"lease_duration\": 0," + " \"data\": {" - + " \"secret_id\": \"my_secret_id\"," - + " \"secret_id_accessor\": \"my_secret_id_accessor\"" + " }," - + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" - + "}"; + String wrappedResponse = "{" + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\"," + + " \"lease_id\": \"\"," + " \"renewable\": false," + " \"lease_duration\": 0," + " \"data\": {" + + " \"secret_id\": \"my_secret_id\"," + " \"secret_id_accessor\": \"my_secret_id_accessor\"" + + " }," + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" + "}"; // Expect a first request to unwrap the response - mockRest.expect(requestTo("/sys/wrapping/unwrap")) - .andExpect(header("X-Vault-Token", "unwrapping_token")) - .andExpect(method(HttpMethod.POST)).andRespond(withSuccess() - .contentType(MediaType.APPLICATION_JSON).body(wrappedResponse)); + this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(header("X-Vault-Token", "unwrapping_token")) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse)); // Also expect a second request to retrieve a token - mockRest.expect(requestTo("/auth/approle/login")) - .andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.role_id").value("my_role_id")) .andExpect(jsonPath("$.secret_id").value("my_secret_id")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" - + "}")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}" + + "}")); - AppRoleAuthentication auth = new AppRoleAuthentication(options, restTemplate); + AppRoleAuthentication auth = new AppRoleAuthentication(options, this.restTemplate); VaultToken login = auth.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsExecutorUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsExecutorUnitTests.java index cc34b403..2a44f1f1 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsExecutorUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsExecutorUnitTests.java @@ -75,8 +75,7 @@ class AuthenticationStepsExecutorUnitTests { @Test void supplierOfStringShouldLoginWithMap() { - AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "my-token") - .login(VaultToken::of); + AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "my-token").login(VaultToken::of); assertThat(login(steps)).isEqualTo(VaultToken.of("my-token")); } @@ -84,10 +83,10 @@ class AuthenticationStepsExecutorUnitTests { @Test void justLoginRequestShouldLogin() { - mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); AuthenticationSteps steps = AuthenticationSteps .just(post("/auth/{path}/login", "cert").as(VaultResponse.class)); @@ -98,33 +97,31 @@ class AuthenticationStepsExecutorUnitTests { @Test void justLoginShouldFail() { - mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) .andRespond(withBadRequest().body("foo")); AuthenticationSteps steps = AuthenticationSteps .just(post("/auth/{path}/login", "cert").as(VaultResponse.class)); - assertThatExceptionOfType(VaultException.class).isThrownBy(() -> login(steps)) - .withMessageContaining( - "HTTP request POST /auth/{path}/login AS class org.springframework.vault.support.VaultResponse " - + "in state null failed with Status 400 and body foo"); + assertThatExceptionOfType(VaultException.class).isThrownBy(() -> login(steps)).withMessageContaining( + "HTTP request POST /auth/{path}/login AS class org.springframework.vault.support.VaultResponse " + + "in state null failed with Status 400 and body foo"); } @Test void initialRequestWithMapShouldLogin() { - mockRest.expect(requestTo("somewhere/else")).andExpect(method(HttpMethod.GET)) + this.mockRest.expect(requestTo("somewhere/else")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo")); - mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST)) .andExpect(content().string("foo-token")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); AuthenticationSteps steps = AuthenticationSteps - .fromHttpRequest(get(URI.create("somewhere/else")).as(String.class)) - .onNext(System.out::println) // + .fromHttpRequest(get(URI.create("somewhere/else")).as(String.class)).onNext(System.out::println) // .map(s -> s.concat("-token")) // .login("/auth/cert/login"); @@ -134,22 +131,21 @@ class AuthenticationStepsExecutorUnitTests { @Test void requestWithHeadersShouldLogin() { - mockRest.expect(requestTo("somewhere/else")) // + this.mockRest.expect(requestTo("somewhere/else")) // .andExpect(header("foo", "bar")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo")); - mockRest.expect(requestTo("/auth/cert/login")).andExpect(content().string("foo")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(content().string("foo")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); HttpHeaders headers = new HttpHeaders(); headers.add("foo", "bar"); AuthenticationSteps steps = AuthenticationSteps - .fromHttpRequest( - get(URI.create("somewhere/else")).with(headers).as(String.class)) // + .fromHttpRequest(get(URI.create("somewhere/else")).with(headers).as(String.class)) // .login("/auth/cert/login"); assertThat(login(steps)).isEqualTo(VaultToken.of("foo-token")); @@ -158,13 +154,11 @@ class AuthenticationStepsExecutorUnitTests { @Test void zipWithShouldRequestTwoItems() { - mockRest.expect(requestTo("/auth/login/left")).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{" + "\"request_id\": \"left\"}")); + this.mockRest.expect(requestTo("/auth/login/left")).andExpect(method(HttpMethod.POST)).andRespond( + withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"left\"}")); - mockRest.expect(requestTo("/auth/login/right")).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{" + "\"request_id\": \"right\"}")); + this.mockRest.expect(requestTo("/auth/login/right")).andExpect(method(HttpMethod.POST)).andRespond( + withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"right\"}")); Node<VaultResponse> left = AuthenticationSteps .fromHttpRequest(post("/auth/login/left").as(VaultResponse.class)); @@ -172,13 +166,14 @@ class AuthenticationStepsExecutorUnitTests { Node<VaultResponse> right = AuthenticationSteps .fromHttpRequest(post("/auth/login/right").as(VaultResponse.class)); - AuthenticationSteps steps = left.zipWith(right).login(it -> VaultToken - .of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId())); + AuthenticationSteps steps = left.zipWith(right) + .login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId())); assertThat(login(steps)).isEqualTo(VaultToken.of("left-right")); } private VaultToken login(AuthenticationSteps steps) { - return new AuthenticationStepsExecutor(steps, restTemplate).login(); + return new AuthenticationStepsExecutor(steps, this.restTemplate).login(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsOperatorUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsOperatorUnitTests.java index 0de3663d..2ec376f4 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsOperatorUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AuthenticationStepsOperatorUnitTests.java @@ -58,8 +58,7 @@ class AuthenticationStepsOperatorUnitTests { @Test void supplierOfStringShouldLoginWithMap() { - AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "my-token") - .login(VaultToken::of); + AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "my-token").login(VaultToken::of); login(steps).as(StepVerifier::create) // .expectNext(VaultToken.of("my-token")) // @@ -69,15 +68,12 @@ class AuthenticationStepsOperatorUnitTests { @Test void justLoginRequestShouldLogin() { - ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, - "/auth/cert/login"); + ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login"); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); - response.setBody("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}"); - ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request) - .then(Mono.just(response)); + response.setBody( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}"); + ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response)); WebClient webClient = WebClient.builder().clientConnector(connector).build(); @@ -92,12 +88,9 @@ class AuthenticationStepsOperatorUnitTests { @Test void justLoginShouldFail() { - ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, - "/auth/cert/login"); - MockClientHttpResponse response = new MockClientHttpResponse( - HttpStatus.BAD_REQUEST); - ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request) - .then(Mono.just(response)); + ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/cert/login"); + MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.BAD_REQUEST); + ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response)); WebClient webClient = WebClient.builder().clientConnector(connector).build(); @@ -112,14 +105,12 @@ class AuthenticationStepsOperatorUnitTests { @Test void zipWithShouldRequestTwoItems() { - ClientHttpRequest leftRequest = new MockClientHttpRequest(HttpMethod.GET, - "/auth/login/left"); + ClientHttpRequest leftRequest = new MockClientHttpRequest(HttpMethod.GET, "/auth/login/left"); MockClientHttpResponse leftResponse = new MockClientHttpResponse(HttpStatus.OK); leftResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON); leftResponse.setBody("{" + "\"request_id\": \"left\"}"); - ClientHttpRequest rightRequest = new MockClientHttpRequest(HttpMethod.GET, - "/auth/login/right"); + ClientHttpRequest rightRequest = new MockClientHttpRequest(HttpMethod.GET, "/auth/login/right"); MockClientHttpResponse rightResponse = new MockClientHttpResponse(HttpStatus.OK); rightResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON); rightResponse.setBody("{" + "\"request_id\": \"right\"}"); @@ -141,8 +132,8 @@ class AuthenticationStepsOperatorUnitTests { Node<VaultResponse> right = AuthenticationSteps .fromHttpRequest(post("/auth/login/right").as(VaultResponse.class)); - AuthenticationSteps steps = left.zipWith(right).login(it -> VaultToken - .of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId())); + AuthenticationSteps steps = left.zipWith(right) + .login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId())); login(steps, webClient).as(StepVerifier::create) // .expectNext(VaultToken.of("left-right")) // @@ -151,15 +142,14 @@ class AuthenticationStepsOperatorUnitTests { private Mono<VaultToken> login(AuthenticationSteps steps) { - AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, - WebClient.create()); + AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, WebClient.create()); return operator.getVaultToken(); } private Mono<VaultToken> login(AuthenticationSteps steps, WebClient webClient) { - AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, - webClient); + AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, webClient); return operator.getVaultToken(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsEc2AuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsEc2AuthenticationUnitTests.java index eb112dfe..5fa3c4ce 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsEc2AuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsEc2AuthenticationUnitTests.java @@ -64,30 +64,25 @@ class AwsEc2AuthenticationUnitTests { @Test void shouldObtainIdentityDocument() { - mockRest.expect(requestTo( - "http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // + this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().body("Hello, world")); - AwsEc2Authentication authentication = new AwsEc2Authentication(restTemplate); + AwsEc2Authentication authentication = new AwsEc2Authentication(this.restTemplate); - assertThat(authentication.getEc2Login()).containsEntry("pkcs7", "Hello, world") - .containsKey("nonce").hasSize(2); + assertThat(authentication.getEc2Login()).containsEntry("pkcs7", "Hello, world").containsKey("nonce").hasSize(2); } @Test void shouldContainRole() { - AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder() - .role("ami").build(); + AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder().role("ami").build(); - mockRest.expect(requestTo( - "http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // + this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().body("Hello, world")); - AwsEc2Authentication authentication = new AwsEc2Authentication(options, - restTemplate, restTemplate); + AwsEc2Authentication authentication = new AwsEc2Authentication(options, this.restTemplate, this.restTemplate); assertThat(authentication.getEc2Login()) // .containsEntry("pkcs7", "Hello, world") // @@ -100,31 +95,25 @@ class AwsEc2AuthenticationUnitTests { Nonce nonce = Nonce.provided("foo".toCharArray()); - AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions - .builder().nonce(nonce).build(); + AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder().nonce(nonce).build(); - mockRest.expect(requestTo( - "http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // + this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().body("value")); - mockRest.expect(requestTo("/auth/aws-ec2/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.pkcs7").value("value")) - .andExpect(jsonPath("$.nonce").value("foo")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" - + "}")); + this.mockRest.expect(requestTo("/auth/aws-ec2/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.pkcs7").value("value")).andExpect(jsonPath("$.nonce").value("foo")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) + .body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}")); - AwsEc2Authentication authentication = new AwsEc2Authentication( - authenticationOptions, restTemplate, restTemplate); + AwsEc2Authentication authentication = new AwsEc2Authentication(authenticationOptions, this.restTemplate, + this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(20)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(20)); assertThat(((LoginToken) login).isRenewable()).isFalse(); } @@ -133,56 +122,49 @@ class AwsEc2AuthenticationUnitTests { Nonce nonce = Nonce.provided("foo".toCharArray()); - AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder() - .nonce(nonce).build(); + AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder().nonce(nonce).build(); - mockRest.expect(requestTo( - "http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // + this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess().body("value")); - mockRest.expect(requestTo("/auth/aws-ec2/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.pkcs7").value("value")) - .andExpect(jsonPath("$.nonce").value("foo")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" - + "}")); + this.mockRest.expect(requestTo("/auth/aws-ec2/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.pkcs7").value("value")).andExpect(jsonPath("$.nonce").value("foo")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) + .body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}")); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - AwsEc2Authentication.createAuthenticationSteps(options), restTemplate); + AwsEc2Authentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = executor.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(20)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(20)); assertThat(((LoginToken) login).isRenewable()).isFalse(); } @Test void loginShouldFailWhileObtainingIdentityDocument() { - mockRest.expect(requestTo( - "http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // + this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) // .andRespond(withServerError()); assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> new AwsEc2Authentication(restTemplate).login()); + .isThrownBy(() -> new AwsEc2Authentication(this.restTemplate).login()); } @Test void loginShouldFail() { - mockRest.expect(requestTo("/auth/aws-ec2/login")) // + this.mockRest.expect(requestTo("/auth/aws-ec2/login")) // .andRespond(withServerError()); - assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> new AwsEc2Authentication(restTemplate) { - @Override - protected Map<String, String> getEc2Login() { - return Collections.singletonMap("pkcs7", "value"); - } - }.login()); + assertThatExceptionOfType(VaultException.class).isThrownBy(() -> new AwsEc2Authentication(this.restTemplate) { + @Override + protected Map<String, String> getEc2Login() { + return Collections.singletonMap("pkcs7", "value"); + } + }.login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsIamAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsIamAuthenticationUnitTests.java index 43ec6e15..e648e0f9 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsIamAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AwsIamAuthenticationUnitTests.java @@ -59,58 +59,49 @@ class AwsIamAuthenticationUnitTests { @Test void shouldAuthenticate() { - mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.iam_http_request_method").value("POST")) - .andExpect(jsonPath("$.iam_request_url").exists()) - .andExpect(jsonPath("$.iam_request_body").exists()) - .andExpect(jsonPath("$.iam_request_headers").exists()) - .andExpect(jsonPath("$.role").value("foo-role")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + .andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists()) + .andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); - AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder() - .role("foo-role").credentials(new BasicAWSCredentials("foo", "bar")) - .build(); - AwsIamAuthentication sut = new AwsIamAuthentication(options, restTemplate); + AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role") + .credentials(new BasicAWSCredentials("foo", "bar")).build(); + AwsIamAuthentication sut = new AwsIamAuthentication(options, this.restTemplate); VaultToken login = sut.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } @Test void shouldUsingAuthenticationSteps() { - mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.iam_http_request_method").value("POST")) - .andExpect(jsonPath("$.iam_request_url").exists()) - .andExpect(jsonPath("$.iam_request_body").exists()) - .andExpect(jsonPath("$.iam_request_headers").exists()) - .andExpect(jsonPath("$.role").value("foo-role")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + .andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists()) + .andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); - AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder() - .role("foo-role").credentials(new BasicAWSCredentials("foo", "bar")) - .build(); + AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role") + .credentials(new BasicAWSCredentials("foo", "bar")).build(); - AuthenticationSteps steps = AwsIamAuthentication - .createAuthenticationSteps(options); - AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, - restTemplate); + AuthenticationSteps steps = AwsIamAuthentication.createAuthenticationSteps(options); + AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, this.restTemplate); VaultToken login = executor.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AzureMsiAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AzureMsiAuthenticationUnitTests.java index 761c2d0f..9153b8a8 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/AzureMsiAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/AzureMsiAuthenticationUnitTests.java @@ -57,16 +57,14 @@ class AzureMsiAuthenticationUnitTests { @Test void loginShouldObtainTokenAndFetchMetadata() { - AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() - .role("dev-role") // + AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") // .build(); expectMetadataRequest(); expectIdentityTokenRequest(); expectLoginRequest(); - AzureMsiAuthentication authentication = new AzureMsiAuthentication(options, - restTemplate); + AzureMsiAuthentication authentication = new AzureMsiAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -76,17 +74,13 @@ class AzureMsiAuthenticationUnitTests { @Test void loginShouldObtainToken() { - AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() - .role("dev-role") - .vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", - "vault-client")) - .build(); + AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") + .vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client")).build(); expectIdentityTokenRequest(); expectLoginRequest(); - AzureMsiAuthentication authentication = new AzureMsiAuthentication(options, - restTemplate); + AzureMsiAuthentication authentication = new AzureMsiAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -96,8 +90,7 @@ class AzureMsiAuthenticationUnitTests { @Test void loginWithStepsShouldObtainTokenAndFetchMetadata() { - AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() - .role("dev-role") // + AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") // .build(); expectMetadataRequest(); @@ -105,7 +98,7 @@ class AzureMsiAuthenticationUnitTests { expectLoginRequest(); AuthenticationStepsExecutor authentication = new AuthenticationStepsExecutor( - AzureMsiAuthentication.createAuthenticationSteps(options), restTemplate); + AzureMsiAuthentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -115,17 +108,14 @@ class AzureMsiAuthenticationUnitTests { @Test void loginWithStepsShouldObtainToken() { - AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() - .role("dev-role") - .vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", - "vault-client")) - .build(); + AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") + .vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client")).build(); expectIdentityTokenRequest(); expectLoginRequest(); AuthenticationStepsExecutor authentication = new AuthenticationStepsExecutor( - AzureMsiAuthentication.createAuthenticationSteps(options), restTemplate); + AzureMsiAuthentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -134,36 +124,31 @@ class AzureMsiAuthenticationUnitTests { private void expectMetadataRequest() { - mockRest.expect(requestTo( - AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI)) + this.mockRest.expect(requestTo(AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI)) .andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\n" + " \"compute\": {\n" - + " \"name\": \"vault-client\",\n" + .body("{\n" + " \"compute\": {\n" + " \"name\": \"vault-client\",\n" + " \"resourceGroupName\": \"vault\",\n" - + " \"subscriptionId\": \"foobar-subscription\"\n" - + " }\n" + "}")); + + " \"subscriptionId\": \"foobar-subscription\"\n" + " }\n" + "}")); } private void expectIdentityTokenRequest() { - mockRest.expect(requestTo( - AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI)) - .andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"access_token\": \"my-token\" }")); + this.mockRest.expect(requestTo(AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI)) + .andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true")).andRespond(withSuccess() + .contentType(MediaType.APPLICATION_JSON).body("{\"access_token\": \"my-token\" }")); } private void expectLoginRequest() { - mockRest.expect(requestTo("/auth/azure/login")).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("dev-role")) - .andExpect(jsonPath("$.jwt").value("my-token")) + this.mockRest.expect(requestTo("/auth/azure/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-token")) .andExpect(jsonPath("$.subscription_id").value("foobar-subscription")) .andExpect(jsonPath("$.resource_group_name").value("vault")) .andExpect(jsonPath("$.vm_name").value("vault-client")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTestBase.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTestBase.java index cd227d14..824fc225 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTestBase.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTestBase.java @@ -38,13 +38,11 @@ import static org.springframework.vault.util.Settings.findWorkDir; * * @author Mark Paluch */ -public abstract class ClientCertificateAuthenticationIntegrationTestBase - extends IntegrationTestSupport { +public abstract class ClientCertificateAuthenticationIntegrationTestBase extends IntegrationTestSupport { - static final Policy POLICY = Policy.of(Policy.Rule.builder().path("/*") - .capabilities(Policy.BuiltinCapabilities.READ, - Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE) - .build()); + static final Policy POLICY = Policy + .of(Policy.Rule.builder().path("/*").capabilities(Policy.BuiltinCapabilities.READ, + Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE).build()); @BeforeEach public void before() { @@ -53,42 +51,33 @@ public abstract class ClientCertificateAuthenticationIntegrationTestBase prepare().mountAuth("cert"); } - prepare().getVaultOperations().opsForSys().createOrUpdatePolicy("cert-auth", - POLICY); + prepare().getVaultOperations().opsForSys().createOrUpdatePolicy("cert-auth", POLICY); - prepare().getVaultOperations() - .doWithSession((RestOperationsCallback<Object>) restOperations -> { - File workDir = findWorkDir(); + prepare().getVaultOperations().doWithSession((RestOperationsCallback<Object>) restOperations -> { + File workDir = findWorkDir(); - String certificate = Files.contentOf( - new File(workDir, "ca/certs/client.cert.pem"), - StandardCharsets.US_ASCII); + String certificate = Files.contentOf(new File(workDir, "ca/certs/client.cert.pem"), + StandardCharsets.US_ASCII); - Map<String, Object> role = new LinkedHashMap<>(); - role.put("token_policies", "cert-auth"); - role.put("certificate", certificate); + Map<String, Object> role = new LinkedHashMap<>(); + role.put("token_policies", "cert-auth"); + role.put("certificate", certificate); - return restOperations.postForEntity("auth/cert/certs/my-role", - role, - Map.class); - }); + return restOperations.postForEntity("auth/cert/certs/my-role", role, Map.class); + }); } static SslConfiguration prepareCertAuthenticationMethod() { - return prepareCertAuthenticationMethod( - SslConfiguration.KeyConfiguration.unconfigured()); + return prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.unconfigured()); } - static SslConfiguration prepareCertAuthenticationMethod( - SslConfiguration.KeyConfiguration keyConfiguration) { + static SslConfiguration prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration keyConfiguration) { SslConfiguration original = createSslConfiguration(); - return new SslConfiguration( - KeyStoreConfiguration.of( - new FileSystemResource( - new File(findWorkDir(), "client-cert.jks")), - "changeit".toCharArray()), + return new SslConfiguration(KeyStoreConfiguration + .of(new FileSystemResource(new File(findWorkDir(), "client-cert.jks")), "changeit".toCharArray()), keyConfiguration, original.getTrustStoreConfiguration()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTests.java index dac5f0db..f91ff0ec 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationIntegrationTests.java @@ -37,19 +37,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * * @author Mark Paluch */ -class ClientCertificateAuthenticationIntegrationTests - extends ClientCertificateAuthenticationIntegrationTestBase { +class ClientCertificateAuthenticationIntegrationTests extends ClientCertificateAuthenticationIntegrationTestBase { @Test void shouldLoginSuccessfully() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), prepareCertAuthenticationMethod()); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + prepareCertAuthenticationMethod()); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); - ClientCertificateAuthentication authentication = new ClientCertificateAuthentication( - restTemplate); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); + ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate); VaultToken login = authentication.login(); assertThat(login.getToken()).isNotEmpty(); @@ -58,15 +56,12 @@ class ClientCertificateAuthenticationIntegrationTests @Test void shouldSelectKey() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), - prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration - .of("changeit".toCharArray(), "1"))); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1"))); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); - ClientCertificateAuthentication authentication = new ClientCertificateAuthentication( - restTemplate); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); + ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate); VaultToken login = authentication.login(); assertThat(login.getToken()).isNotEmpty(); @@ -75,27 +70,21 @@ class ClientCertificateAuthenticationIntegrationTests @Test void shouldSelectInvalidKey() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), - prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration - .of("changeit".toCharArray(), "2"))); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "2"))); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); - ClientCertificateAuthentication authentication = new ClientCertificateAuthentication( - restTemplate); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); + ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(restTemplate); - assertThatExceptionOfType(NestedRuntimeException.class) - .isThrownBy(authentication::login); + assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(authentication::login); } @Test void shouldProvideInvalidKeyPassword() { - assertThatIllegalStateException().isThrownBy( - () -> ClientHttpRequestFactoryFactory.create(new ClientOptions(), - prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration - .of("wrong".toCharArray(), "1")))); + assertThatIllegalStateException().isThrownBy(() -> ClientHttpRequestFactoryFactory.create(new ClientOptions(), + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("wrong".toCharArray(), "1")))); } // Compatibility for Vault 0.6.0 and below. Vault 0.6.1 fixed that issue and we @@ -103,12 +92,13 @@ class ClientCertificateAuthenticationIntegrationTests @Test void loginShouldFail() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration()); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + Settings.createSslConfiguration()); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); - assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy( - () -> new ClientCertificateAuthentication(restTemplate).login()); + assertThatExceptionOfType(NestedRuntimeException.class) + .isThrownBy(() -> new ClientCertificateAuthentication(restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOperatorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOperatorIntegrationTests.java index 22f91682..0082c895 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOperatorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationOperatorIntegrationTests.java @@ -36,8 +36,7 @@ class ClientCertificateAuthenticationOperatorIntegrationTests @Test void authenticationStepsShouldLoginSuccessfully() { - WebClient webClient = TestWebClientFactory - .create(prepareCertAuthenticationMethod()); + WebClient webClient = TestWebClientFactory.create(prepareCertAuthenticationMethod()); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( ClientCertificateAuthentication.createAuthenticationSteps(), webClient); @@ -51,8 +50,8 @@ class ClientCertificateAuthenticationOperatorIntegrationTests @Test void shouldSelectKey() { - WebClient webClient = TestWebClientFactory.create(prepareCertAuthenticationMethod( - SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1"))); + WebClient webClient = TestWebClientFactory.create( + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1"))); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( ClientCertificateAuthentication.createAuthenticationSteps(), webClient); @@ -66,8 +65,8 @@ class ClientCertificateAuthenticationOperatorIntegrationTests @Test void shouldSelectInvalidKey() { - WebClient webClient = TestWebClientFactory.create(prepareCertAuthenticationMethod( - SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "2"))); + WebClient webClient = TestWebClientFactory.create( + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "2"))); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( ClientCertificateAuthentication.createAuthenticationSteps(), webClient); @@ -79,8 +78,8 @@ class ClientCertificateAuthenticationOperatorIntegrationTests @Test void shouldProvideInvalidKeyPassword() { - assertThatIllegalStateException().isThrownBy(() -> TestWebClientFactory - .create(prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration - .of("wrong".toCharArray(), "1")))); + assertThatIllegalStateException().isThrownBy(() -> TestWebClientFactory.create( + prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("wrong".toCharArray(), "1")))); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationStepsIntegrationTests.java index 9877df9d..55164ece 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationStepsIntegrationTests.java @@ -36,21 +36,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Mark Paluch */ -class ClientCertificateAuthenticationStepsIntegrationTests - extends ClientCertificateAuthenticationIntegrationTestBase { +class ClientCertificateAuthenticationStepsIntegrationTests extends ClientCertificateAuthenticationIntegrationTestBase { @Test void authenticationStepsShouldLoginSuccessfully() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), prepareCertAuthenticationMethod()); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + prepareCertAuthenticationMethod()); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - ClientCertificateAuthentication.createAuthenticationSteps(), - restTemplate); + ClientCertificateAuthentication.createAuthenticationSteps(), restTemplate); VaultToken login = executor.login(); @@ -62,14 +60,14 @@ class ClientCertificateAuthenticationStepsIntegrationTests @Test void authenticationStepsLoginShouldFail() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration()); - RestTemplate restTemplate = VaultClients.createRestTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, clientHttpRequestFactory); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + Settings.createSslConfiguration()); + RestTemplate restTemplate = VaultClients.createRestTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + clientHttpRequestFactory); - assertThatExceptionOfType(NestedRuntimeException.class) - .isThrownBy(() -> new AuthenticationStepsExecutor( - ClientCertificateAuthentication.createAuthenticationSteps(), + assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy( + () -> new AuthenticationStepsExecutor(ClientCertificateAuthentication.createAuthenticationSteps(), restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationUnitTests.java index e5f74cd6..adb36abf 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateAuthenticationUnitTests.java @@ -60,34 +60,32 @@ class ClientCertificateAuthenticationUnitTests { @Test void loginShouldObtainToken() { - mockRest.expect(requestTo("/auth/my/path/login")) - .andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + this.mockRest.expect(requestTo("/auth/my/path/login")).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); - ClientCertificateAuthenticationOptions options = ClientCertificateAuthenticationOptions - .builder().path("my/path").build(); + ClientCertificateAuthenticationOptions options = ClientCertificateAuthenticationOptions.builder() + .path("my/path").build(); - ClientCertificateAuthentication sut = new ClientCertificateAuthentication( - options, restTemplate); + ClientCertificateAuthentication sut = new ClientCertificateAuthentication(options, this.restTemplate); VaultToken login = sut.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); - assertThat(((LoginToken) login).getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(10)); + assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); } @Test void loginShouldFail() { - mockRest.expect(requestTo("/auth/cert/login")) // + this.mockRest.expect(requestTo("/auth/cert/login")) // .andRespond(withServerError()); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> new ClientCertificateAuthentication(restTemplate).login()); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> new ClientCertificateAuthentication(this.restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateNamespaceIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateNamespaceIntegrationTests.java index f3bf9153..21bec6b5 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateNamespaceIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ClientCertificateNamespaceIntegrationTests.java @@ -62,32 +62,28 @@ import static org.springframework.vault.util.Settings.findWorkDir; */ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport { - static final Policy POLICY = Policy.of(Policy.Rule.builder().path("/*") - .capabilities(Policy.BuiltinCapabilities.READ, - Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE) - .build()); + static final Policy POLICY = Policy + .of(Policy.Rule.builder().path("/*").capabilities(Policy.BuiltinCapabilities.READ, + Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE).build()); @BeforeEach void before() { - Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), - "Namespaces require enterprise version"); + Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), "Namespaces require enterprise version"); List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/")); List<String> list = prepare().getVaultOperations().list("sys/namespaces"); namespaces.removeAll(list); for (String namespace : namespaces) { - prepare().getVaultOperations() - .write("sys/namespaces/" + namespace.replaceAll("/", "")); + prepare().getVaultOperations().write("sys/namespaces/" + namespace.replaceAll("/", "")); } RestTemplateBuilder devRestTemplate = RestTemplateBuilder.builder() - .requestFactory(ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration())) - .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) - .customizers(restTemplate -> restTemplate.getInterceptors() - .add(VaultClients.createNamespaceInterceptor("dev"))); + .requestFactory( + ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration())) + .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate + .getInterceptors().add(VaultClients.createNamespaceInterceptor("dev"))); VaultTemplate dev = new VaultTemplate(devRestTemplate, new SimpleSessionManager(new TokenAuthentication(Settings.token()))); @@ -103,8 +99,7 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport File workDir = findWorkDir(); - String certificate = Files.contentOf( - new File(workDir, "ca/certs/client.cert.pem"), + String certificate = Files.contentOf(new File(workDir, "ca/certs/client.cert.pem"), StandardCharsets.US_ASCII); Map<String, String> role = new LinkedHashMap<>(); @@ -112,8 +107,7 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport role.put("policies", "relaxed"); role.put("certificate", certificate); - return restOperations.postForEntity("auth/cert/certs/relaxed", role, - Map.class); + return restOperations.postForEntity("auth/cert/certs/relaxed", role, Map.class); }); } @@ -124,67 +118,56 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport Map<String, VaultMount> mounts = vaultSysOperations.getMounts(); if (!mounts.containsKey(path + "/")) { - vaultSysOperations.mount(path, VaultMount.builder().type("kv") - .options(Collections.singletonMap("version", "1")).build()); + vaultSysOperations.mount(path, + VaultMount.builder().type("kv").options(Collections.singletonMap("version", "1")).build()); } } @Test void shouldAuthenticateWithNamespace() { - ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), - ClientCertificateAuthenticationIntegrationTestBase - .prepareCertAuthenticationMethod()); + ClientHttpRequestFactory clientHttpRequestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod()); RestTemplateBuilder builder = RestTemplateBuilder.builder() - .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) - .requestFactory(clientHttpRequestFactory) + .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).requestFactory(clientHttpRequestFactory) .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev"); RestTemplate forAuthentication = builder.build(); - ClientCertificateAuthentication authentication = new ClientCertificateAuthentication( - forAuthentication); + ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(forAuthentication); - VaultTemplate dev = new VaultTemplate(builder, - new SimpleSessionManager(authentication)); + VaultTemplate dev = new VaultTemplate(builder, new SimpleSessionManager(authentication)); dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")); - assertThat(dev.read("dev-secrets/my-secret").getRequiredData()) - .containsEntry("key", "dev"); + assertThat(dev.read("dev-secrets/my-secret").getRequiredData()).containsEntry("key", "dev"); } @Test void shouldAuthenticateReactiveWithNamespace() { - ClientHttpConnector connector = ClientHttpConnectorFactory.create( - new ClientOptions(), ClientCertificateAuthenticationIntegrationTestBase - .prepareCertAuthenticationMethod()); + ClientHttpConnector connector = ClientHttpConnectorFactory.create(new ClientOptions(), + ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod()); - WebClientBuilder builder = WebClientBuilder.builder() - .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) - .httpConnector(connector) - .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev"); + WebClientBuilder builder = WebClientBuilder.builder().endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) + .httpConnector(connector).defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev"); WebClient forAuthentication = builder.build(); - AuthenticationSteps steps = ClientCertificateAuthentication - .createAuthenticationSteps(); + AuthenticationSteps steps = ClientCertificateAuthentication.createAuthenticationSteps(); - AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, - forAuthentication); + AuthenticationStepsOperator operator = new AuthenticationStepsOperator(steps, forAuthentication); ReactiveVaultTemplate dev = new ReactiveVaultTemplate(builder, operator); - dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")) - .as(StepVerifier::create).verifyComplete(); + dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")).as(StepVerifier::create) + .verifyComplete(); - dev.read("dev-secrets/my-secret").as(StepVerifier::create) - .consumeNextWith(actual -> { + dev.read("dev-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> { - assertThat(actual.getRequiredData()).containsEntry("key", "dev"); - }).verifyComplete(); + assertThat(actual.getRequiredData()).containsEntry("key", "dev"); + }).verifyComplete(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTestBase.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTestBase.java index fe7cb1db..fb1c97f3 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTestBase.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTestBase.java @@ -38,15 +38,14 @@ abstract class CubbyholeAuthenticationIntegrationTestBase extends IntegrationTes Map<String, String> prepareWrappedToken() { - ResponseEntity<VaultResponse> response = prepare().getVaultOperations() - .doWithSession(restOperations -> { + ResponseEntity<VaultResponse> response = prepare().getVaultOperations().doWithSession(restOperations -> { - HttpHeaders headers = new HttpHeaders(); - headers.add("X-Vault-Wrap-TTL", "10m"); + HttpHeaders headers = new HttpHeaders(); + headers.add("X-Vault-Wrap-TTL", "10m"); - return restOperations.exchange("auth/token/create", HttpMethod.POST, - new HttpEntity<>(headers), VaultResponse.class); - }); + return restOperations.exchange("auth/token/create", HttpMethod.POST, new HttpEntity<>(headers), + VaultResponse.class); + }); Map<String, String> wrapInfo = response.getBody().getWrapInfo(); @@ -56,11 +55,11 @@ abstract class CubbyholeAuthenticationIntegrationTestBase extends IntegrationTes } UnwrappingEndpoints getUnwrappingEndpoints() { - return useSysWrapping() ? UnwrappingEndpoints.SysWrapping - : UnwrappingEndpoints.Cubbyhole; + return useSysWrapping() ? UnwrappingEndpoints.SysWrapping : UnwrappingEndpoints.Cubbyhole; } private boolean useSysWrapping() { return prepare().getVersion().isGreaterThanOrEqualTo(sysUnwrapSince); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTests.java index eddc134c..d23dfa65 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationIntegrationTests.java @@ -33,8 +33,7 @@ import static org.assertj.core.api.Assertions.fail; * * @author Mark Paluch */ -class CubbyholeAuthenticationIntegrationTests - extends CubbyholeAuthenticationIntegrationTestBase { +class CubbyholeAuthenticationIntegrationTests extends CubbyholeAuthenticationIntegrationTestBase { @Test void shouldCreateWrappedToken() { @@ -44,13 +43,11 @@ class CubbyholeAuthenticationIntegrationTests String initialToken = wrapInfo.get("token"); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .unwrappingEndpoints(getUnwrappingEndpoints()) - .initialToken(VaultToken.of(initialToken)).wrapped().build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + .unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped() + .build(); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restTemplate); VaultToken login = authentication.login(); assertThat(login.getToken()).doesNotContain(Settings.token().getToken()); } @@ -59,13 +56,10 @@ class CubbyholeAuthenticationIntegrationTests void loginShouldFail() { CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .unwrappingEndpoints(getUnwrappingEndpoints()) - .initialToken(VaultToken.of("Hello")).wrapped().build(); + .unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of("Hello")).wrapped().build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restTemplate); try { authentication.login(); @@ -75,4 +69,5 @@ class CubbyholeAuthenticationIntegrationTests assertThat(e).hasMessageContaining("Cannot login using Cubbyhole"); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationOperatorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationOperatorIntegrationTests.java index 0c5fe5df..5d2a610a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationOperatorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationOperatorIntegrationTests.java @@ -33,11 +33,9 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Mark Paluch */ -class CubbyholeAuthenticationOperatorIntegrationTests - extends CubbyholeAuthenticationIntegrationTestBase { +class CubbyholeAuthenticationOperatorIntegrationTests extends CubbyholeAuthenticationIntegrationTestBase { - private WebClient webClient = TestWebClientFactory - .create(Settings.createSslConfiguration()); + private WebClient webClient = TestWebClientFactory.create(Settings.createSslConfiguration()); @Test void authenticationStepsShouldCreateWrappedToken() { @@ -47,20 +45,20 @@ class CubbyholeAuthenticationOperatorIntegrationTests String initialToken = wrapInfo.get("token"); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .unwrappingEndpoints(getUnwrappingEndpoints()) - .initialToken(VaultToken.of(initialToken)).wrapped().build(); + .unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped() + .build(); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( - CubbyholeAuthentication.createAuthenticationSteps(options), webClient); + CubbyholeAuthentication.createAuthenticationSteps(options), this.webClient); operator.getVaultToken() // .as(StepVerifier::create) // .consumeNextWith(actual -> { - assertThat(actual).isNotEqualTo(Settings.token().getToken()) - .isNotNull(); + assertThat(actual).isNotEqualTo(Settings.token().getToken()).isNotNull(); }) // .verifyComplete(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationStepsIntegrationTests.java index d1e27f75..ca28f791 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationStepsIntegrationTests.java @@ -32,8 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Mark Paluch */ -class CubbyholeAuthenticationStepsIntegrationTests - extends CubbyholeAuthenticationIntegrationTestBase { +class CubbyholeAuthenticationStepsIntegrationTests extends CubbyholeAuthenticationIntegrationTestBase { @Test void authenticationStepsShouldCreateWrappedToken() { @@ -43,10 +42,9 @@ class CubbyholeAuthenticationStepsIntegrationTests String initialToken = wrapInfo.get("token"); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .unwrappingEndpoints(getUnwrappingEndpoints()) - .initialToken(VaultToken.of(initialToken)).wrapped().build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + .unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped() + .build(); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( CubbyholeAuthentication.createAuthenticationSteps(options), restTemplate); @@ -54,4 +52,5 @@ class CubbyholeAuthenticationStepsIntegrationTests VaultToken login = executor.login(); assertThat(login.getToken()).doesNotContain(Settings.token().getToken()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationUnitTests.java index cf3aae27..3780d08c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/CubbyholeAuthenticationUnitTests.java @@ -65,24 +65,19 @@ class CubbyholeAuthenticationUnitTests { void shouldLoginUsingCubbyholeLogin() throws Exception { String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"," - + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," - + "\"lease_duration\":0," + + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0," + "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }"; - mockRest.expect(requestTo("/cubbyhole/response")) - .andExpect(method(HttpMethod.GET)) + this.mockRest.expect(requestTo("/cubbyhole/response")).andExpect(method(HttpMethod.GET)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\":{\"response\":" - + OBJECT_MAPPER.writeValueAsString(wrappedResponse) - + "} }")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .initialToken(VaultToken.of("hello")) - .unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).wrapped().build(); + .initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).wrapped() + .build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -98,22 +93,18 @@ class CubbyholeAuthenticationUnitTests { void shouldLoginUsingWrappedLogin() { String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"," - + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," - + "\"lease_duration\":0," + + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0," + "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }"; - mockRest.expect(requestTo("/sys/wrapping/unwrap")) - .andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body(wrappedResponse)); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse)); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .initialToken(VaultToken.of("hello")) - .unwrappingEndpoints(UnwrappingEndpoints.SysWrapping).wrapped().build(); + .initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.SysWrapping).wrapped() + .build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -129,29 +120,22 @@ class CubbyholeAuthenticationUnitTests { void shouldLoginUsingWrappedLoginWithSelfLookup() { String wrappedResponse = "{\"request_id\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"," - + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," - + "\"lease_duration\":10," + + "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":10," + "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }"; - mockRest.expect(requestTo("/sys/wrapping/unwrap")) - .andExpect(method(HttpMethod.POST)) + this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body(wrappedResponse)); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse)); - mockRest.expect(requestTo("/auth/token/lookup-self")) - .andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, - "5e6332cf-f003-6369-8cba-5bce2330f6cc")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" - + " \"renewable\": false,\n" + " \"ttl\": 456} }")); + this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET)) + .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n" + + " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n" + " \"ttl\": 456} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() .initialToken(VaultToken.of("hello")).wrapped().build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -166,17 +150,15 @@ class CubbyholeAuthenticationUnitTests { @Test void shouldLoginUsingStoredLogin() { - mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) + this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( - "{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) + .body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() - .initialToken(VaultToken.of("hello")).path("cubbyhole/token") - .selfLookup(false).build(); + .initialToken(VaultToken.of("hello")).path("cubbyhole/token").selfLookup(false).build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -187,24 +169,20 @@ class CubbyholeAuthenticationUnitTests { @Test void shouldRetrieveRenewabilityUsingStoredLogin() { - mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) + this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( - "{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }")); - - mockRest.expect(requestTo("/auth/token/lookup-self")) - .andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, - "058222ef-9ab9-ff39-f087-9d5bee64e46d")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" - + " \"renewable\": true,\n" + " \"ttl\": 456} }")); + .body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }")); + + this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET)) + .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "058222ef-9ab9-ff39-f087-9d5bee64e46d")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n" + + " \"creation_ttl\": 600,\n" + " \"renewable\": true,\n" + " \"ttl\": 456} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() .initialToken(VaultToken.of("hello")).path("cubbyhole/token").build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -219,16 +197,14 @@ class CubbyholeAuthenticationUnitTests { @Test void shouldFailUsingStoredLoginNoData() { - mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) + this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\":{} }")); + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\":{} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() .initialToken(VaultToken.of("hello")).path("cubbyhole/token").build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); try { authentication.login(); @@ -242,16 +218,14 @@ class CubbyholeAuthenticationUnitTests { @Test void shouldFailUsingStoredMultipleEntries() { - mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\":{\"key1\":1, \"key2\":2} }")); + this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET)) + .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")).andRespond(withSuccess() + .contentType(MediaType.APPLICATION_JSON).body("{\"data\":{\"key1\":1, \"key2\":2} }")); CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() .initialToken(VaultToken.of("hello")).path("cubbyhole/token").build(); - CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, - restTemplate); + CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate); try { authentication.login(); @@ -261,4 +235,5 @@ class CubbyholeAuthenticationUnitTests { assertThat(e).hasMessageContaining("does not contain an unique token"); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpComputeAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpComputeAuthenticationUnitTests.java index e038f1d0..945a7a4b 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpComputeAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpComputeAuthenticationUnitTests.java @@ -54,17 +54,16 @@ class GcpComputeAuthenticationUnitTests { private void setupMocks() { - mockRest.expect(requestTo( + this.mockRest.expect(requestTo( "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://localhost:8200/vault/dev-role&format=full")) - .andExpect(method(HttpMethod.GET)).andRespond( - withSuccess().contentType(MediaType.TEXT_PLAIN).body("my-jwt")); + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("my-jwt")); - mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("dev-role")) - .andExpect(jsonPath("$.jwt").value("my-jwt")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); } @Test @@ -72,11 +71,9 @@ class GcpComputeAuthenticationUnitTests { setupMocks(); - GcpComputeAuthenticationOptions options = GcpComputeAuthenticationOptions - .builder().role("dev-role").build(); + GcpComputeAuthenticationOptions options = GcpComputeAuthenticationOptions.builder().role("dev-role").build(); - GcpComputeAuthentication authentication = new GcpComputeAuthentication(options, - restTemplate); + GcpComputeAuthentication authentication = new GcpComputeAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); @@ -93,14 +90,12 @@ class GcpComputeAuthenticationUnitTests { setupMocks(); - GcpComputeAuthenticationOptions options = GcpComputeAuthenticationOptions - .builder().role("dev-role").build(); + GcpComputeAuthenticationOptions options = GcpComputeAuthenticationOptions.builder().role("dev-role").build(); - GcpComputeAuthentication authentication = new GcpComputeAuthentication(options, - restTemplate); + GcpComputeAuthentication authentication = new GcpComputeAuthentication(options, this.restTemplate); - AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - authentication.getAuthenticationSteps(), restTemplate); + AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(authentication.getAuthenticationSteps(), + this.restTemplate); VaultToken login = executor.login(); @@ -111,4 +106,5 @@ class GcpComputeAuthenticationUnitTests { assertThat(loginToken.isRenewable()).isTrue(); assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationOptionsBuilderUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationOptionsBuilderUnitTests.java index b00ef0e3..19782cb7 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationOptionsBuilderUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationOptionsBuilderUnitTests.java @@ -35,11 +35,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential).role("foo").build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential).role("foo") + .build(); - assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)) - .isEqualTo("hello@world"); + assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("hello@world"); } @Test @@ -47,12 +46,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential).serviceAccountId("override@foo.com").role("foo") - .build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential) + .serviceAccountId("override@foo.com").role("foo").build(); - assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)) - .isEqualTo("override@foo.com"); + assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com"); } @Test @@ -60,14 +57,11 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential) - .serviceAccountIdAccessor( - (GoogleCredential googleCredential) -> "override@foo.com") - .role("foo").build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential) + .serviceAccountIdAccessor((GoogleCredential googleCredential) -> "override@foo.com").role("foo") + .build(); - assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)) - .isEqualTo("override@foo.com"); + assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com"); } @Test @@ -75,11 +69,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential).role("foo").build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential).role("foo") + .build(); - assertThat(options.getProjectIdAccessor().getProjectId(credential)) - .isEqualTo("project-id"); + assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("project-id"); } @Test @@ -87,11 +80,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential).projectId("my-project").role("foo").build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential) + .projectId("my-project").role("foo").build(); - assertThat(options.getProjectIdAccessor().getProjectId(credential)) - .isEqualTo("my-project"); + assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("my-project"); } @Test @@ -99,25 +91,21 @@ class GcpIamAuthenticationOptionsBuilderUnitTests { GoogleCredential credential = createGoogleCredential(); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .credential(credential) - .projectIdAccessor((GoogleCredential googleCredential) -> "my-project") - .role("foo").build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential) + .projectIdAccessor((GoogleCredential googleCredential) -> "my-project").role("foo").build(); - assertThat(options.getProjectIdAccessor().getProjectId(credential)) - .isEqualTo("my-project"); + assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("my-project"); } private static GoogleCredential createGoogleCredential() { - GoogleCredential credential = new GoogleCredential.Builder() - .setServiceAccountId("hello@world") - .setServiceAccountProjectId("project-id") - .setServiceAccountPrivateKey(mock(PrivateKey.class)) + GoogleCredential credential = new GoogleCredential.Builder().setServiceAccountId("hello@world") + .setServiceAccountProjectId("project-id").setServiceAccountPrivateKey(mock(PrivateKey.class)) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); return credential; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationUnitTests.java index dfe0db71..c8fc1da1 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/GcpIamAuthenticationUnitTests.java @@ -71,27 +71,24 @@ class GcpIamAuthenticationUnitTests { response.setStatusCode(200); response.setContent("{\"keyId\":\"keyid\", \"signedJwt\":\"my-jwt\"}"); - mockHttpTransport = new MockHttpTransport.Builder() - .setLowLevelHttpResponse(response).build(); + this.mockHttpTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(response).build(); - mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("dev-role")) - .andExpect(jsonPath("$.jwt").value("my-jwt")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" - + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" - + "}")); + this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( + "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + + "}")); PrivateKey privateKeyMock = mock(PrivateKey.class); GoogleCredential credential = new Builder().setServiceAccountId("hello@world") - .setServiceAccountProjectId("foobar") - .setServiceAccountPrivateKey(privateKeyMock) + .setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .role("dev-role").credential(credential).build(); - GcpIamAuthentication authentication = new GcpIamAuthentication(options, - restTemplate, mockHttpTransport); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role") + .credential(credential).build(); + GcpIamAuthentication authentication = new GcpIamAuthentication(options, this.restTemplate, + this.mockHttpTransport); VaultToken login = authentication.login(); @@ -104,19 +101,18 @@ class GcpIamAuthenticationUnitTests { } @Test - void shouldCreateNewGcpIamObjectInstance() - throws GeneralSecurityException, IOException { + void shouldCreateNewGcpIamObjectInstance() throws GeneralSecurityException, IOException { PrivateKey privateKeyMock = mock(PrivateKey.class); GoogleCredential credential = new Builder().setServiceAccountId("hello@world") - .setServiceAccountProjectId("foobar") - .setServiceAccountPrivateKey(privateKeyMock) + .setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); - GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder() - .role("dev-role").credential(credential).build(); + GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role") + .credential(credential).build(); - new GcpIamAuthentication(options, restTemplate); + new GcpIamAuthentication(options, this.restTemplate); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/IpAddressUserIdTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/IpAddressUserIdTests.java index f20feec8..49e4c77b 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/IpAddressUserIdTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/IpAddressUserIdTests.java @@ -33,7 +33,7 @@ class IpAddressUserIdTests { String userId = new IpAddressUserId().createUserId(); - assertThat(userId).matches(Pattern.compile("[0-9A-F]+")) - .doesNotMatch(Pattern.compile("[a-f]")); + assertThat(userId).matches(Pattern.compile("[0-9A-F]+")).doesNotMatch(Pattern.compile("[a-f]")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubeServiceAccountTokenFileUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubeServiceAccountTokenFileUnitTests.java index 40cfd208..925b23f4 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubeServiceAccountTokenFileUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubeServiceAccountTokenFileUnitTests.java @@ -36,20 +36,17 @@ class KubeServiceAccountTokenFileUnitTests { + "9rZW4tNHcydmciLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZp" + "Y2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2Vydm" + "ljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjllMjQzNWY0LTgxNDctMT" - + "FlNy05MGFiLTA4MDAyN2NlZTQwNyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3" - + "VudDpkZWZhdWx0OmRlZmF1bHQifQ." + + "FlNy05MGFiLTA4MDAyN2NlZTQwNyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3" + "VudDpkZWZhdWx0OmRlZmF1bHQifQ." + "asFRZRZ1gRj9sF0lQqbbxrNhW_lOdj9WjqUpH_4TstxqZZ7B36a0xKKXg6XaFW" + "JY1eMsytpwa7uMzvsvf2pYCcklinaSE_F-wc42IOWcpwSLl4PND92Tp7n_JYEAbb" + "SQVfZPzQ2Y7b6cWu6NRzDs638LwVTqYeWMWbcWlOMaTxjMzGTcgDe5RWslkKUPkY" + "svPOAFtt5ZErwtVcvTUmplJfHzdWwatlpZRQhYkxGgRIJ6LabXfZOd2N_TchJ3tH" - + "jAVBzUDTQq3APQssGb9df2RxVTUiyzbhdRGt7129-LCZ8rZYE7E-Mr3SSpExGYcD" - + "k-v0It8hky0CKtCLs2UHiABA"; + + "jAVBzUDTQq3APQssGb9df2RxVTUiyzbhdRGt7129-LCZ8rZYE7E-Mr3SSpExGYcD" + "k-v0It8hky0CKtCLs2UHiABA"; @Test void shouldGetJwtTokenFromResource() { - String jwt = new KubernetesServiceAccountTokenFile( - new ClassPathResource("kube-jwt-token")).get(); + String jwt = new KubernetesServiceAccountTokenFile(new ClassPathResource("kube-jwt-token")).get(); assertThat(jwt).isEqualTo(TEST_TOKEN); } @@ -57,9 +54,9 @@ class KubeServiceAccountTokenFileUnitTests { @Test void shouldGetJwtTokenFromFile() throws Exception { - String fileName = new ClassPathResource("kube-jwt-token").getFile() - .getAbsolutePath(); + String fileName = new ClassPathResource("kube-jwt-token").getFile().getAbsolutePath(); String jwt = new KubernetesServiceAccountTokenFile(fileName).get(); assertThat(jwt).isEqualTo(TEST_TOKEN); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTestBase.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTestBase.java index 59650225..6e0530b5 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTestBase.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTestBase.java @@ -37,8 +37,7 @@ import static org.springframework.vault.util.Settings.findWorkDir; * @author Michal Budzyn */ @RequiresVaultVersion("0.8.3") -public abstract class KubernetesAuthenticationIntegrationTestBase - extends IntegrationTestSupport { +public abstract class KubernetesAuthenticationIntegrationTestBase extends IntegrationTestSupport { @BeforeEach public void before() { @@ -50,30 +49,26 @@ public abstract class KubernetesAuthenticationIntegrationTestBase prepare().mountAuth("kubernetes"); } - prepare().getVaultOperations() - .doWithSession((RestOperationsCallback<Object>) restOperations -> { - File workDir = findWorkDir(); + prepare().getVaultOperations().doWithSession((RestOperationsCallback<Object>) restOperations -> { + File workDir = findWorkDir(); - String certificate = Files.contentOf( - new File(workDir, "minikube/ca.crt"), - StandardCharsets.US_ASCII); + String certificate = Files.contentOf(new File(workDir, "minikube/ca.crt"), StandardCharsets.US_ASCII); - String host = String.format("https://%s:8443", minikubeIp); + String host = String.format("https://%s:8443", minikubeIp); - Map<String, String> kubeConfig = new HashMap<>(); - kubeConfig.put("kubernetes_ca_cert", certificate); - kubeConfig.put("kubernetes_host", host); - restOperations.postForEntity("auth/kubernetes/config", kubeConfig, - Map.class); + Map<String, String> kubeConfig = new HashMap<>(); + kubeConfig.put("kubernetes_ca_cert", certificate); + kubeConfig.put("kubernetes_host", host); + restOperations.postForEntity("auth/kubernetes/config", kubeConfig, Map.class); - Map<String, String> roleData = new HashMap<>(); - roleData.put("bound_service_account_names", "default"); - roleData.put("bound_service_account_namespaces", "default"); - roleData.put("policies", "default"); - roleData.put("ttl", "1h"); + Map<String, String> roleData = new HashMap<>(); + roleData.put("bound_service_account_names", "default"); + roleData.put("bound_service_account_namespaces", "default"); + roleData.put("policies", "default"); + roleData.put("ttl", "1h"); - return restOperations.postForEntity("auth/kubernetes/role/my-role", - roleData, Map.class); - }); + return restOperations.postForEntity("auth/kubernetes/role/my-role", roleData, Map.class); + }); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTests.java index 8f959039..14973a90 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationIntegrationTests.java @@ -35,23 +35,19 @@ import static org.springframework.vault.util.Settings.findWorkDir; * * @author Michal Budzyn */ -class KubernetesAuthenticationIntegrationTests - extends KubernetesAuthenticationIntegrationTestBase { +class KubernetesAuthenticationIntegrationTests extends KubernetesAuthenticationIntegrationTestBase { @Test void shouldLoginSuccessfully() { File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token"); - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("my-role") + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role") .jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); - KubernetesAuthentication authentication = new KubernetesAuthentication(options, - restTemplate); + KubernetesAuthentication authentication = new KubernetesAuthentication(options, restTemplate); VaultToken login = authentication.login(); assertThat(login.getToken()).isNotEmpty(); @@ -62,15 +58,13 @@ class KubernetesAuthenticationIntegrationTests File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token"); - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("wrong") + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("wrong") .jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> new KubernetesAuthentication(options, restTemplate).login()); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login()); } @Test @@ -78,15 +72,13 @@ class KubernetesAuthenticationIntegrationTests ClassPathResource tokenResource = new ClassPathResource("kube-jwt-token"); - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("my-role") - .jwtSupplier(new KubernetesServiceAccountTokenFile(tokenResource)) - .build(); + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role") + .jwtSupplier(new KubernetesServiceAccountTokenFile(tokenResource)).build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> new KubernetesAuthentication(options, restTemplate).login()); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationStepsIntegrationTests.java index 59a09847..7b1c1e9a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationStepsIntegrationTests.java @@ -33,26 +33,23 @@ import static org.springframework.vault.util.Settings.findWorkDir; * * @author Mark Paluch */ -class KubernetesAuthenticationStepsIntegrationTests - extends KubernetesAuthenticationIntegrationTestBase { +class KubernetesAuthenticationStepsIntegrationTests extends KubernetesAuthenticationIntegrationTestBase { @Test void shouldLoginSuccessfully() { File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token"); - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("my-role") + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role") .jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build(); - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( - KubernetesAuthentication.createAuthenticationSteps(options), - restTemplate); + KubernetesAuthentication.createAuthenticationSteps(options), restTemplate); VaultToken login = executor.login(); assertThat(login.getToken()).doesNotContain(Settings.token().getToken()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationUnitTests.java index 5dcd531e..281e3ab0 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/KubernetesAuthenticationUnitTests.java @@ -61,19 +61,15 @@ class KubernetesAuthenticationUnitTests { @Test void loginShouldObtainTokenWithStaticJwtSupplier() { - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("hello") // + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello") // .jwtSupplier(() -> "my-jwt-token").build(); - mockRest.expect(requestTo("/auth/kubernetes/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("hello")) - .andExpect(jsonPath("$.jwt").value("my-jwt-token")) + this.mockRest.expect(requestTo("/auth/kubernetes/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("hello")).andExpect(jsonPath("$.jwt").value("my-jwt-token")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); - KubernetesAuthentication authentication = new KubernetesAuthentication(options, - restTemplate); + KubernetesAuthentication authentication = new KubernetesAuthentication(options, this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -83,36 +79,33 @@ class KubernetesAuthenticationUnitTests { @Test void loginShouldFail() { - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("hello").jwtSupplier(() -> "my-jwt-token").build(); + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello") + .jwtSupplier(() -> "my-jwt-token").build(); - mockRest.expect(requestTo("/auth/kubernetes/login")) // + this.mockRest.expect(requestTo("/auth/kubernetes/login")) // .andRespond(withServerError()); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> new KubernetesAuthentication(options, restTemplate).login()); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> new KubernetesAuthentication(options, this.restTemplate).login()); } @Test void shouldReuseCachedToken() { AtomicReference<String> token = new AtomicReference<>("foo"); - KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions - .builder().role("hello") // + KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello") // .jwtSupplier(((KubernetesJwtSupplier) token::get).cached()).build(); token.set("bar"); - mockRest.expect(requestTo("/auth/kubernetes/login")) - .andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("hello")) - .andExpect(jsonPath("$.jwt").value("foo")) + this.mockRest.expect(requestTo("/auth/kubernetes/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("hello")).andExpect(jsonPath("$.jwt").value("foo")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); - KubernetesAuthentication authentication = new KubernetesAuthentication(options, - restTemplate); + KubernetesAuthentication authentication = new KubernetesAuthentication(options, this.restTemplate); authentication.login(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerIntegrationTests.java index fe97c4d4..5300aa01 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerIntegrationTests.java @@ -46,12 +46,12 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor @BeforeEach void before() { - taskScheduler.afterPropertiesSet(); + this.taskScheduler.afterPropertiesSet(); } @AfterEach void tearDown() { - taskScheduler.destroy(); + this.taskScheduler.destroy(); } @Test @@ -60,8 +60,8 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor LoginToken loginToken = createLoginToken(); TokenAuthentication tokenAuthentication = new TokenAuthentication(loginToken); - LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager( - tokenAuthentication, taskScheduler, prepare().getRestTemplate()); + LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager(tokenAuthentication, + this.taskScheduler, prepare().getRestTemplate()); assertThat(sessionManager.getSessionToken()).isSameAs(loginToken); } @@ -70,8 +70,7 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor @Test void shouldRenewToken() { - VaultTokenOperations tokenOperations = prepare().getVaultOperations() - .opsForToken(); + VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken(); VaultTokenRequest tokenRequest = VaultTokenRequest.builder() // .renewable().ttl(1, TimeUnit.HOURS) // @@ -84,8 +83,8 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor LoginToken.renewable(token.getToken().toCharArray(), Duration.ZERO)); final AtomicInteger counter = new AtomicInteger(); - LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager( - tokenAuthentication, taskScheduler, prepare().getRestTemplate()) { + LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager(tokenAuthentication, + this.taskScheduler, prepare().getRestTemplate()) { @Override public VaultToken getSessionToken() { @@ -106,8 +105,8 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor final LoginToken loginToken = createLoginToken(); TokenAuthentication tokenAuthentication = new TokenAuthentication(loginToken); - LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager( - tokenAuthentication, taskScheduler, prepare().getRestTemplate()); + LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager(tokenAuthentication, + this.taskScheduler, prepare().getRestTemplate()); sessionManager.getSessionToken(); sessionManager.destroy(); @@ -115,14 +114,12 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor prepare().getVaultOperations().doWithSession(restOperations -> { try { - restOperations.getForEntity("auth/token/lookup/{token}", Map.class, - loginToken.toCharArray()); + restOperations.getForEntity("auth/token/lookup/{token}", Map.class, loginToken.toCharArray()); fail("Missing HttpStatusCodeException"); } catch (HttpStatusCodeException e) { // Compatibility across Vault versions. - assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, - HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); + assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); } return null; @@ -131,10 +128,10 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor private LoginToken createLoginToken() { - VaultTokenOperations tokenOperations = prepare().getVaultOperations() - .opsForToken(); + VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken(); VaultToken token = tokenOperations.createOrphan().getToken(); return LoginToken.of(token.getToken()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupportUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupportUnitTests.java index e5d6ced1..58ce003d 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupportUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerSupportUnitTests.java @@ -35,26 +35,21 @@ class LifecycleAwareSessionManagerSupportUnitTests { @Test void shouldScheduleNextExecutionTimeCorrectly() { - FixedTimeoutRefreshTrigger trigger = new FixedTimeoutRefreshTrigger(5, - TimeUnit.SECONDS); + FixedTimeoutRefreshTrigger trigger = new FixedTimeoutRefreshTrigger(5, TimeUnit.SECONDS); - Date nextExecutionTime = trigger.nextExecutionTime( - LoginToken.of("foo".toCharArray(), Duration.ofMinutes(1))); - assertThat(nextExecutionTime).isBetween( - new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(52)), + Date nextExecutionTime = trigger.nextExecutionTime(LoginToken.of("foo".toCharArray(), Duration.ofMinutes(1))); + assertThat(nextExecutionTime).isBetween(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(52)), new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(56))); } @Test void shouldScheduleNextExecutionIfValidityLessThanTimeout() { - FixedTimeoutRefreshTrigger trigger = new FixedTimeoutRefreshTrigger(5, - TimeUnit.SECONDS); + FixedTimeoutRefreshTrigger trigger = new FixedTimeoutRefreshTrigger(5, TimeUnit.SECONDS); - Date nextExecutionTime = trigger.nextExecutionTime( - LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))); - assertThat(nextExecutionTime).isBetween( - new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(0)), + Date nextExecutionTime = trigger.nextExecutionTime(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))); + assertThat(nextExecutionTime).isBetween(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(0)), new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(2))); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerUnitTests.java index ec5e2afc..aade9a56 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LifecycleAwareSessionManagerUnitTests.java @@ -98,30 +98,29 @@ class LifecycleAwareSessionManagerUnitTests { @BeforeEach void before() { - sessionManager = new LifecycleAwareSessionManager(clientAuthentication, - taskScheduler, restOperations); - sessionManager.addAuthenticationListener(listener); - sessionManager.addErrorListener(errorListener); + this.sessionManager = new LifecycleAwareSessionManager(this.clientAuthentication, this.taskScheduler, + this.restOperations); + this.sessionManager.addAuthenticationListener(this.listener); + this.sessionManager.addErrorListener(this.errorListener); } @Test void shouldObtainTokenFromClientAuthentication() { - when(clientAuthentication.login()).thenReturn(LoginToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login")); - assertThat(sessionManager.getSessionToken()).isEqualTo(LoginToken.of("login")); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + assertThat(this.sessionManager.getSessionToken()).isEqualTo(LoginToken.of("login")); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); } @Test void loginShouldFail() { - when(clientAuthentication.login()).thenThrow(new VaultLoginException("foo")); + when(this.clientAuthentication.login()).thenThrow(new VaultLoginException("foo")); - assertThatExceptionOfType(VaultLoginException.class) - .isThrownBy(() -> sessionManager.getSessionToken()); - verifyZeroInteractions(listener); - verify(errorListener).onAuthenticationError(any(LoginFailedEvent.class)); + assertThatExceptionOfType(VaultLoginException.class).isThrownBy(() -> this.sessionManager.getSessionToken()); + verifyZeroInteractions(this.listener); + verify(this.errorListener).onAuthenticationError(any(LoginFailedEvent.class)); } @Test @@ -131,21 +130,19 @@ class LifecycleAwareSessionManagerUnitTests { VaultResponse vaultResponse = new VaultResponse(); vaultResponse.setData(Collections.singletonMap("ttl", 100)); - when(clientAuthentication.login()).thenReturn(VaultToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login")); - when(restOperations.exchange(anyString(), any(), any(), - ArgumentMatchers.<Class> any())) - .thenReturn(new ResponseEntity<>(vaultResponse, HttpStatus.OK)); + when(this.restOperations.exchange(anyString(), any(), any(), ArgumentMatchers.<Class>any())) + .thenReturn(new ResponseEntity<>(vaultResponse, HttpStatus.OK)); - LoginToken sessionToken = (LoginToken) sessionManager.getSessionToken(); + LoginToken sessionToken = (LoginToken) this.sessionManager.getSessionToken(); assertThat(sessionToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(100)); - verify(restOperations).exchange(eq("auth/token/lookup-self"), eq(HttpMethod.GET), - eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), - any(Class.class)); + verify(this.restOperations).exchange(eq("auth/token/lookup-self"), eq(HttpMethod.GET), + eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class)); - verify(listener).onAuthenticationEvent(captor.capture()); - AfterLoginEvent event = (AfterLoginEvent) captor.getValue(); + verify(this.listener).onAuthenticationEvent(this.captor.capture()); + AfterLoginEvent event = (AfterLoginEvent) this.captor.getValue(); assertThat(event.getSource()).isSameAs(sessionToken); } @@ -156,35 +153,32 @@ class LifecycleAwareSessionManagerUnitTests { VaultResponse vaultResponse = new VaultResponse(); vaultResponse.setData(Collections.singletonMap("ttl", 100)); - when(clientAuthentication.login()).thenReturn(VaultToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login")); - when(restOperations.exchange(anyString(), any(), any(), - ArgumentMatchers.<Class> any())) - .thenThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN)); + when(this.restOperations.exchange(anyString(), any(), any(), ArgumentMatchers.<Class>any())) + .thenThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN)); - VaultToken sessionToken = sessionManager.getSessionToken(); + VaultToken sessionToken = this.sessionManager.getSessionToken(); assertThat(sessionToken).isExactlyInstanceOf(VaultToken.class); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); - verify(errorListener).onAuthenticationError(any()); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.errorListener).onAuthenticationError(any()); } @Test void shouldTranslateExceptionOnTokenRenewal() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofMinutes(5))); - when(restOperations.postForObject(anyString(), any(HttpEntity.class), any())) - .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, - "Some server error")); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofMinutes(5))); + when(this.restOperations.postForObject(anyString(), any(HttpEntity.class), any())) + .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Some server error")); AtomicReference<AuthenticationErrorEvent> listener = new AtomicReference<>(); - sessionManager.addErrorListener(listener::set); + this.sessionManager.addErrorListener(listener::set); - sessionManager.getSessionToken(); - sessionManager.renewToken(); + this.sessionManager.getSessionToken(); + this.sessionManager.renewToken(); - assertThat(listener.get().getException()) - .isInstanceOf(VaultTokenRenewalException.class) + assertThat(listener.get().getException()).isInstanceOf(VaultTokenRenewalException.class) .hasCauseInstanceOf(HttpServerErrorException.class) .hasMessageContaining("Cannot renew token: Status 500 Some server error"); } @@ -193,210 +187,200 @@ class LifecycleAwareSessionManagerUnitTests { @SuppressWarnings("unchecked") void shouldRevokeLoginTokenOnDestroy() { - when(clientAuthentication.login()).thenReturn(LoginToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login")); - sessionManager.renewToken(); - sessionManager.destroy(); + this.sessionManager.renewToken(); + this.sessionManager.destroy(); - verify(restOperations).postForObject(eq("auth/token/revoke-self"), - eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), - any(Class.class)); + verify(this.restOperations).postForObject(eq("auth/token/revoke-self"), + eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class)); - verify(listener) - .onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); - verify(listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class)); + verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class)); } @Test void shouldNotRevokeRegularTokenOnDestroy() { - when(clientAuthentication.login()).thenReturn(VaultToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login")); - sessionManager.setTokenSelfLookupEnabled(false); - sessionManager.renewToken(); - sessionManager.destroy(); + this.sessionManager.setTokenSelfLookupEnabled(false); + this.sessionManager.renewToken(); + this.sessionManager.destroy(); - verifyZeroInteractions(restOperations); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); - verifyNoMoreInteractions(listener); + verifyZeroInteractions(this.restOperations); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verifyNoMoreInteractions(this.listener); } @Test @SuppressWarnings("unchecked") void shouldNotThrowExceptionsOnRevokeErrors() { - when(clientAuthentication.login()).thenReturn(LoginToken.of("login")); + when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login")); - when(restOperations.postForObject(anyString(), any(), - ArgumentMatchers.<Class> any())).thenThrow( - new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); + when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any())) + .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); - sessionManager.renewToken(); - sessionManager.destroy(); + this.sessionManager.renewToken(); + this.sessionManager.destroy(); - verify(restOperations).postForObject(eq("auth/token/revoke-self"), - eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), - any(Class.class)); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); - verify(listener) - .onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); - verifyNoMoreInteractions(listener); - verify(errorListener) - .onAuthenticationError(any(LoginTokenRevocationFailedEvent.class)); + verify(this.restOperations).postForObject(eq("auth/token/revoke-self"), + eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); + verifyNoMoreInteractions(this.listener); + verify(this.errorListener).onAuthenticationError(any(LoginTokenRevocationFailedEvent.class)); } @Test void shouldScheduleTokenRenewal() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - sessionManager.getSessionToken(); + this.sessionManager.getSessionToken(); - verify(taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); } @Test @SuppressWarnings("unchecked") void shouldRunTokenRenewal() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) - .thenReturn(fromToken( - LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + .thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(restOperations).postForObject(eq("auth/token/renew-self"), - eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken - .renewable("login".toCharArray(), Duration.ofSeconds(5))))), + verify(this.restOperations).postForObject(eq("auth/token/renew-self"), + eq(new HttpEntity<>( + VaultHttpHeaders.from(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))))), any(Class.class)); - verify(clientAuthentication, times(1)).login(); - verify(listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class)); - verify(listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class)); + verify(this.clientAuthentication, times(1)).login(); + verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class)); } @Test void shouldReScheduleTokenRenewalAfterSuccessfulRenewal() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) - .thenReturn(fromToken( - LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + .thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class)); } @Test void shouldNotScheduleRenewalIfRenewalTtlExceedsThreshold() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) - .thenReturn(fromToken( - LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + .thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); } @Test void shouldReLoginIfRenewalTtlExceedsThreshold() { - when(clientAuthentication.login()).thenReturn( + when(this.clientAuthentication.login()).thenReturn( LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)), LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) - .thenReturn(fromToken( - LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))); + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + .thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - assertThat(sessionManager.getSessionToken()).isEqualTo( - LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); + assertThat(this.sessionManager.getSessionToken()) + .isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); - verify(clientAuthentication, times(2)).login(); - verify(listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class)); - verify(listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class)); + verify(this.clientAuthentication, times(2)).login(); + verify(this.listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class)); } @Test void shouldReLoginIfRenewalFails() { - when(clientAuthentication.login()).thenReturn( + when(this.clientAuthentication.login()).thenReturn( LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)), LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) .thenThrow(new ResourceAccessException("Connection refused")); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - assertThat(sessionManager.getSessionToken()).isEqualTo( - LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); + assertThat(this.sessionManager.getSessionToken()) + .isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); - verify(clientAuthentication, times(2)).login(); + verify(this.clientAuthentication, times(2)).login(); } @Test void shouldRetainTokenAfterRenewalFailure() { - when(clientAuthentication.login()).thenReturn( + when(this.clientAuthentication.login()).thenReturn( LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)), LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) + when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class))) .thenThrow(new ResourceAccessException("Connection refused")); - sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError()); + this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError()); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - assertThat(sessionManager.getSessionToken()).isEqualTo( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + assertThat(this.sessionManager.getSessionToken()) + .isEqualTo(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - verify(clientAuthentication).login(); + verify(this.clientAuthentication).login(); } @Test void shouldUseTaskScheduler() { - sessionManager = new LifecycleAwareSessionManager(clientAuthentication, - taskScheduler, restOperations); + this.sessionManager = new LifecycleAwareSessionManager(this.clientAuthentication, this.taskScheduler, + this.restOperations); - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); ArgumentCaptor<Trigger> triggerCaptor = ArgumentCaptor.forClass(Trigger.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(any(Runnable.class), triggerCaptor.capture()); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(any(Runnable.class), triggerCaptor.capture()); assertThat(triggerCaptor.getValue().nextExecutionTime(null)).isNotNull(); assertThat(triggerCaptor.getValue().nextExecutionTime(null)).isNull(); @@ -406,49 +390,47 @@ class LifecycleAwareSessionManagerUnitTests { @SuppressWarnings("unchecked") void shouldNotReScheduleTokenRenewalAfterFailedRenewal() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), any(), - ArgumentMatchers.<Class> any())).thenThrow( - new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any())) + .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); } @Test void shouldObtainTokenIfNoTokenAvailable() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - sessionManager.renewToken(); + this.sessionManager.renewToken(); - assertThat(sessionManager.getSessionToken()).isEqualTo( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - verify(clientAuthentication, times(1)).login(); + assertThat(this.sessionManager.getSessionToken()) + .isEqualTo(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + verify(this.clientAuthentication, times(1)).login(); } @Test @SuppressWarnings("unchecked") void renewShouldReportFalseIfTokenRenewalFails() { - when(clientAuthentication.login()).thenReturn( - LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(restOperations.postForObject(anyString(), ArgumentMatchers.any(), - ArgumentMatchers.<Class> any())) - .thenThrow(new HttpServerErrorException(HttpStatus.BAD_REQUEST)); + when(this.clientAuthentication.login()) + .thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); + when(this.restOperations.postForObject(anyString(), ArgumentMatchers.any(), ArgumentMatchers.<Class>any())) + .thenThrow(new HttpServerErrorException(HttpStatus.BAD_REQUEST)); - sessionManager.getSessionToken(); + this.sessionManager.getSessionToken(); - assertThat(sessionManager.renewToken()).isFalse(); - verify(clientAuthentication, times(1)).login(); + assertThat(this.sessionManager.renewToken()).isFalse(); + verify(this.clientAuthentication, times(1)).login(); } private static VaultResponse fromToken(LoginToken loginToken) { @@ -464,4 +446,5 @@ class LifecycleAwareSessionManagerUnitTests { return response; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenAdapterUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenAdapterUnitTests.java index d92609aa..744b6837 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenAdapterUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenAdapterUnitTests.java @@ -56,17 +56,13 @@ class LoginTokenAdapterUnitTests { @Test void shouldSelfLookupToken() throws Exception { - mockRest.expect(requestTo("/auth/token/lookup-self")) - .andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, - "5e6332cf-f003-6369-8cba-5bce2330f6cc")) - .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) - .body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" - + " \"renewable\": false,\n" + " \"ttl\": 456} }")); + this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET)) + .andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc")) + .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n" + + " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n" + " \"ttl\": 456} }")); LoginTokenAdapter adapter = new LoginTokenAdapter( - new TokenAuthentication("5e6332cf-f003-6369-8cba-5bce2330f6cc"), - restTemplate); + new TokenAuthentication("5e6332cf-f003-6369-8cba-5bce2330f6cc"), this.restTemplate); VaultToken login = adapter.login(); diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenUnitTests.java index 6386ff75..6dd3c436 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/LoginTokenUnitTests.java @@ -37,11 +37,10 @@ class LoginTokenUnitTests { @Test void toStringShouldPrintFields() { - assertThat(LoginToken.of("token").toString()) - .isEqualTo("LoginToken [renewable=false, leaseDuration=PT0S]"); - assertThat(LoginToken.of("token", 1).toString()) - .isEqualTo("LoginToken [renewable=false, leaseDuration=PT1S]"); + assertThat(LoginToken.of("token").toString()).isEqualTo("LoginToken [renewable=false, leaseDuration=PT0S]"); + assertThat(LoginToken.of("token", 1).toString()).isEqualTo("LoginToken [renewable=false, leaseDuration=PT1S]"); assertThat(LoginToken.renewable("token", 1).toString()) .isEqualTo("LoginToken [renewable=true, leaseDuration=PT1S]"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/MacAddressUserIdUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/MacAddressUserIdUnitTests.java index d46581f1..325926fa 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/MacAddressUserIdUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/MacAddressUserIdUnitTests.java @@ -38,8 +38,7 @@ class MacAddressUserIdUnitTests { String userId = new MacAddressUserId().createUserId(); - assertThat(userId).matches(Pattern.compile("[0-9A-F]+")) - .doesNotMatch(Pattern.compile("[a-f]")); + assertThat(userId).matches(Pattern.compile("[0-9A-F]+")).doesNotMatch(Pattern.compile("[a-f]")); } @Test @@ -50,20 +49,17 @@ class MacAddressUserIdUnitTests { String userId = new MacAddressUserId(index).createUserId(); - assertThat(userId).matches(Pattern.compile("[0-9A-F]+")) - .doesNotMatch(Pattern.compile("[a-f]")); + assertThat(userId).matches(Pattern.compile("[0-9A-F]+")).doesNotMatch(Pattern.compile("[a-f]")); } /** * Obtain index for {@link NetworkInterface} with a HardwareAddress. - * * @return -1 if none, otherwise index. * @throws SocketException */ private int getValidNetworkInterfaceIndex() throws SocketException { - List<NetworkInterface> interfaces = Collections - .list(NetworkInterface.getNetworkInterfaces()); + List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); int index = -1; @@ -75,4 +71,5 @@ class MacAddressUserIdUnitTests { } return index; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationOptionsUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationOptionsUnitTests.java index 4e343f99..6c28b205 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationOptionsUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationOptionsUnitTests.java @@ -29,10 +29,9 @@ class PcfAuthenticationOptionsUnitTests { @Test void emptyEnvVariableShouldFailWithMeaningfulMessage() { - assertThatThrownBy( - () -> PcfAuthenticationOptions.builder().role("my-role").build()) - .isInstanceOf(IllegalStateException.class) // - .hasMessageContaining( - "Environment variable CF_INSTANCE_CERT not set"); + assertThatThrownBy(() -> PcfAuthenticationOptions.builder().role("my-role").build()) + .isInstanceOf(IllegalStateException.class) // + .hasMessageContaining("Environment variable CF_INSTANCE_CERT not set"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationUnitTests.java index d99e93e6..b74c0220 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/PcfAuthenticationUnitTests.java @@ -72,8 +72,7 @@ class PcfAuthenticationUnitTests { + "TaqiSKrR62qswte+TKq/psakoNH9xhkCsltQ3MMfc6k0kSwwhda9p1pXWK3VFkUh\n" + "EazY3PECgYAoo8jvvQTKlXBmnVU1R//16fCklJXqYcEeOAO0CgyPCxHuAULK++M/\n" + "HRHd+6FippoH4ppSACEqQO5TwBTYxgOCwOcYZaRDvYZqEbgPNlf3oZ73kRyoIeAK\n" - + "zvaXPNUuUEoW4E9Y2M+9SzF+975TTjqwjBgoCIF3xd+xQfgV9vkB6w==\n" - + "-----END RSA PRIVATE KEY-----"; + + "zvaXPNUuUEoW4E9Y2M+9SzF+975TTjqwjBgoCIF3xd+xQfgV9vkB6w==\n" + "-----END RSA PRIVATE KEY-----"; Clock clock = Clock.fixed(Instant.parse("2007-12-03T10:15:30.00Z"), ZoneId.of("UTC")); @@ -90,14 +89,13 @@ class PcfAuthenticationUnitTests { @Test void loginShouldObtainToken() { - PcfAuthenticationOptions options = PcfAuthenticationOptions.builder() - .instanceCertificate(() -> "foo") // - .instanceKey(() -> instanceKey) // + PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") // + .instanceKey(() -> this.instanceKey) // .role("dev-role") // - .clock(clock) // + .clock(this.clock) // .build(); - PcfAuthentication authentication = new PcfAuthentication(options, restTemplate); + PcfAuthentication authentication = new PcfAuthentication(options, this.restTemplate); expectLoginRequest(); @@ -109,17 +107,16 @@ class PcfAuthenticationUnitTests { @Test void loginWithStepsShouldObtainToken() { - PcfAuthenticationOptions options = PcfAuthenticationOptions.builder() - .instanceCertificate(() -> "foo") // - .instanceKey(() -> instanceKey) // + PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") // + .instanceKey(() -> this.instanceKey) // .role("dev-role") // - .clock(clock) // + .clock(this.clock) // .build(); expectLoginRequest(); AuthenticationStepsExecutor authentication = new AuthenticationStepsExecutor( - PcfAuthentication.createAuthenticationSteps(options), restTemplate); + PcfAuthentication.createAuthenticationSteps(options), this.restTemplate); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); @@ -128,12 +125,12 @@ class PcfAuthenticationUnitTests { private void expectLoginRequest() { - mockRest.expect(requestTo("/auth/pcf/login")).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.role").value("dev-role")) - .andExpect(jsonPath("$.signature").exists()) + this.mockRest.expect(requestTo("/auth/pcf/login")).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.signature").exists()) .andExpect(jsonPath("$.cf_instance_cert").value("foo")) .andExpect(jsonPath("$.signing_time").value("2007-12-03T10:15:30Z")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON) .body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerIntegrationTests.java index c3f48fb6..c5d9d605 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerIntegrationTests.java @@ -53,41 +53,37 @@ import static org.springframework.vault.util.Settings.findWorkDir; * @author Mark Paluch */ @RequiresVaultVersion("0.6.2") -class ReactiveLifecycleAwareSessionManagerIntegrationTests - extends IntegrationTestSupport { +class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSupport { private ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); @BeforeEach void before() { - taskScheduler.afterPropertiesSet(); + this.taskScheduler.afterPropertiesSet(); if (!prepare().hasAuth("cert")) { prepare().mountAuth("cert"); } - prepare().getVaultOperations() - .doWithSession((RestOperationsCallback<Object>) restOperations -> { - File workDir = findWorkDir(); + prepare().getVaultOperations().doWithSession((RestOperationsCallback<Object>) restOperations -> { + File workDir = findWorkDir(); - String certificate = Files.contentOf( - new File(workDir, "ca/certs/client.cert.pem"), - StandardCharsets.US_ASCII); + String certificate = Files.contentOf(new File(workDir, "ca/certs/client.cert.pem"), + StandardCharsets.US_ASCII); - Map<String, Object> body = new HashMap<>(); - body.put("certificate", certificate); - body.put("ttl", 2 /* seconds */); - body.put("max_ttl", 2 /* seconds */); + Map<String, Object> body = new HashMap<>(); + body.put("certificate", certificate); + body.put("ttl", 2 /* seconds */); + body.put("max_ttl", 2 /* seconds */); - return restOperations.postForEntity("auth/cert/certs/my-role", body, - Map.class); - }); + return restOperations.postForEntity("auth/cert/certs/my-role", body, Map.class); + }); } @AfterEach void tearDown() { - taskScheduler.destroy(); + this.taskScheduler.destroy(); } @Test @@ -96,7 +92,7 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests LoginToken loginToken = createLoginToken(); ReactiveLifecycleAwareSessionManager sessionManager = new ReactiveLifecycleAwareSessionManager( - () -> Mono.just(loginToken), taskScheduler, prepare().getWebClient()); + () -> Mono.just(loginToken), this.taskScheduler, prepare().getWebClient()); sessionManager.getVaultToken() // .as(StepVerifier::create) // @@ -108,8 +104,7 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests @Test void shouldRenewToken() { - VaultTokenOperations tokenOperations = prepare().getVaultOperations() - .opsForToken(); + VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken(); VaultTokenRequest tokenRequest = VaultTokenRequest.builder() // .renewable().ttl(1, TimeUnit.HOURS) // @@ -122,8 +117,8 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests final AtomicInteger counter = new AtomicInteger(); ReactiveLifecycleAwareSessionManager sessionManager = new ReactiveLifecycleAwareSessionManager( - () -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), - taskScheduler, prepare().getWebClient()) { + () -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), this.taskScheduler, + prepare().getWebClient()) { @Override public Mono<VaultToken> getVaultToken() throws VaultException { @@ -152,8 +147,8 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests final LoginToken loginToken = createLoginToken(); ReactiveLifecycleAwareSessionManager sessionManager = new ReactiveLifecycleAwareSessionManager( - () -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), - taskScheduler, prepare().getWebClient()); + () -> Flux.fromStream(Stream.of((VaultToken) loginToken)).next(), this.taskScheduler, + prepare().getWebClient()); sessionManager.getSessionToken() // .as(StepVerifier::create) // @@ -164,14 +159,12 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests prepare().getVaultOperations().doWithSession(restOperations -> { try { - restOperations.getForEntity("auth/token/lookup/{token}", Map.class, - loginToken.toCharArray()); + restOperations.getForEntity("auth/token/lookup/{token}", Map.class, loginToken.toCharArray()); fail("Missing HttpStatusCodeException"); } catch (HttpStatusCodeException e) { // Compatibility across Vault versions. - assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, - HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); + assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); } return null; @@ -180,10 +173,10 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests private LoginToken createLoginToken() { - VaultTokenOperations tokenOperations = prepare().getVaultOperations() - .opsForToken(); + VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken(); VaultToken token = tokenOperations.createOrphan().getToken(); return LoginToken.of(token.getToken()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerUnitTests.java index 9c7113bc..e594d8e7 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/ReactiveLifecycleAwareSessionManagerUnitTests.java @@ -115,21 +115,21 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { void before() { // POST - when(webClient.post()).thenReturn(requestBodyUriSpec); - when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec); - when(requestBodySpec.headers(any())).thenReturn(requestBodySpec); - when(requestBodySpec.retrieve()).thenReturn(responseSpec); + when(this.webClient.post()).thenReturn(this.requestBodyUriSpec); + when(this.requestBodyUriSpec.uri(anyString())).thenReturn(this.requestBodySpec); + when(this.requestBodySpec.headers(any())).thenReturn(this.requestBodySpec); + when(this.requestBodySpec.retrieve()).thenReturn(this.responseSpec); // GET - when(webClient.get()).thenReturn(requestHeadersUriSpec); - when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestHeadersSpec); - when(requestHeadersSpec.headers(any())).thenReturn(requestHeadersSpec); - when(requestHeadersSpec.retrieve()).thenReturn(responseSpec); + when(this.webClient.get()).thenReturn(this.requestHeadersUriSpec); + when(this.requestHeadersUriSpec.uri(anyString())).thenReturn(this.requestHeadersSpec); + when(this.requestHeadersSpec.headers(any())).thenReturn(this.requestHeadersSpec); + when(this.requestHeadersSpec.retrieve()).thenReturn(this.responseSpec); - sessionManager = new ReactiveLifecycleAwareSessionManager(tokenSupplier, - taskScheduler, webClient); - sessionManager.addAuthenticationListener(listener); - sessionManager.addErrorListener(errorListener); + this.sessionManager = new ReactiveLifecycleAwareSessionManager(this.tokenSupplier, this.taskScheduler, + this.webClient); + this.sessionManager.addAuthenticationListener(this.listener); + this.sessionManager.addErrorListener(this.errorListener); } @Test @@ -137,24 +137,23 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(LoginToken.of("login")); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNext(LoginToken.of("login")) // .verifyComplete(); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); } @Test void loginShouldFail() { - when(tokenSupplier.getVaultToken()) - .thenReturn(Mono.error(new VaultLoginException("foo"))); + when(this.tokenSupplier.getVaultToken()).thenReturn(Mono.error(new VaultLoginException("foo"))); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .verifyError(); - verifyZeroInteractions(listener); - verify(errorListener).onAuthenticationError(any(LoginFailedEvent.class)); + verifyZeroInteractions(this.listener); + verify(this.errorListener).onAuthenticationError(any(LoginFailedEvent.class)); } @Test @@ -166,18 +165,17 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(VaultToken.of("login")); - when(responseSpec.bodyToMono((Class) any())).thenReturn(Mono.just(vaultResponse)); + when(this.responseSpec.bodyToMono((Class) any())).thenReturn(Mono.just(vaultResponse)); - sessionManager.getSessionToken().as(StepVerifier::create).assertNext(it -> { + this.sessionManager.getSessionToken().as(StepVerifier::create).assertNext(it -> { LoginToken sessionToken = (LoginToken) it; - assertThat(sessionToken.getLeaseDuration()) - .isEqualTo(Duration.ofSeconds(100)); + assertThat(sessionToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(100)); }).verifyComplete(); - verify(webClient.get()).uri("auth/token/lookup-self"); - verify(listener).onAuthenticationEvent(captor.capture()); - AfterLoginEvent event = (AfterLoginEvent) captor.getValue(); + verify(this.webClient.get()).uri("auth/token/lookup-self"); + verify(this.listener).onAuthenticationEvent(this.captor.capture()); + AfterLoginEvent event = (AfterLoginEvent) this.captor.getValue(); assertThat(event.getSource()).isInstanceOf(LoginToken.class); } @@ -190,17 +188,16 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(VaultToken.of("login")); - when(responseSpec.bodyToMono((Class) any())) - .thenReturn(Mono.error(new WebClientResponseException("forbidden", 403, - "Forbidden", null, null, null))); + when(this.responseSpec.bodyToMono((Class) any())).thenReturn( + Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null))); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .assertNext(it -> { assertThat(it).isExactlyInstanceOf(VaultToken.class); }).verifyComplete(); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); - verify(errorListener).onAuthenticationError(any()); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.errorListener).onAuthenticationError(any()); } @Test @@ -208,22 +205,17 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(LoginToken.renewable("foo".toCharArray(), Duration.ofMinutes(1))); - when(responseSpec.bodyToMono((Class) any())) - .thenReturn(Mono.error(new WebClientResponseException("Some server error", - 500, "Some server error", null, null, null))); + when(this.responseSpec.bodyToMono((Class) any())).thenReturn(Mono.error( + new WebClientResponseException("Some server error", 500, "Some server error", null, null, null))); AtomicReference<AuthenticationErrorEvent> listener = new AtomicReference<>(); - sessionManager.addErrorListener(listener::set); + this.sessionManager.addErrorListener(listener::set); - sessionManager.getVaultToken().as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - sessionManager.renewToken().as(StepVerifier::create) - .verifyComplete(); - assertThat(listener.get().getException()) - .isInstanceOf(VaultTokenRenewalException.class) - .hasCauseInstanceOf(WebClientResponseException.class) - .hasMessageContaining( - "Cannot renew token: Status 500 Some server error"); + this.sessionManager.getVaultToken().as(StepVerifier::create).expectNextCount(1).verifyComplete(); + this.sessionManager.renewToken().as(StepVerifier::create).verifyComplete(); + assertThat(listener.get().getException()).isInstanceOf(VaultTokenRenewalException.class) + .hasCauseInstanceOf(WebClientResponseException.class) + .hasMessageContaining("Cannot renew token: Status 500 Some server error"); } @@ -234,19 +226,18 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { vaultResponse.setData(Collections.singletonMap("ttl", 100)); mockToken(LoginToken.of("login")); - when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just("OK")); + when(this.responseSpec.bodyToMono(String.class)).thenReturn(Mono.just("OK")); - sessionManager.getVaultToken() // + this.sessionManager.getVaultToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - sessionManager.destroy(); + this.sessionManager.destroy(); - verify(webClient.post()).uri("auth/token/revoke-self"); - verify(listener) - .onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); - verify(listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class)); + verify(this.webClient.post()).uri("auth/token/revoke-self"); + verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRevocationEvent.class)); } @Test @@ -254,17 +245,17 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(VaultToken.of("login")); - sessionManager.setTokenSelfLookupEnabled(false); - sessionManager.renewToken() // + this.sessionManager.setTokenSelfLookupEnabled(false); + this.sessionManager.renewToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - sessionManager.destroy(); + this.sessionManager.destroy(); - verify(webClient, never()).post(); - verify(webClient.post(), never()).uri("auth/token/revoke-self"); - verify(listener).onAuthenticationEvent(any(AfterLoginEvent.class)); - verifyNoMoreInteractions(listener); + verify(this.webClient, never()).post(); + verify(this.webClient.post(), never()).uri("auth/token/revoke-self"); + verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class)); + verifyNoMoreInteractions(this.listener); } @Test @@ -272,17 +263,16 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(LoginToken.of("login")); - when(responseSpec.bodyToMono((Class) any())) - .thenReturn(Mono.error(new WebClientResponseException("forbidden", 403, - "Forbidden", null, null, null))); + when(this.responseSpec.bodyToMono((Class) any())).thenReturn( + Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null))); - sessionManager.renewToken() // + this.sessionManager.renewToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - sessionManager.destroy(); + this.sessionManager.destroy(); - verify(requestBodyUriSpec).uri("auth/token/revoke-self"); + verify(this.requestBodyUriSpec).uri("auth/token/revoke-self"); } @Test @@ -290,12 +280,12 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); } @Test @@ -310,24 +300,23 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { auth.put("ttl", 100); vaultResponse.setAuth(auth); - when(responseSpec.bodyToMono(VaultResponse.class)) - .thenReturn(Mono.just(vaultResponse)); + when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.just(vaultResponse)); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(webClient).post(); - verify(webClient.post()).uri("auth/token/renew-self"); + verify(this.webClient).post(); + verify(this.webClient.post()).uri("auth/token/renew-self"); - verify(tokenSupplier, times(1)).getVaultToken(); - verify(listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class)); - verify(listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class)); + verify(this.tokenSupplier, times(1)).getVaultToken(); + verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class)); + verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class)); } @Test @@ -335,122 +324,107 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.just( - fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10))))); + when(this.responseSpec.bodyToMono(VaultResponse.class)) + .thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10))))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class)); } @Test void shouldNotScheduleRenewalIfRenewalTtlExceedsThreshold() { mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))); - when(responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.just( - fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))))); + when(this.responseSpec.bodyToMono(VaultResponse.class)) + .thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken().as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + this.sessionManager.getSessionToken().as(StepVerifier::create).expectNextCount(1).verifyComplete(); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class)); } @Test void shouldReLoginIfRenewalTtlExceedsThreshold() { - when(tokenSupplier.getVaultToken()).thenReturn( - Mono.just(LoginToken.renewable("login".toCharArray(), - Duration.ofSeconds(5))), - Mono.just(LoginToken.renewable("bar".toCharArray(), - Duration.ofSeconds(5)))); - when(responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.just( - fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))))); + when(this.tokenSupplier.getVaultToken()).thenReturn( + Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))), + Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)))); + when(this.responseSpec.bodyToMono(VaultResponse.class)) + .thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - sessionManager.getSessionToken().as(StepVerifier::create) - .expectNext( - LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))) - .verifyComplete(); + this.sessionManager.getSessionToken().as(StepVerifier::create) + .expectNext(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))).verifyComplete(); - verify(tokenSupplier, times(2)).getVaultToken(); - verify(listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class)); - verify(listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class)); + verify(this.tokenSupplier, times(2)).getVaultToken(); + verify(this.listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class)); + verify(this.listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class)); } @Test void shouldReLoginIfRenewFails() { - when(tokenSupplier.getVaultToken()).thenReturn( - Mono.just(LoginToken.renewable("login".toCharArray(), - Duration.ofSeconds(5))), - Mono.just(LoginToken.renewable("bar".toCharArray(), - Duration.ofSeconds(5)))); - when(responseSpec.bodyToMono(VaultResponse.class)) - .thenReturn(Mono.error(new RuntimeException("foo"))); + when(this.tokenSupplier.getVaultToken()).thenReturn( + Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))), + Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)))); + when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo"))); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - sessionManager.getSessionToken().as(StepVerifier::create) - .expectNext( - LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))) - .verifyComplete(); + this.sessionManager.getSessionToken().as(StepVerifier::create) + .expectNext(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))).verifyComplete(); - verify(tokenSupplier, times(2)).getVaultToken(); + verify(this.tokenSupplier, times(2)).getVaultToken(); } @Test void shouldRetainTokenAfterRenewalFailure() { - when(tokenSupplier.getVaultToken()).thenReturn( - Mono.just(LoginToken.renewable("login".toCharArray(), - Duration.ofSeconds(5))), - Mono.just(LoginToken.renewable("bar".toCharArray(), - Duration.ofSeconds(5)))); - when(responseSpec.bodyToMono(VaultResponse.class)) - .thenReturn(Mono.error(new RuntimeException("foo"))); - sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError()); + when(this.tokenSupplier.getVaultToken()).thenReturn( + Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))), + Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)))); + when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo"))); + this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError()); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - sessionManager.getSessionToken() // + this.sessionManager.getSessionToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - sessionManager - .getSessionToken().as(StepVerifier::create).expectNext(LoginToken - .renewable("login".toCharArray(), Duration.ofSeconds(5))) - .verifyComplete(); + this.sessionManager.getSessionToken().as(StepVerifier::create) + .expectNext(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))).verifyComplete(); - verify(tokenSupplier).getVaultToken(); + verify(this.tokenSupplier).getVaultToken(); } private static VaultResponse fromToken(LoginToken loginToken) { @@ -468,6 +442,7 @@ class ReactiveLifecycleAwareSessionManagerUnitTests { } private void mockToken(VaultToken token) { - when(tokenSupplier.getVaultToken()).thenReturn(Mono.just(token)); + when(this.tokenSupplier.getVaultToken()).thenReturn(Mono.just(token)); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationOperatorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationOperatorIntegrationTests.java index 6a73e27e..1ad7d670 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationOperatorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationOperatorIntegrationTests.java @@ -35,22 +35,20 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Mark Paluch */ -class TokenAuthenticationOperatorIntegrationTests - extends TokenAuthenticationIntegrationTestBase { +class TokenAuthenticationOperatorIntegrationTests extends TokenAuthenticationIntegrationTestBase { WebClient webClient = TestWebClientFactory.create(Settings.createSslConfiguration()); @Test void shouldSelfLookup() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .ttl(Duration.ofSeconds(60)).renewable().numUses(1).build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) + .build(); - VaultToken token = prepare().getVaultOperations().opsForToken() - .create(tokenRequest).getToken(); + VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( - TokenAuthentication.createAuthenticationSteps(token, true), webClient); + TokenAuthentication.createAuthenticationSteps(token, true), this.webClient); operator.getVaultToken().as(StepVerifier::create).consumeNextWith(actual -> { @@ -58,8 +56,7 @@ class TokenAuthenticationOperatorIntegrationTests LoginToken loginToken = (LoginToken) actual; - assertThat(loginToken.getLeaseDuration()).isBetween(Duration.ofSeconds(40), - Duration.ofSeconds(60)); + assertThat(loginToken.getLeaseDuration()).isBetween(Duration.ofSeconds(40), Duration.ofSeconds(60)); assertThat(loginToken.isRenewable()).isTrue(); }).verifyComplete(); @@ -68,14 +65,13 @@ class TokenAuthenticationOperatorIntegrationTests @Test void shouldFailDuringSelfLookup() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .ttl(Duration.ofSeconds(60)).renewable().numUses(1).build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) + .build(); - VaultToken token = prepare().getVaultOperations().opsForToken() - .create(tokenRequest).getToken(); + VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( - TokenAuthentication.createAuthenticationSteps(token, true), webClient); + TokenAuthentication.createAuthenticationSteps(token, true), this.webClient); // first usage operator.getVaultToken() // @@ -88,4 +84,5 @@ class TokenAuthenticationOperatorIntegrationTests .expectError(VaultException.class) // .verify(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationStepsIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationStepsIntegrationTests.java index b5a97a91..6d9e99c9 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationStepsIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/authentication/TokenAuthenticationStepsIntegrationTests.java @@ -35,47 +35,43 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Mark Paluch */ -class TokenAuthenticationStepsIntegrationTests - extends TokenAuthenticationIntegrationTestBase { +class TokenAuthenticationStepsIntegrationTests extends TokenAuthenticationIntegrationTestBase { - RestTemplate restTemplate = TestRestTemplateFactory - .create(Settings.createSslConfiguration()); + RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration()); @Test void shouldSelfLookup() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .ttl(Duration.ofSeconds(60)).renewable().numUses(1).build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) + .build(); - VaultToken token = prepare().getVaultOperations().opsForToken() - .create(tokenRequest).getToken(); + VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsExecutor operator = new AuthenticationStepsExecutor( - TokenAuthentication.createAuthenticationSteps(token, true), restTemplate); + TokenAuthentication.createAuthenticationSteps(token, true), this.restTemplate); VaultToken login = operator.login(); assertThat(login).isInstanceOf(LoginToken.class); LoginToken loginToken = (LoginToken) login; - assertThat(loginToken.getLeaseDuration()).isBetween(Duration.ofSeconds(40), - Duration.ofSeconds(60)); + assertThat(loginToken.getLeaseDuration()).isBetween(Duration.ofSeconds(40), Duration.ofSeconds(60)); assertThat(loginToken.isRenewable()).isTrue(); } @Test void shouldFailDuringSelfLookup() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .ttl(Duration.ofSeconds(60)).renewable().numUses(1).build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1) + .build(); - VaultToken token = prepare().getVaultOperations().opsForToken() - .create(tokenRequest).getToken(); + VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken(); AuthenticationStepsExecutor operator = new AuthenticationStepsExecutor( - TokenAuthentication.createAuthenticationSteps(token, true), restTemplate); + TokenAuthentication.createAuthenticationSteps(token, true), this.restTemplate); operator.login(); assertThatExceptionOfType(VaultException.class).isThrownBy(operator::login); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpConnectorFactoryIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpConnectorFactoryIntegrationTests.java index c9351c4d..7d90e253 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpConnectorFactoryIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpConnectorFactoryIntegrationTests.java @@ -52,8 +52,7 @@ class ClientHttpConnectorFactoryIntegrationTests { @Test void jettyClientShouldWork() { - ClientHttpConnector factory = JettyClient.usingJetty(new ClientOptions(), - Settings.createSslConfiguration()); + ClientHttpConnector factory = JettyClient.usingJetty(new ClientOptions(), Settings.createSslConfiguration()); WebClient webClient = WebClient.builder().clientConnector(factory).build(); @@ -66,10 +65,11 @@ class ClientHttpConnectorFactoryIntegrationTests { // Uninitialized and sealed can cause status 500 try { - return webClient.get().uri(url).retrieve().bodyToMono(String.class).block(); + return webClient.get().uri(this.url).retrieve().bodyToMono(String.class).block(); } catch (WebClientResponseException e) { return e.getResponseBodyAsString(); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpRequestFactoryFactoryIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpRequestFactoryFactoryIntegrationTests.java index ce165c94..f885bf25 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpRequestFactoryFactoryIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/ClientHttpRequestFactoryFactoryIntegrationTests.java @@ -47,8 +47,8 @@ class ClientHttpRequestFactoryFactoryIntegrationTests { @Test void httpComponentsClientShouldWork() throws Exception { - ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents( - new ClientOptions(), Settings.createSslConfiguration()); + ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(), + Settings.createSslConfiguration()); RestTemplate template = new RestTemplate(factory); String response = request(template); @@ -62,8 +62,7 @@ class ClientHttpRequestFactoryFactoryIntegrationTests { @Test void nettyClientShouldWork() throws Exception { - ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions(), - Settings.createSslConfiguration()); + ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions(), Settings.createSslConfiguration()); ((InitializingBean) factory).afterPropertiesSet(); RestTemplate template = new RestTemplate(factory); @@ -78,8 +77,7 @@ class ClientHttpRequestFactoryFactoryIntegrationTests { @Test void okHttp3ClientShouldWork() throws Exception { - ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions(), - Settings.createSslConfiguration()); + ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions(), Settings.createSslConfiguration()); RestTemplate template = new RestTemplate(factory); String response = request(template); @@ -94,12 +92,12 @@ class ClientHttpRequestFactoryFactoryIntegrationTests { // Uninitialized and sealed can cause status 500 try { - ResponseEntity<String> responseEntity = template.exchange(url, HttpMethod.GET, - null, String.class); + ResponseEntity<String> responseEntity = template.exchange(this.url, HttpMethod.GET, null, String.class); return responseEntity.getBody(); } catch (HttpStatusCodeException e) { return e.getResponseBodyAsString(); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/ReactiveVaultClientsUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/ReactiveVaultClientsUnitTests.java index 46358b3c..6fd35d8c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/ReactiveVaultClientsUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/ReactiveVaultClientsUnitTests.java @@ -41,18 +41,15 @@ class ReactiveVaultClientsUnitTests { @Test void shouldApplyNamespace() { - ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, - "/auth/foo"); + ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/foo"); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); - ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request) - .then(Mono.just(response)); + ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response)); WebClient webClient = WebClient.builder().clientConnector(connector) .filter(ReactiveVaultClients.namespace("foo/bar")).build(); - webClient.get().uri("/auth/foo").retrieve().bodyToMono(String.class) - .as(StepVerifier::create) // + webClient.get().uri("/auth/foo").retrieve().bodyToMono(String.class).as(StepVerifier::create) // .verifyComplete(); assertThat(request.getHeaders()).containsEntry(VaultHttpHeaders.VAULT_NAMESPACE, @@ -62,22 +59,21 @@ class ReactiveVaultClientsUnitTests { @Test void shouldAllowNamespaceOverride() { - ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, - "/auth/foo"); + ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/auth/foo"); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); - ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request) - .then(Mono.just(response)); + ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response)); WebClient webClient = WebClient.builder().clientConnector(connector) .filter(ReactiveVaultClients.namespace("foo/bar")).build(); - webClient.get().uri("/auth/foo").header(VaultHttpHeaders.VAULT_NAMESPACE, "baz") - .retrieve().bodyToMono(String.class) // + webClient.get().uri("/auth/foo").header(VaultHttpHeaders.VAULT_NAMESPACE, "baz").retrieve() + .bodyToMono(String.class) // .as(StepVerifier::create) // .verifyComplete(); assertThat(request.getHeaders()).containsEntry(VaultHttpHeaders.VAULT_NAMESPACE, Collections.singletonList("baz")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/RestTemplateBuilderUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/RestTemplateBuilderUnitTests.java index 069d7525..034e8ef8 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/RestTemplateBuilderUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/RestTemplateBuilderUnitTests.java @@ -41,8 +41,7 @@ class RestTemplateBuilderUnitTests { ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler(); - RestTemplate restTemplate = RestTemplateBuilder.builder() - .endpoint(VaultEndpoint.create("localhost", 8200)) + RestTemplate restTemplate = RestTemplateBuilder.builder().endpoint(VaultEndpoint.create("localhost", 8200)) .errorHandler(errorHandler).build(); assertThat(restTemplate.getErrorHandler()).isSameAs(errorHandler); @@ -53,8 +52,7 @@ class RestTemplateBuilderUnitTests { ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler(); - RestTemplate restTemplate = RestTemplateBuilder.builder() - .endpoint(VaultEndpoint.create("localhost", 8200)) + RestTemplate restTemplate = RestTemplateBuilder.builder().endpoint(VaultEndpoint.create("localhost", 8200)) .customizers(it -> it.setErrorHandler(errorHandler)).build(); assertThat(restTemplate.getErrorHandler()).isSameAs(errorHandler); @@ -63,17 +61,14 @@ class RestTemplateBuilderUnitTests { @Test void shouldApplyRequestCustomizers() throws IOException { - RestTemplate restTemplate = RestTemplateBuilder.builder() - .endpoint(VaultEndpoint.create("localhost", 8200)).requestCustomizers( - request -> request.getHeaders().add("header", "value")) - .build(); + RestTemplate restTemplate = RestTemplateBuilder.builder().endpoint(VaultEndpoint.create("localhost", 8200)) + .requestCustomizers(request -> request.getHeaders().add("header", "value")).build(); restTemplate.getInterceptors().clear(); - ClientHttpRequest request = restTemplate.getRequestFactory() - .createRequest(URI.create("/"), HttpMethod.GET); + ClientHttpRequest request = restTemplate.getRequestFactory().createRequest(URI.create("/"), HttpMethod.GET); - assertThat(request.getHeaders()).containsEntry("header", - Collections.singletonList("value")); + assertThat(request.getHeaders()).containsEntry("header", Collections.singletonList("value")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultClientsUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultClientsUnitTests.java index f69757fb..047bfa6a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultClientsUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultClientsUnitTests.java @@ -44,8 +44,7 @@ class VaultClientsUnitTests { void uriHandlerShouldPrefixRelativeUrl() { VaultEndpoint localhost = VaultEndpoint.create("localhost", 8200); - PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler( - () -> localhost); + PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler(() -> localhost); URI uri = handler.expand("/path/{bar}", "bar"); @@ -56,21 +55,18 @@ class VaultClientsUnitTests { void uriHandlerShouldNotPrefixAbsoluteUrl() { VaultEndpoint localhost = VaultEndpoint.create("localhost", 8200); - PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler( - () -> localhost); + PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler(() -> localhost); URI uri = handler.expand("https://foo/path/{bar}", "bar"); - assertThat(uri).hasScheme("https").hasHost("foo").hasPort(-1) - .hasPath("/path/bar"); + assertThat(uri).hasScheme("https").hasHost("foo").hasPort(-1).hasPath("/path/bar"); } @Test void uriBuilderShouldPrefixRelativeUrl() { VaultEndpoint localhost = VaultEndpoint.create("localhost", 8200); - PrefixAwareUriBuilderFactory handler = new PrefixAwareUriBuilderFactory( - () -> localhost); + PrefixAwareUriBuilderFactory handler = new PrefixAwareUriBuilderFactory(() -> localhost); URI uri = handler.expand("/path/{bar}", "bar"); @@ -81,28 +77,24 @@ class VaultClientsUnitTests { void uriBuilderShouldNotPrefixAbsoluteUrl() { VaultEndpoint localhost = VaultEndpoint.create("localhost", 8200); - PrefixAwareUriBuilderFactory handler = new PrefixAwareUriBuilderFactory( - () -> localhost); + PrefixAwareUriBuilderFactory handler = new PrefixAwareUriBuilderFactory(() -> localhost); URI uri = handler.expand("https://foo/path/{bar}", "bar"); - assertThat(uri).hasScheme("https").hasHost("foo").hasPort(-1) - .hasPath("/path/bar"); + assertThat(uri).hasScheme("https").hasHost("foo").hasPort(-1).hasPath("/path/bar"); } @Test void shouldApplyNamespace() { RestTemplate restTemplate = VaultClients.createRestTemplate(); - restTemplate.getInterceptors() - .add(VaultClients.createNamespaceInterceptor("foo/bar")); + restTemplate.getInterceptors().add(VaultClients.createNamespaceInterceptor("foo/bar")); restTemplate.setUriTemplateHandler(new PrefixAwareUriTemplateHandler()); MockRestServiceServer mockRest = MockRestServiceServer.createServer(restTemplate); mockRest.expect(requestTo("/auth/foo")).andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_NAMESPACE, "foo/bar")) - .andRespond(withSuccess()); + .andExpect(header(VaultHttpHeaders.VAULT_NAMESPACE, "foo/bar")).andRespond(withSuccess()); restTemplate.getForEntity("/auth/foo", String.class); } @@ -111,21 +103,18 @@ class VaultClientsUnitTests { void shouldAllowNamespaceOverride() { RestTemplate restTemplate = VaultClients.createRestTemplate(); - restTemplate.getInterceptors() - .add(VaultClients.createNamespaceInterceptor("foo/bar")); + restTemplate.getInterceptors().add(VaultClients.createNamespaceInterceptor("foo/bar")); restTemplate.setUriTemplateHandler(new PrefixAwareUriTemplateHandler()); MockRestServiceServer mockRest = MockRestServiceServer.createServer(restTemplate); mockRest.expect(requestTo("/auth/foo")).andExpect(method(HttpMethod.GET)) - .andExpect(header(VaultHttpHeaders.VAULT_NAMESPACE, "baz")) - .andRespond(withSuccess()); + .andExpect(header(VaultHttpHeaders.VAULT_NAMESPACE, "baz")).andRespond(withSuccess()); HttpHeaders headers = new HttpHeaders(); headers.add(VaultHttpHeaders.VAULT_NAMESPACE, "baz"); - restTemplate.exchange("/auth/foo", HttpMethod.GET, new HttpEntity<>(headers), - String.class); + restTemplate.exchange("/auth/foo", HttpMethod.GET, new HttpEntity<>(headers), String.class); } @Test @@ -133,11 +122,11 @@ class VaultClientsUnitTests { VaultEndpoint localhost = VaultEndpoint.create("localhost", 8200); localhost.setPath("foo/v1"); - PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler( - () -> localhost); + PrefixAwareUriTemplateHandler handler = new PrefixAwareUriTemplateHandler(() -> localhost); URI uri = handler.expand("/path/{bar}", "bar"); assertThat(uri).hasHost("localhost").hasPort(8200).hasPath("/foo/v1/path/bar"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultEndpointUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultEndpointUnitTests.java index 86c4375a..e91a1d59 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultEndpointUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultEndpointUnitTests.java @@ -63,11 +63,10 @@ class VaultEndpointUnitTests { @Test void shouldCreateEndpointWithPath() { - VaultEndpoint endpoint = VaultEndpoint - .from(URI.create("http://127.0.0.1/context")); + VaultEndpoint endpoint = VaultEndpoint.from(URI.create("http://127.0.0.1/context")); assertThat(endpoint.getPath()).isEqualTo("context"); - assertThat(endpoint.createUri("foo")) - .isEqualTo(URI.create("http://127.0.0.1:80/context/foo")); + assertThat(endpoint.createUri("foo")).isEqualTo(URI.create("http://127.0.0.1:80/context/foo")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultResponsesUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultResponsesUnitTests.java index 2ea0e3ae..e7dca1f0 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/client/VaultResponsesUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/client/VaultResponsesUnitTests.java @@ -36,49 +36,40 @@ class VaultResponsesUnitTests { @Test void shouldBuildException() { - HttpStatusCodeException cause = new HttpClientErrorException( - HttpStatus.BAD_REQUEST, "Bad Request"); + HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request"); VaultException vaultException = VaultResponses.buildException(cause); - assertThat(vaultException).hasMessageContaining("Status 400 Bad Request;") - .hasCause(cause); + assertThat(vaultException).hasMessageContaining("Status 400 Bad Request;").hasCause(cause); } @Test void shouldBuildExceptionWithErrorMessage() { - HttpStatusCodeException cause = new HttpClientErrorException( - HttpStatus.BAD_REQUEST, "Bad Request", + HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request", "{\"errors\":[\"some-error\"]}".getBytes(), StandardCharsets.US_ASCII); VaultException vaultException = VaultResponses.buildException(cause); - assertThat(vaultException) - .hasMessageContaining("Status 400 Bad Request: some-error;") - .hasCause(cause); + assertThat(vaultException).hasMessageContaining("Status 400 Bad Request: some-error;").hasCause(cause); } @Test void shouldBuildExceptionWithPath() { - HttpStatusCodeException cause = new HttpClientErrorException( - HttpStatus.BAD_REQUEST, "Bad Request"); + HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request"); VaultException vaultException = VaultResponses.buildException(cause, "sys/path"); - assertThat(vaultException) - .hasMessageContaining("Status 400 Bad Request [sys/path];") - .hasCause(cause); + assertThat(vaultException).hasMessageContaining("Status 400 Bad Request [sys/path];").hasCause(cause); } @Test void shouldBuildExceptionWithPathAndErrorMessage() { - HttpStatusCodeException cause = new HttpClientErrorException( - HttpStatus.BAD_REQUEST, "Bad Request", + HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request", "{\"errors\":[\"some-error\"]}".getBytes(), StandardCharsets.US_ASCII); VaultException vaultException = VaultResponses.buildException(cause, "sys/path"); - assertThat(vaultException) - .hasMessageContaining("Status 400 Bad Request [sys/path]: some-error;") + assertThat(vaultException).hasMessageContaining("Status 400 Bad Request [sys/path]: some-error;") .hasCause(cause); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppIdAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppIdAuthenticationUnitTests.java index 0faef892..3fb6b20d 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppIdAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppIdAuthenticationUnitTests.java @@ -34,14 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=appid", "vault.app-id.user-id=IP_ADDRESS", - "vault.app-id.app-id=foo" }) +@TestPropertySource(properties = { "vault.uri=https://localhost:8123", "vault.authentication=appid", + "vault.app-id.user-id=IP_ADDRESS", "vault.app-id.app-id=foo" }) class EnvironmentVaultConfigurationAppIdAuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -50,8 +50,9 @@ class EnvironmentVaultConfigurationAppIdAuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(AppIdAuthentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests.java index 1dd6c601..b5f2db1c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests.java @@ -34,14 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=approle", "vault.app-role.role-id=role", - "vault.app-role.secret-id=foo" }) +@TestPropertySource(properties = { "vault.uri=https://localhost:8123", "vault.authentication=approle", + "vault.app-role.role-id=role", "vault.app-role.secret-id=foo" }) class EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -50,8 +50,9 @@ class EnvironmentVaultConfigurationAppRoleAuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(AppRoleAuthentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests.java index df74211b..be0a5785 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests.java @@ -34,13 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=aws-ec2", "vault.aws-ec2.role=role" }) +@TestPropertySource( + properties = { "vault.uri=https://localhost:8123", "vault.authentication=aws-ec2", "vault.aws-ec2.role=role" }) class EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -49,8 +50,9 @@ class EnvironmentVaultConfigurationAwsEc2AuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(AwsEc2Authentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests.java index 24ffb29a..4fabc1ea 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests.java @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=http://null", "vault.authentication=azure", - "vault.azure-msi.role=role", "vault.azure-msi.metadata-service=http://foo" }) +@TestPropertySource(properties = { "vault.uri=http://null", "vault.authentication=azure", "vault.azure-msi.role=role", + "vault.azure-msi.metadata-service=http://foo" }) class EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests { @Configuration @@ -50,20 +50,18 @@ class EnvironmentVaultConfigurationAzureMSIAuthenticationUnitTests { } @Test - void shouldConfigureAuthentication( - @Autowired EnvironmentVaultConfiguration configuration) { + void shouldConfigureAuthentication(@Autowired EnvironmentVaultConfiguration configuration) { ClientAuthentication clientAuthentication = configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(AzureMsiAuthentication.class); DirectFieldAccessor accessor = new DirectFieldAccessor(clientAuthentication); - AzureMsiAuthenticationOptions options = (AzureMsiAuthenticationOptions) accessor - .getPropertyValue("options"); + AzureMsiAuthenticationOptions options = (AzureMsiAuthenticationOptions) accessor.getPropertyValue("options"); - assertThat(options.getIdentityTokenServiceUri()).isEqualTo( - AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI); - assertThat(options.getInstanceMetadataServiceUri()) - .isEqualTo(URI.create("http://foo")); + assertThat(options.getIdentityTokenServiceUri()) + .isEqualTo(AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI); + assertThat(options.getInstanceMetadataServiceUri()).isEqualTo(URI.create("http://foo")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationClientCertAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationClientCertAuthenticationUnitTests.java index 0bc493b8..575c280e 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationClientCertAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationClientCertAuthenticationUnitTests.java @@ -34,13 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=cert", "vault.aws-ec2.role-id=role" }) +@TestPropertySource( + properties = { "vault.uri=https://localhost:8123", "vault.authentication=cert", "vault.aws-ec2.role-id=role" }) class EnvironmentVaultConfigurationClientCertAuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -49,9 +50,9 @@ class EnvironmentVaultConfigurationClientCertAuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); - assertThat(clientAuthentication) - .isInstanceOf(ClientCertificateAuthentication.class); + assertThat(clientAuthentication).isInstanceOf(ClientCertificateAuthentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests.java index 888dc0a3..f9e31c2a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests.java @@ -34,13 +34,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=cubbyhole", "vault.token=my-token" }) +@TestPropertySource( + properties = { "vault.uri=https://localhost:8123", "vault.authentication=cubbyhole", "vault.token=my-token" }) class EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -49,8 +50,9 @@ class EnvironmentVaultConfigurationCubbyholeAuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(CubbyholeAuthentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests.java index 7c3af862..6a6de748 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests.java @@ -41,14 +41,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @ExtendWith(VaultExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.authentication=kubernetes", "vault.kubernetes.role=my-role", - "vault.kubernetes.service-account-token-file=target/token" }) +@TestPropertySource(properties = { "vault.uri=https://localhost:8123", "vault.authentication=kubernetes", + "vault.kubernetes.role=my-role", "vault.kubernetes.service-account-token-file=target/token" }) class EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @BeforeAll @@ -62,8 +62,9 @@ class EnvironmentVaultConfigurationKubernetesAuthenticationUnitTests { @Test void shouldConfigureAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(KubernetesAuthentication.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationUnitTests.java index 4bf173ae..b90ea726 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/config/EnvironmentVaultConfigurationUnitTests.java @@ -42,14 +42,14 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @ExtendWith(SpringExtension.class) -@TestPropertySource(properties = { "vault.uri=https://localhost:8123", - "vault.token=my-token", "vault.ssl.key-store-password=key store password", - "vault.ssl.trust-store-password=trust store password" }) +@TestPropertySource(properties = { "vault.uri=https://localhost:8123", "vault.token=my-token", + "vault.ssl.key-store-password=key store password", "vault.ssl.trust-store-password=trust store password" }) class EnvironmentVaultConfigurationUnitTests { @Configuration @Import(EnvironmentVaultConfiguration.class) static class ApplicationConfiguration { + } @Autowired @@ -60,13 +60,13 @@ class EnvironmentVaultConfigurationUnitTests { @Test void shouldConfigureEndpoint() { - assertThat(configuration.vaultEndpoint().getPort()).isEqualTo(8123); + assertThat(this.configuration.vaultEndpoint().getPort()).isEqualTo(8123); } @Test void shouldConfigureTokenAuthentication() { - ClientAuthentication clientAuthentication = configuration.clientAuthentication(); + ClientAuthentication clientAuthentication = this.configuration.clientAuthentication(); assertThat(clientAuthentication).isInstanceOf(TokenAuthentication.class); assertThat(clientAuthentication.login()).isEqualTo(VaultToken.of("my-token")); @@ -79,21 +79,18 @@ class EnvironmentVaultConfigurationUnitTests { map.put("vault.ssl.key-store", "classpath:certificate.json"); map.put("vault.ssl.trust-store", "classpath:certificate.json"); - MapPropertySource propertySource = new MapPropertySource("shouldConfigureSsl", - map); - configurableEnvironment.getPropertySources().addFirst(propertySource); + MapPropertySource propertySource = new MapPropertySource("shouldConfigureSsl", map); + this.configurableEnvironment.getPropertySources().addFirst(propertySource); - SslConfiguration sslConfiguration = configuration.sslConfiguration(); + SslConfiguration sslConfiguration = this.configuration.sslConfiguration(); assertThat(sslConfiguration.getKeyStore()).isInstanceOf(ClassPathResource.class); - assertThat(sslConfiguration.getKeyStorePassword()) - .isEqualTo("key store password"); + assertThat(sslConfiguration.getKeyStorePassword()).isEqualTo("key store password"); - assertThat(sslConfiguration.getTrustStore()) - .isInstanceOf(ClassPathResource.class); - assertThat(sslConfiguration.getTrustStorePassword()) - .isEqualTo("trust store password"); + assertThat(sslConfiguration.getTrustStore()).isInstanceOf(ClassPathResource.class); + assertThat(sslConfiguration.getTrustStorePassword()).isEqualTo("trust store password"); - configurableEnvironment.getPropertySources().remove(propertySource.getName()); + this.configurableEnvironment.getPropertySources().remove(propertySource.getName()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/AbstractVaultKeyValueTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/AbstractVaultKeyValueTemplateIntegrationTests.java index 9a355bc7..be6c2394 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/AbstractVaultKeyValueTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/AbstractVaultKeyValueTemplateIntegrationTests.java @@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mark Paluch */ @RequiresVaultVersion(VaultInitializer.VERSIONING_INTRODUCED_WITH_VALUE) -abstract class AbstractVaultKeyValueTemplateIntegrationTests - extends IntegrationTestSupport { +abstract class AbstractVaultKeyValueTemplateIntegrationTests extends IntegrationTestSupport { private final String path; @@ -49,20 +48,19 @@ abstract class AbstractVaultKeyValueTemplateIntegrationTests VaultKeyValueOperations kvOperations; - AbstractVaultKeyValueTemplateIntegrationTests(String path, - KeyValueBackend apiVersion) { + AbstractVaultKeyValueTemplateIntegrationTests(String path, KeyValueBackend apiVersion) { this.path = path; this.apiVersion = apiVersion; } @BeforeEach void before() { - kvOperations = vaultOperations.opsForKeyValue(path, apiVersion); + this.kvOperations = this.vaultOperations.opsForKeyValue(this.path, this.apiVersion); } @Test void shouldReportExpectedApiVersion() { - assertThat(kvOperations.getApiVersion()).isEqualTo(apiVersion); + assertThat(this.kvOperations.getApiVersion()).isEqualTo(this.apiVersion); } @Test @@ -72,9 +70,9 @@ abstract class AbstractVaultKeyValueTemplateIntegrationTests String key = UUID.randomUUID().toString(); - kvOperations.put(key, secret); + this.kvOperations.put(key, secret); - assertThat(kvOperations.list("/")).contains(key); + assertThat(this.kvOperations.list("/")).contains(key); } @Test @@ -84,16 +82,16 @@ abstract class AbstractVaultKeyValueTemplateIntegrationTests String key = UUID.randomUUID().toString(); - kvOperations.put(key, secret); + this.kvOperations.put(key, secret); - assertThat(kvOperations.get(key).getRequiredData()).containsEntry("key", "value"); + assertThat(this.kvOperations.get(key).getRequiredData()).containsEntry("key", "value"); } @Test void shouldReadAbsentSecret() { - assertThat(kvOperations.get("absent")).isNull(); - assertThat(kvOperations.get("absent", Person.class)).isNull(); + assertThat(this.kvOperations.get("absent")).isNull(); + assertThat(this.kvOperations.get("absent", Person.class)).isNull(); } @Test @@ -103,12 +101,10 @@ abstract class AbstractVaultKeyValueTemplateIntegrationTests person.setFirstname("Walter"); person.setLastname("Heisenberg"); - kvOperations.put("my-secret", person); + this.kvOperations.put("my-secret", person); - assertThat(kvOperations.get("my-secret").getRequiredData()) - .containsEntry("firstname", "Walter"); - assertThat(kvOperations.get("my-secret", Person.class).getRequiredData()) - .isEqualTo(person); + assertThat(this.kvOperations.get("my-secret").getRequiredData()).containsEntry("firstname", "Walter"); + assertThat(this.kvOperations.get("my-secret", Person.class).getRequiredData()).isEqualTo(person); } @Test @@ -118,9 +114,10 @@ abstract class AbstractVaultKeyValueTemplateIntegrationTests String key = UUID.randomUUID().toString(); - kvOperations.put(key, secret); - kvOperations.delete(key); + this.kvOperations.put(key, secret); + this.kvOperations.delete(key); - assertThat(kvOperations.get(key)).isNull(); + assertThat(this.kvOperations.get(key)).isNull(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/PkiSecretIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/PkiSecretIntegrationTests.java index b2eee44f..aa22d50d 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/PkiSecretIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/PkiSecretIntegrationTests.java @@ -48,15 +48,12 @@ class PkiSecretIntegrationTests extends IntegrationTestSupport { File workDir = findWorkDir(new File(System.getProperty("user.dir"))); - String cert = Files.contentOf(new File(workDir, "ca/certs/intermediate.cert.pem"), + String cert = Files.contentOf(new File(workDir, "ca/certs/intermediate.cert.pem"), StandardCharsets.US_ASCII); + + String key = Files.contentOf(new File(workDir, "ca/private/intermediate.decrypted.key.pem"), StandardCharsets.US_ASCII); - String key = Files.contentOf( - new File(workDir, "ca/private/intermediate.decrypted.key.pem"), - StandardCharsets.US_ASCII); - - Map<String, String> pembundle = Collections.singletonMap("pem_bundle", - cert + key); + Map<String, String> pembundle = Collections.singletonMap("pem_bundle", cert + key); VaultOperations vaultOperations = prepare().getVaultOperations(); vaultOperations.write("pki/config/ca", pembundle); @@ -76,4 +73,5 @@ class PkiSecretIntegrationTests extends IntegrationTestSupport { void shouldCreateCertificateCorrectly() { } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateAgentIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateAgentIntegrationTests.java index a9ec5463..339b79b3 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateAgentIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateAgentIntegrationTests.java @@ -50,34 +50,32 @@ class ReactiveVaultTemplateAgentIntegrationTests extends IntegrationTestSupport try (Socket socket = new Socket()) { - socket.connect(new InetSocketAddress(endpoint.getHost(), endpoint.getPort()), + socket.connect(new InetSocketAddress(this.endpoint.getHost(), this.endpoint.getPort()), (int) new ClientOptions().getConnectionTimeout().toMillis()); } catch (IOException e) { - throw new TestAbortedException( - "Vault Agent not available: " + e.getMessage()); + throw new TestAbortedException("Vault Agent not available: " + e.getMessage()); } } @Test void shouldUseAgentAuthentication() { - ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(endpoint, - connector); + ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(this.endpoint, this.connector); - vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")) - .as(StepVerifier::create).verifyComplete(); + vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")).as(StepVerifier::create) + .verifyComplete(); } @Test void shouldUseAgentAuthenticationWithBuilder() { - WebClientBuilder builder = WebClientBuilder.builder().endpoint(endpoint) - .httpConnector(connector); + WebClientBuilder builder = WebClientBuilder.builder().endpoint(this.endpoint).httpConnector(this.connector); ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(builder); - vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")) - .as(StepVerifier::create).verifyComplete(); + vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")).as(StepVerifier::create) + .verifyComplete(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateGenericIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateGenericIntegrationTests.java index 813582d0..4d299334 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateGenericIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/ReactiveVaultTemplateGenericIntegrationTests.java @@ -53,59 +53,48 @@ class ReactiveVaultTemplateGenericIntegrationTests extends IntegrationTestSuppor @Test void readShouldReturnAbsentKey() { - vaultOperations.read("secret/absent").as(StepVerifier::create).verifyComplete(); + this.vaultOperations.read("secret/absent").as(StepVerifier::create).verifyComplete(); } @Test void readShouldReturnExistingKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")) - .as(StepVerifier::create) // + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")).as(StepVerifier::create) // .verifyComplete(); - vaultOperations.read("secret/mykey").as(StepVerifier::create) - .consumeNextWith(actual -> assertThat(actual.getRequiredData()) - .containsEntry("hello", "world")) // + this.vaultOperations.read("secret/mykey").as(StepVerifier::create) + .consumeNextWith(actual -> assertThat(actual.getRequiredData()).containsEntry("hello", "world")) // .verifyComplete(); } @Test void readShouldReturnNestedPropertiesKey() throws IOException { - Map map = OBJECT_MAPPER.readValue( - "{ \"hello.array[0]\":\"array-value0\", \"hello.array[1]\":\"array-value1\" }", - Map.class); + Map map = this.OBJECT_MAPPER + .readValue("{ \"hello.array[0]\":\"array-value0\", \"hello.array[1]\":\"array-value1\" }", Map.class); - vaultOperations.write("secret/mykey", map).as(StepVerifier::create) - .verifyComplete(); + this.vaultOperations.write("secret/mykey", map).as(StepVerifier::create).verifyComplete(); - vaultOperations.read("secret/mykey").as(StepVerifier::create) - .consumeNextWith(actual -> { - assertThat(actual.getRequiredData()).containsEntry("hello.array[0]", - "array-value0"); - assertThat(actual.getRequiredData()).containsEntry("hello.array[1]", - "array-value1"); - }).verifyComplete(); + this.vaultOperations.read("secret/mykey").as(StepVerifier::create).consumeNextWith(actual -> { + assertThat(actual.getRequiredData()).containsEntry("hello.array[0]", "array-value0"); + assertThat(actual.getRequiredData()).containsEntry("hello.array[1]", "array-value1"); + }).verifyComplete(); } @Test void readShouldReturnNestedObjects() throws IOException { - Map map = OBJECT_MAPPER.readValue( - "{ \"array\": [ {\"hello\": \"world\"}, {\"hello1\": \"world1\"} ] }", + Map map = this.OBJECT_MAPPER.readValue("{ \"array\": [ {\"hello\": \"world\"}, {\"hello1\": \"world1\"} ] }", Map.class); - vaultOperations.write("secret/mykey", map).as(StepVerifier::create) - .verifyComplete(); + this.vaultOperations.write("secret/mykey", map).as(StepVerifier::create).verifyComplete(); - List<Map<String, String>> expected = Arrays.asList( - Collections.singletonMap("hello", "world"), + List<Map<String, String>> expected = Arrays.asList(Collections.singletonMap("hello", "world"), Collections.singletonMap("hello1", "world1")); - vaultOperations.read("secret/mykey").as(StepVerifier::create) - .consumeNextWith(actual -> { - assertThat(actual.getRequiredData()).containsEntry("array", expected); - }).verifyComplete(); + this.vaultOperations.read("secret/mykey").as(StepVerifier::create).consumeNextWith(actual -> { + assertThat(actual.getRequiredData()).containsEntry("array", expected); + }).verifyComplete(); } @Test @@ -115,11 +104,11 @@ class ReactiveVaultTemplateGenericIntegrationTests extends IntegrationTestSuppor data.put("firstname", "Walter"); data.put("password", "Secret"); - vaultOperations.write("secret/mykey", data) // + this.vaultOperations.write("secret/mykey", data) // .as(StepVerifier::create) // .verifyComplete(); - vaultOperations.read("secret/mykey", Person.class) // + this.vaultOperations.read("secret/mykey", Person.class) // .as(StepVerifier::create) // .consumeNextWith(actual -> { @@ -133,34 +122,31 @@ class ReactiveVaultTemplateGenericIntegrationTests extends IntegrationTestSuppor @Test void listShouldNotReturnAbsentKey() { - vaultOperations.list("foo").collectList().as(StepVerifier::create) + this.vaultOperations.list("foo").collectList().as(StepVerifier::create) .consumeNextWith(actual -> assertThat(actual).isEmpty()).verifyComplete(); } @Test void listShouldReturnExistingKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")) - .as(StepVerifier::create) // + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")).as(StepVerifier::create) // .verifyComplete(); - vaultOperations.list("secret").collectList().as(StepVerifier::create) - .consumeNextWith(actual -> assertThat(actual).contains("mykey")) - .verifyComplete(); + this.vaultOperations.list("secret").collectList().as(StepVerifier::create) + .consumeNextWith(actual -> assertThat(actual).contains("mykey")).verifyComplete(); } @Test void deleteShouldRemoveKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")) + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")).as(StepVerifier::create) // + .verifyComplete(); + + this.vaultOperations.delete("secret/mykey") // .as(StepVerifier::create) // .verifyComplete(); - vaultOperations.delete("secret/mykey") // - .as(StepVerifier::create) // - .verifyComplete(); - - vaultOperations.read("secret/mykey") // + this.vaultOperations.read("secret/mykey") // .as(StepVerifier::create) // .verifyComplete(); } @@ -168,25 +154,23 @@ class ReactiveVaultTemplateGenericIntegrationTests extends IntegrationTestSuppor @Test void writeShouldReturnResponse() { - vaultOperations.write("auth/token/create").as(StepVerifier::create) - .assertNext(response -> { + this.vaultOperations.write("auth/token/create").as(StepVerifier::create).assertNext(response -> { - assertThat(response.getAuth()).isNotNull(); + assertThat(response.getAuth()).isNotNull(); - }).verifyComplete(); + }).verifyComplete(); } @Test void deleteUnknownPathShouldFail() { - vaultOperations.delete("foobar").as(StepVerifier::create) - .verifyError(VaultException.class); + this.vaultOperations.delete("foobar").as(StepVerifier::create).verifyError(VaultException.class); } @Test void writeUnknownPathShouldFail() { - vaultOperations.write("foobar").as(StepVerifier::create) - .verifyError(VaultException.class); + this.vaultOperations.write("foobar").as(StepVerifier::create).verifyError(VaultException.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultIntegrationTestConfiguration.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultIntegrationTestConfiguration.java index f1e13b09..e7cfe269 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultIntegrationTestConfiguration.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultIntegrationTestConfiguration.java @@ -30,8 +30,7 @@ import org.springframework.vault.util.TestRestTemplateFactory; * @author Mark Paluch */ @Configuration -public class VaultIntegrationTestConfiguration - extends AbstractReactiveVaultConfiguration { +public class VaultIntegrationTestConfiguration extends AbstractReactiveVaultConfiguration { @Override public VaultEndpoint vaultEndpoint() { @@ -47,4 +46,5 @@ public class VaultIntegrationTestConfiguration public SslConfiguration sslConfiguration() { return Settings.createSslConfiguration(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateIntegrationTests.java index f3735b6e..a3405498 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateIntegrationTests.java @@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = VaultIntegrationTestConfiguration.class) -class VaultKeyValueTemplateIntegrationTests - extends AbstractVaultKeyValueTemplateIntegrationTests { +class VaultKeyValueTemplateIntegrationTests extends AbstractVaultKeyValueTemplateIntegrationTests { VaultKeyValueTemplateIntegrationTests() { super("secret", KeyValueBackend.unversioned()); @@ -50,11 +49,12 @@ class VaultKeyValueTemplateIntegrationTests secret.put("key", "value"); secret.put("ttl", "5"); - kvOperations.put("my-secret", secret); + this.kvOperations.put("my-secret", secret); - VaultResponse response = kvOperations.get("my-secret"); + VaultResponse response = this.kvOperations.get("my-secret"); assertThat(response.getRequiredData()).containsEntry("key", "value"); assertThat(response.getLeaseDuration()).isEqualTo(5L); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateVersionedIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateVersionedIntegrationTests.java index f2c09df4..20b7a87a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateVersionedIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultKeyValueTemplateVersionedIntegrationTests.java @@ -29,10 +29,10 @@ import org.springframework.vault.core.VaultKeyValueOperationsSupport.KeyValueBac */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = VaultIntegrationTestConfiguration.class) -class VaultKeyValueTemplateVersionedIntegrationTests - extends AbstractVaultKeyValueTemplateIntegrationTests { +class VaultKeyValueTemplateVersionedIntegrationTests extends AbstractVaultKeyValueTemplateIntegrationTests { VaultKeyValueTemplateVersionedIntegrationTests() { super("versioned", KeyValueBackend.versioned()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultNamespaceSecretIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultNamespaceSecretIntegrationTests.java index 973b4f91..78f57d12 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultNamespaceSecretIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultNamespaceSecretIntegrationTests.java @@ -61,67 +61,62 @@ import static org.assertj.core.api.Assertions.assertThat; */ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { - static final Policy POLICY = Policy.of(Policy.Rule.builder().path("/*") - .capabilities(Policy.BuiltinCapabilities.READ, - Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE) - .build()); + static final Policy POLICY = Policy + .of(Policy.Rule.builder().path("/*").capabilities(Policy.BuiltinCapabilities.READ, + Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE).build()); RestTemplateBuilder devRestTemplate; + RestTemplateBuilder maketingRestTemplate; WebClientBuilder marketingWebClientBuilder = WebClientBuilder.builder() - .httpConnector(ClientHttpConnectorFactory.create(new ClientOptions(), - Settings.createSslConfiguration())) + .httpConnector(ClientHttpConnectorFactory.create(new ClientOptions(), Settings.createSslConfiguration())) .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing"); String devToken; + String marketingToken; @BeforeEach void before() { - Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), - "Namespaces require enterprise version"); + Assumptions.assumeTrue(prepare().getVersion().isEnterprise(), "Namespaces require enterprise version"); List<String> namespaces = new ArrayList<>(Arrays.asList("dev/", "marketing/")); List<String> list = prepare().getVaultOperations().list("sys/namespaces"); namespaces.removeAll(list); for (String namespace : namespaces) { - prepare().getVaultOperations() - .write("sys/namespaces/" + namespace.replaceAll("/", "")); + prepare().getVaultOperations().write("sys/namespaces/" + namespace.replaceAll("/", "")); } - devRestTemplate = RestTemplateBuilder.builder() - .requestFactory(ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration())) - .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) - .customizers(restTemplate -> restTemplate.getInterceptors() - .add(VaultClients.createNamespaceInterceptor("dev"))); + this.devRestTemplate = RestTemplateBuilder.builder() + .requestFactory( + ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration())) + .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate + .getInterceptors().add(VaultClients.createNamespaceInterceptor("dev"))); - maketingRestTemplate = RestTemplateBuilder.builder() - .requestFactory(ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration())) + this.maketingRestTemplate = RestTemplateBuilder.builder() + .requestFactory( + ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration())) .endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT) .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing"); - VaultTemplate dev = new VaultTemplate(devRestTemplate, + VaultTemplate dev = new VaultTemplate(this.devRestTemplate, new SimpleSessionManager(new TokenAuthentication(Settings.token()))); mountKv(dev, "dev-secrets"); dev.opsForSys().createOrUpdatePolicy("relaxed", POLICY); - this.devToken = dev.opsForToken() - .create(VaultTokenRequest.builder().withPolicy("relaxed").build()) - .getToken().getToken(); + this.devToken = dev.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build()).getToken() + .getToken(); - VaultTemplate marketing = new VaultTemplate(maketingRestTemplate, + VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate, new SimpleSessionManager(new TokenAuthentication(Settings.token()))); mountKv(marketing, "marketing-secrets"); marketing.opsForSys().createOrUpdatePolicy("relaxed", POLICY); - this.marketingToken = marketing.opsForToken() - .create(VaultTokenRequest.builder().withPolicy("relaxed").build()) + this.marketingToken = marketing.opsForToken().create(VaultTokenRequest.builder().withPolicy("relaxed").build()) .getToken().getToken(); } @@ -132,22 +127,21 @@ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { Map<String, VaultMount> mounts = vaultSysOperations.getMounts(); if (!mounts.containsKey(path + "/")) { - vaultSysOperations.mount(path, VaultMount.builder().type("kv") - .options(Collections.singletonMap("version", "1")).build()); + vaultSysOperations.mount(path, + VaultMount.builder().type("kv").options(Collections.singletonMap("version", "1")).build()); } } @Test void namespaceSecretsAreIsolated() { - VaultTemplate dev = new VaultTemplate(devRestTemplate, - new SimpleSessionManager(new TokenAuthentication(devToken))); - VaultTemplate marketing = new VaultTemplate(maketingRestTemplate, - new SimpleSessionManager(new TokenAuthentication(marketingToken))); + VaultTemplate dev = new VaultTemplate(this.devRestTemplate, + new SimpleSessionManager(new TokenAuthentication(this.devToken))); + VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate, + new SimpleSessionManager(new TokenAuthentication(this.marketingToken))); dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")); - marketing.write("marketing-secrets/my-secret", - Collections.singletonMap("key", "marketing")); + marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing")); assertThat(dev.read("marketing-secrets/my-secret")).isNull(); assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull(); @@ -169,30 +163,26 @@ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { @Test void reactiveNamespaceSecretsAreIsolated() { - VaultTemplate marketing = new VaultTemplate(maketingRestTemplate, - new SimpleSessionManager(new TokenAuthentication(marketingToken))); + VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate, + new SimpleSessionManager(new TokenAuthentication(this.marketingToken))); - ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate( - marketingWebClientBuilder, - () -> Mono.just(VaultToken.of(marketingToken))); + ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate(this.marketingWebClientBuilder, + () -> Mono.just(VaultToken.of(this.marketingToken))); - marketing.write("marketing-secrets/my-secret", - Collections.singletonMap("key", "marketing")); + marketing.write("marketing-secrets/my-secret", Collections.singletonMap("key", "marketing")); assertThat(marketing.read("marketing-secrets/my-secret")).isNotNull(); - reactiveMarketing.read("marketing-secrets/my-secret").as(StepVerifier::create) - .consumeNextWith(actual -> { - assertThat(actual.getRequiredData()).containsEntry("key", - "marketing"); - }).verifyComplete(); + reactiveMarketing.read("marketing-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> { + assertThat(actual.getRequiredData()).containsEntry("key", "marketing"); + }).verifyComplete(); } @Test void shouldReportInitialized() { - VaultTemplate marketing = new VaultTemplate(maketingRestTemplate, - new SimpleSessionManager(new TokenAuthentication(marketingToken))); + VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate, + new SimpleSessionManager(new TokenAuthentication(this.marketingToken))); assertThat(marketing.opsForSys().isInitialized()).isTrue(); } @@ -200,8 +190,8 @@ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { @Test void shouldReportHealth() { - VaultTemplate marketing = new VaultTemplate(maketingRestTemplate, - new SimpleSessionManager(new TokenAuthentication(marketingToken))); + VaultTemplate marketing = new VaultTemplate(this.maketingRestTemplate, + new SimpleSessionManager(new TokenAuthentication(this.marketingToken))); assertThat(marketing.opsForSys().health().isInitialized()).isTrue(); } @@ -209,17 +199,13 @@ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { @Test void shouldReportReactiveInitialized() { - ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate( - marketingWebClientBuilder, - () -> Mono.just(VaultToken.of(marketingToken))); + ReactiveVaultTemplate reactiveMarketing = new ReactiveVaultTemplate(this.marketingWebClientBuilder, + () -> Mono.just(VaultToken.of(this.marketingToken))); reactiveMarketing.doWithSession(webClient -> { - return webClient.get().uri("sys/init") - .header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange() + return webClient.get().uri("sys/init").header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange() .flatMap(it -> it.bodyToMono(Map.class)); - }).as(StepVerifier::create) - .assertNext( - actual -> assertThat(actual).containsEntry("initialized", true)) + }).as(StepVerifier::create).assertNext(actual -> assertThat(actual).containsEntry("initialized", true)) .verifyComplete(); } @@ -242,11 +228,12 @@ class VaultNamespaceSecretIntegrationTests extends IntegrationTestSupport { } @Override - protected RestTemplateBuilder restTemplateBuilder( - VaultEndpointProvider endpointProvider, + protected RestTemplateBuilder restTemplateBuilder(VaultEndpointProvider endpointProvider, ClientHttpRequestFactory requestFactory) { return super.restTemplateBuilder(endpointProvider, requestFactory) .defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "marketing"); } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultPkiTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultPkiTemplateIntegrationTests.java index 8df0c78c..34f6e33b 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultPkiTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultPkiTemplateIntegrationTests.java @@ -71,23 +71,19 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - pkiOperations = vaultOperations.opsForPki(); + this.pkiOperations = this.vaultOperations.opsForPki(); if (!prepare().hasSecret("pki")) { prepare().mountSecret("pki"); } File workDir = findWorkDir(new File(System.getProperty("user.dir"))); - String cert = Files.contentOf(new File(workDir, "ca/certs/intermediate.cert.pem"), - "US-ASCII"); - String key = Files.contentOf( - new File(workDir, "ca/private/intermediate.decrypted.key.pem"), - "US-ASCII"); + String cert = Files.contentOf(new File(workDir, "ca/certs/intermediate.cert.pem"), "US-ASCII"); + String key = Files.contentOf(new File(workDir, "ca/private/intermediate.decrypted.key.pem"), "US-ASCII"); - Map<String, String> pembundle = Collections.singletonMap("pem_bundle", - cert + key); + Map<String, String> pembundle = Collections.singletonMap("pem_bundle", cert + key); - vaultOperations.write("pki/config/ca", pembundle); + this.vaultOperations.write("pki/config/ca", pembundle); Map<String, String> role = new HashMap<String, String>(); role.put("allowed_domains", "localhost,example.com"); @@ -96,17 +92,15 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { role.put("allow_ip_sans", "true"); role.put("max_ttl", "72h"); - vaultOperations.write("pki/roles/testrole", role); + this.vaultOperations.write("pki/roles/testrole", role); } @Test void issueCertificateShouldCreateCertificate() { - VaultCertificateRequest request = VaultCertificateRequest - .create("hello.example.com"); + VaultCertificateRequest request = VaultCertificateRequest.create("hello.example.com"); - VaultCertificateResponse certificateResponse = pkiOperations - .issueCertificate("testrole", request); + VaultCertificateResponse certificateResponse = this.pkiOperations.issueCertificate("testrole", request); CertificateBundle data = certificateResponse.getRequiredData(); @@ -114,26 +108,22 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { assertThat(data.getCertificate()).isNotEmpty(); assertThat(data.getIssuingCaCertificate()).isNotEmpty(); assertThat(data.getSerialNumber()).isNotEmpty(); - assertThat(data.getX509Certificate().getSubjectX500Principal().getName()) - .isEqualTo("CN=hello.example.com"); + assertThat(data.getX509Certificate().getSubjectX500Principal().getName()).isEqualTo("CN=hello.example.com"); } @Test @RequiresVaultVersion(NO_TTL_UNIT_REQUIRED_FROM) void issueCertificateWithTtlShouldCreateCertificate() { - VaultCertificateRequest request = VaultCertificateRequest.builder() - .ttl(Duration.ofHours(48)).commonName("hello.example.com").build(); + VaultCertificateRequest request = VaultCertificateRequest.builder().ttl(Duration.ofHours(48)) + .commonName("hello.example.com").build(); - VaultCertificateResponse certificateResponse = pkiOperations - .issueCertificate("testrole", request); + VaultCertificateResponse certificateResponse = this.pkiOperations.issueCertificate("testrole", request); - X509Certificate certificate = certificateResponse.getRequiredData() - .getX509Certificate(); + X509Certificate certificate = certificateResponse.getRequiredData().getX509Certificate(); Instant now = Instant.now(); - assertThat(certificate.getNotAfter()) - .isAfter(Date.from(now.plus(40, ChronoUnit.HOURS))) + assertThat(certificate.getNotAfter()).isAfter(Date.from(now.plus(40, ChronoUnit.HOURS))) .isBefore(Date.from(now.plus(50, ChronoUnit.HOURS))); } @@ -155,22 +145,20 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { + "Vn93GO7cfaTOetK0VtDqis1VFQD0eVPWf5s6UqT/+XGrFRhwJ9hM+2FQSrUDFecs\n" + "+/605n1rD7qOj3vkGrtwvEUrxyRaQaKpPLHmVHENqV6F1NsO3Z27f2FWWAZF2VKN\n" + "cCQQJNc//DbIN3J3JSElpIDBDHctoBoQVnMiwpCbSA+CaAtlWYJKnAfhTKeqnNMy\n" - + "qf3ACZ+1sBIuqSP7dEJ2KfIezaCPQ88+PAloRB52LFa+iq3yI7F5VzkwAvQFnTi+\n" - + "cQ==\n" + "-----END CERTIFICATE REQUEST-----"; + + "qf3ACZ+1sBIuqSP7dEJ2KfIezaCPQ88+PAloRB52LFa+iq3yI7F5VzkwAvQFnTi+\n" + "cQ==\n" + + "-----END CERTIFICATE REQUEST-----"; - VaultCertificateRequest request = VaultCertificateRequest - .create("hello.example.com"); + VaultCertificateRequest request = VaultCertificateRequest.create("hello.example.com"); - VaultSignCertificateRequestResponse certificateResponse = pkiOperations - .signCertificateRequest("testrole", csr, request); + VaultSignCertificateRequestResponse certificateResponse = this.pkiOperations.signCertificateRequest("testrole", + csr, request); Certificate data = certificateResponse.getRequiredData(); assertThat(data.getCertificate()).isNotEmpty(); assertThat(data.getIssuingCaCertificate()).isNotEmpty(); assertThat(data.getSerialNumber()).isNotEmpty(); - assertThat(data.getX509Certificate().getSubjectX500Principal().getName()) - .isEqualTo("CN=csr.example.com"); + assertThat(data.getX509Certificate().getSubjectX500Principal().getName()).isEqualTo("CN=csr.example.com"); assertThat(data.createTrustStore()).isNotNull(); } @@ -180,23 +168,21 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { VaultCertificateRequest request = VaultCertificateRequest.create("not.supported"); assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> pkiOperations.issueCertificate("testrole", request)); + .isThrownBy(() -> this.pkiOperations.issueCertificate("testrole", request)); } @Test void shouldRevokeCertificate() throws Exception { - VaultCertificateRequest request = VaultCertificateRequest - .create("foo.example.com"); + VaultCertificateRequest request = VaultCertificateRequest.create("foo.example.com"); - VaultCertificateResponse certificateResponse = pkiOperations - .issueCertificate("testrole", request); + VaultCertificateResponse certificateResponse = this.pkiOperations.issueCertificate("testrole", request); - BigInteger serial = new BigInteger(certificateResponse.getRequiredData() - .getSerialNumber().replaceAll("\\:", ""), 16); - pkiOperations.revoke(certificateResponse.getRequiredData().getSerialNumber()); + BigInteger serial = new BigInteger( + certificateResponse.getRequiredData().getSerialNumber().replaceAll("\\:", ""), 16); + this.pkiOperations.revoke(certificateResponse.getRequiredData().getSerialNumber()); - try (InputStream in = pkiOperations.getCrl(Encoding.DER)) { + try (InputStream in = this.pkiOperations.getCrl(Encoding.DER)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); @@ -209,17 +195,18 @@ class VaultPkiTemplateIntegrationTests extends IntegrationTestSupport { @Test void shouldReturnCrl() throws Exception { - try (InputStream in = pkiOperations.getCrl(Encoding.DER)) { + try (InputStream in = this.pkiOperations.getCrl(Encoding.DER)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); assertThat(cf.generateCRL(in)).isInstanceOf(X509CRL.class); } - try (InputStream crl = pkiOperations.getCrl(Encoding.PEM)) { + try (InputStream crl = this.pkiOperations.getCrl(Encoding.PEM)) { byte[] bytes = StreamUtils.copyToByteArray(crl); assertThat(bytes).isNotEmpty(); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateIntegrationTests.java index dd579acd..3bb4c014 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateIntegrationTests.java @@ -60,13 +60,13 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - adminOperations = vaultOperations.opsForSys(); + this.adminOperations = this.vaultOperations.opsForSys(); } @Test void getMountsShouldContainSecretBackend() { - Map<String, VaultMount> mounts = adminOperations.getMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getMounts(); assertThat(mounts).containsKey("secret/"); @@ -77,17 +77,16 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @Test void mountShouldMountGenericSecret() { - if (adminOperations.getMounts().containsKey("other/")) { - adminOperations.unmount("other"); + if (this.adminOperations.getMounts().containsKey("other/")) { + this.adminOperations.unmount("other"); } VaultMount mount = VaultMount.builder().type("generic") - .config(Collections.singletonMap("default_lease_ttl", "1h")) - .description("hello, world").build(); + .config(Collections.singletonMap("default_lease_ttl", "1h")).description("hello, world").build(); - adminOperations.mount("other", mount); + this.adminOperations.mount("other", mount); - Map<String, VaultMount> mounts = adminOperations.getMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getMounts(); assertThat(mounts).containsKey("other/"); @@ -101,17 +100,16 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(VaultInitializer.VERSIONING_INTRODUCED_WITH_VALUE) void mountShouldMountKv1Secret() { - if (adminOperations.getMounts().containsKey("kVv1/")) { - adminOperations.unmount("kVv1"); + if (this.adminOperations.getMounts().containsKey("kVv1/")) { + this.adminOperations.unmount("kVv1"); } - VaultMount mount = VaultMount.builder().type("kv") - .config(Collections.singletonMap("default_lease_ttl", "1h")) + VaultMount mount = VaultMount.builder().type("kv").config(Collections.singletonMap("default_lease_ttl", "1h")) .description("hello, world").build(); - adminOperations.mount("kVv1", mount); + this.adminOperations.mount("kVv1", mount); - Map<String, VaultMount> mounts = adminOperations.getMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getMounts(); assertThat(mounts).containsKey("kVv1/"); @@ -120,9 +118,9 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { assertThat(kVv1.getConfig()).containsEntry("default_lease_ttl", 3600); assertThat(kVv1.getType()).isEqualTo("kv"); - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); - VaultResponse read = vaultOperations.read("secret/mykey"); + VaultResponse read = this.vaultOperations.read("secret/mykey"); assertThat(read).isNotNull(); assertThat(read.getRequiredData()).containsEntry("hello", "world"); } @@ -131,18 +129,16 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(VaultInitializer.VERSIONING_INTRODUCED_WITH_VALUE) void mountShouldMountKv2Secret() { - if (adminOperations.getMounts().containsKey("kVv2/")) { - adminOperations.unmount("kVv2"); + if (this.adminOperations.getMounts().containsKey("kVv2/")) { + this.adminOperations.unmount("kVv2"); } - VaultMount mount = VaultMount.builder().type("kv") - .config(Collections.singletonMap("default_lease_ttl", "1h")) - .options(Collections.singletonMap("version", "2")) - .description("hello, world").build(); + VaultMount mount = VaultMount.builder().type("kv").config(Collections.singletonMap("default_lease_ttl", "1h")) + .options(Collections.singletonMap("version", "2")).description("hello, world").build(); - adminOperations.mount("kVv2", mount); + this.adminOperations.mount("kVv2", mount); - Map<String, VaultMount> mounts = adminOperations.getMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getMounts(); assertThat(mounts).containsKey("kVv2/"); @@ -152,18 +148,16 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { assertThat(kVv2.getType()).isEqualTo("kv"); assertThat(kVv2.getOptions()).containsEntry("version", "2"); - VaultVersionedKeyValueOperations versionedOperations = vaultOperations - .opsForVersionedKeyValue("kVv2"); + VaultVersionedKeyValueOperations versionedOperations = this.vaultOperations.opsForVersionedKeyValue("kVv2"); versionedOperations.put("secret/mykey", Collections.singletonMap("key", "value")); - assertThat(versionedOperations.get("secret/mykey").getRequiredData()) - .containsEntry("key", "value"); + assertThat(versionedOperations.get("secret/mykey").getRequiredData()).containsEntry("key", "value"); } @Test void getAuthMountsShouldContainSecretBackend() { - Map<String, VaultMount> mounts = adminOperations.getAuthMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getAuthMounts(); assertThat(mounts).containsKey("token/"); @@ -175,16 +169,15 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @Test void authMountShouldMountGenericSecret() { - if (adminOperations.getAuthMounts().containsKey("other/")) { - adminOperations.authUnmount("other"); + if (this.adminOperations.getAuthMounts().containsKey("other/")) { + this.adminOperations.authUnmount("other"); } - VaultMount mount = VaultMount.builder().type("userpass") - .description("hello, world").build(); + VaultMount mount = VaultMount.builder().type("userpass").description("hello, world").build(); - adminOperations.authMount("other", mount); + this.adminOperations.authMount("other", mount); - Map<String, VaultMount> mounts = adminOperations.getAuthMounts(); + Map<String, VaultMount> mounts = this.adminOperations.getAuthMounts(); assertThat(mounts).containsKey("other/"); @@ -197,7 +190,7 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion("0.6.1") void shouldEnumeratePolicyNames() { - List<String> policyNames = adminOperations.getPolicyNames(); + List<String> policyNames = this.adminOperations.getPolicyNames(); assertThat(policyNames).contains("root", "default"); } @@ -206,7 +199,7 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion("0.6.1") void shouldReadRootPolicy() { - Policy root = adminOperations.getPolicy("root"); + Policy root = this.adminOperations.getPolicy("root"); assertThat(root).isEqualTo(Policy.empty()); } @@ -215,7 +208,7 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion("0.6.1") void shouldReadAbsentRootPolicy() { - Policy root = adminOperations.getPolicy("absent-policy"); + Policy root = this.adminOperations.getPolicy("absent-policy"); assertThat(root).isNull(); } @@ -225,22 +218,21 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { void shouldReadDefaultPolicy() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> adminOperations.getPolicy("default")); + .isThrownBy(() -> this.adminOperations.getPolicy("default")); } @Test @RequiresVaultVersion("0.7.0") void shouldCreatePolicy() { - Rule rule = Rule.builder().path("foo").capabilities(READ, UPDATE) - .minWrappingTtl(Duration.ofSeconds(100)) + Rule rule = Rule.builder().path("foo").capabilities(READ, UPDATE).minWrappingTtl(Duration.ofSeconds(100)) .maxWrappingTtl(Duration.ofHours(2)).build(); - adminOperations.createOrUpdatePolicy("foo", Policy.of(rule)); + this.adminOperations.createOrUpdatePolicy("foo", Policy.of(rule)); - assertThat(adminOperations.getPolicyNames()).contains("foo"); + assertThat(this.adminOperations.getPolicyNames()).contains("foo"); - Policy loaded = adminOperations.getPolicy("foo"); + Policy loaded = this.adminOperations.getPolicy("foo"); assertThat(loaded.getRules()).contains(rule); } @@ -250,18 +242,18 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { Rule rule = Rule.builder().path("foo").capabilities(READ).build(); - adminOperations.createOrUpdatePolicy("foo", Policy.of(rule)); + this.adminOperations.createOrUpdatePolicy("foo", Policy.of(rule)); - adminOperations.deletePolicy("foo"); + this.adminOperations.deletePolicy("foo"); - assertThat(adminOperations.getPolicyNames()).doesNotContain("foo"); + assertThat(this.adminOperations.getPolicyNames()).doesNotContain("foo"); } @Test @RequiresVaultVersion("0.6.1") void shouldReportHealth() { - VaultHealth health = adminOperations.health(); + VaultHealth health = this.adminOperations.health(); assertThat(health.isInitialized()).isTrue(); assertThat(health.isSealed()).isFalse(); @@ -272,15 +264,16 @@ class VaultSysTemplateIntegrationTests extends IntegrationTestSupport { @Test void isInitializedShouldReturnTrue() { - assertThat(adminOperations.isInitialized()).isTrue(); + assertThat(this.adminOperations.isInitialized()).isTrue(); } @Test void getUnsealStatusShouldReturnStatus() { - VaultUnsealStatus unsealStatus = adminOperations.getUnsealStatus(); + VaultUnsealStatus unsealStatus = this.adminOperations.getUnsealStatus(); assertThat(unsealStatus.isSealed()).isFalse(); assertThat(unsealStatus.getProgress()).isEqualTo(0); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateUnitTests.java index 7a0ed716..f2d15b81 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultSysTemplateUnitTests.java @@ -29,14 +29,15 @@ class VaultSysTemplateUnitTests { @Test void shouldReportRecoveryReplicationMode() { - VaultSysTemplate.VaultHealthImpl disabled = new VaultSysTemplate.VaultHealthImpl( - true, true, true, true, "disabled", 0, null); + VaultSysTemplate.VaultHealthImpl disabled = new VaultSysTemplate.VaultHealthImpl(true, true, true, true, + "disabled", 0, null); assertThat(disabled.isRecoveryReplicationSecondary()).isFalse(); - VaultSysTemplate.VaultHealthImpl enabled = new VaultSysTemplate.VaultHealthImpl( - true, true, true, true, "enabled", 0, null); + VaultSysTemplate.VaultHealthImpl enabled = new VaultSysTemplate.VaultHealthImpl(true, true, true, true, + "enabled", 0, null); assertThat(enabled.isRecoveryReplicationSecondary()).isTrue(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateAgentIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateAgentIntegrationTests.java index 298fb289..ca5b1dd1 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateAgentIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateAgentIntegrationTests.java @@ -39,8 +39,8 @@ import org.springframework.vault.util.Settings; */ class VaultTemplateAgentIntegrationTests extends IntegrationTestSupport { - ClientHttpRequestFactory requestFactory = ClientHttpRequestFactoryFactory - .create(new ClientOptions(), Settings.createSslConfiguration()); + ClientHttpRequestFactory requestFactory = ClientHttpRequestFactoryFactory.create(new ClientOptions(), + Settings.createSslConfiguration()); VaultEndpoint endpoint = VaultEndpoint.create("localhost", 8202); @@ -49,19 +49,18 @@ class VaultTemplateAgentIntegrationTests extends IntegrationTestSupport { try (Socket socket = new Socket()) { - socket.connect(new InetSocketAddress(endpoint.getHost(), endpoint.getPort()), + socket.connect(new InetSocketAddress(this.endpoint.getHost(), this.endpoint.getPort()), (int) new ClientOptions().getConnectionTimeout().toMillis()); } catch (IOException e) { - throw new TestAbortedException( - "Vault Agent not available: " + e.getMessage()); + throw new TestAbortedException("Vault Agent not available: " + e.getMessage()); } } @Test void shouldUseAgentAuthentication() { - VaultTemplate vaultTemplate = new VaultTemplate(endpoint, requestFactory); + VaultTemplate vaultTemplate = new VaultTemplate(this.endpoint, this.requestFactory); vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")); } @@ -69,11 +68,12 @@ class VaultTemplateAgentIntegrationTests extends IntegrationTestSupport { @Test void shouldUseAgentAuthenticationWithBuilder() { - RestTemplateBuilder builder = RestTemplateBuilder.builder().endpoint(endpoint) - .requestFactory(requestFactory); + RestTemplateBuilder builder = RestTemplateBuilder.builder().endpoint(this.endpoint) + .requestFactory(this.requestFactory); VaultTemplate vaultTemplate = new VaultTemplate(builder); vaultTemplate.write("secret/foo", Collections.singletonMap("key", "value")); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateGenericIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateGenericIntegrationTests.java index 91da8230..7ffd1c94 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateGenericIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateGenericIntegrationTests.java @@ -53,7 +53,7 @@ class VaultTemplateGenericIntegrationTests extends IntegrationTestSupport { @Test void readShouldReturnAbsentKey() { - VaultResponse read = vaultOperations.read("secret/absent"); + VaultResponse read = this.vaultOperations.read("secret/absent"); assertThat(read).isNull(); } @@ -61,9 +61,9 @@ class VaultTemplateGenericIntegrationTests extends IntegrationTestSupport { @Test void readShouldReturnExistingKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); - VaultResponse read = vaultOperations.read("secret/mykey"); + VaultResponse read = this.vaultOperations.read("secret/mykey"); assertThat(read).isNotNull(); assertThat(read.getRequiredData()).containsEntry("hello", "world"); } @@ -71,32 +71,27 @@ class VaultTemplateGenericIntegrationTests extends IntegrationTestSupport { @Test void readShouldReturnNestedPropertiesKey() throws Exception { - Map map = OBJECT_MAPPER.readValue( - "{ \"hello.array[0]\":\"array-value0\", \"hello.array[1]\":\"array-value1\" }", - Map.class); - vaultOperations.write("secret/mykey", map); + Map map = this.OBJECT_MAPPER + .readValue("{ \"hello.array[0]\":\"array-value0\", \"hello.array[1]\":\"array-value1\" }", Map.class); + this.vaultOperations.write("secret/mykey", map); - VaultResponse read = vaultOperations.read("secret/mykey"); + VaultResponse read = this.vaultOperations.read("secret/mykey"); assertThat(read).isNotNull(); - assertThat(read.getRequiredData()).containsEntry("hello.array[0]", - "array-value0"); - assertThat(read.getRequiredData()).containsEntry("hello.array[1]", - "array-value1"); + assertThat(read.getRequiredData()).containsEntry("hello.array[0]", "array-value0"); + assertThat(read.getRequiredData()).containsEntry("hello.array[1]", "array-value1"); } @Test void readShouldReturnNestedObjects() throws Exception { - Map map = OBJECT_MAPPER.readValue( - "{ \"array\": [ {\"hello\": \"world\"}, {\"hello1\": \"world1\"} ] }", + Map map = this.OBJECT_MAPPER.readValue("{ \"array\": [ {\"hello\": \"world\"}, {\"hello1\": \"world1\"} ] }", Map.class); - vaultOperations.write("secret/mykey", map); + this.vaultOperations.write("secret/mykey", map); - VaultResponse read = vaultOperations.read("secret/mykey"); + VaultResponse read = this.vaultOperations.read("secret/mykey"); assertThat(read).isNotNull(); - assertThat(read.getRequiredData()).containsEntry("array", - Arrays.asList(Collections.singletonMap("hello", "world"), - Collections.singletonMap("hello1", "world1"))); + assertThat(read.getRequiredData()).containsEntry("array", Arrays + .asList(Collections.singletonMap("hello", "world"), Collections.singletonMap("hello1", "world1"))); } @Test @@ -106,10 +101,9 @@ class VaultTemplateGenericIntegrationTests extends IntegrationTestSupport { data.put("firstname", "Walter"); data.put("password", "Secret"); - vaultOperations.write("secret/mykey", data); + this.vaultOperations.write("secret/mykey", data); - VaultResponseSupport<Person> read = vaultOperations.read("secret/mykey", - Person.class); + VaultResponseSupport<Person> read = this.vaultOperations.read("secret/mykey", Person.class); assertThat(read).isNotNull(); Person person = read.getRequiredData(); @@ -120,27 +114,28 @@ class VaultTemplateGenericIntegrationTests extends IntegrationTestSupport { @Test void listShouldReturnExistingKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); - List<String> keys = vaultOperations.list("secret"); + List<String> keys = this.vaultOperations.list("secret"); assertThat(keys).contains("mykey"); } @Test void listShouldNotReturnAbsentKey() { - List<String> keys = vaultOperations.list("foo"); + List<String> keys = this.vaultOperations.list("foo"); assertThat(keys).isEmpty(); } @Test void deleteShouldRemoveKey() { - vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); + this.vaultOperations.write("secret/mykey", Collections.singletonMap("hello", "world")); - vaultOperations.delete("secret/mykey"); + this.vaultOperations.delete("secret/mykey"); - VaultResponse read = vaultOperations.read("secret/mykey"); + VaultResponse read = this.vaultOperations.read("secret/mykey"); assertThat(read).isNull(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateTransitIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateTransitIntegrationTests.java index 7394c021..026a8289 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateTransitIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTemplateTransitIntegrationTests.java @@ -53,9 +53,9 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - VaultSysOperations adminOperations = vaultOperations.opsForSys(); + VaultSysOperations adminOperations = this.vaultOperations.opsForSys(); - vaultVersion = prepare().getVersion(); + this.vaultVersion = prepare().getVersion(); if (!adminOperations.getMounts().containsKey("transit/")) { adminOperations.mount("transit", VaultMount.create("transit")); @@ -63,7 +63,7 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { removeKeys(); - vaultOperations.write("transit/keys/mykey", null); + this.vaultOperations.write("transit/keys/mykey", null); } @AfterEach @@ -74,14 +74,14 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { private void deleteKey(String keyName) { try { - vaultOperations.opsForTransit().configureKey(keyName, + this.vaultOperations.opsForTransit().configureKey(keyName, VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); } catch (Exception e) { } try { - vaultOperations.opsForTransit().deleteKey(keyName); + this.vaultOperations.opsForTransit().deleteKey(keyName); } catch (Exception e) { } @@ -89,8 +89,8 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { private void removeKeys() { - if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { - List<String> keys = vaultOperations.opsForTransit().getKeys(); + if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { + List<String> keys = this.vaultOperations.opsForTransit().getKeys(); keys.forEach(this::deleteKey); } else { @@ -101,9 +101,8 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { @Test void shouldEncrypt() { - VaultResponse response = vaultOperations.write("transit/encrypt/mykey", - Collections.singletonMap("plaintext", - Base64Utils.encodeToString("that message is secret".getBytes()))); + VaultResponse response = this.vaultOperations.write("transit/encrypt/mykey", + Collections.singletonMap("plaintext", Base64Utils.encodeToString("that message is secret".getBytes()))); assertThat((String) response.getRequiredData().get("ciphertext")).isNotEmpty(); } @@ -111,15 +110,14 @@ class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport { @Test void shouldEncryptAndDecrypt() { - VaultResponse response = vaultOperations.write("transit/encrypt/mykey", - Collections.singletonMap("plaintext", - Base64Utils.encodeToString("that message is secret".getBytes()))); + VaultResponse response = this.vaultOperations.write("transit/encrypt/mykey", + Collections.singletonMap("plaintext", Base64Utils.encodeToString("that message is secret".getBytes()))); - VaultResponse decrypted = vaultOperations.write("transit/decrypt/mykey", - Collections.singletonMap("ciphertext", - response.getRequiredData().get("ciphertext"))); + VaultResponse decrypted = this.vaultOperations.write("transit/decrypt/mykey", + Collections.singletonMap("ciphertext", response.getRequiredData().get("ciphertext"))); - assertThat((String) decrypted.getRequiredData().get("plaintext")).isEqualTo( - Base64Utils.encodeToString("that message is secret".getBytes())); + assertThat((String) decrypted.getRequiredData().get("plaintext")) + .isEqualTo(Base64Utils.encodeToString("that message is secret".getBytes())); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTokenTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTokenTemplateIntegrationTests.java index 222a8c25..78c92c4c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTokenTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTokenTemplateIntegrationTests.java @@ -56,21 +56,20 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - tokenOperations = vaultOperations.opsForToken(); + this.tokenOperations = this.vaultOperations.opsForToken(); } @Test void createTokenShouldCreateANewToken() { - VaultTokenResponse tokenResponse = tokenOperations.create(); + VaultTokenResponse tokenResponse = this.tokenOperations.create(); assertThat(tokenResponse.getAuth()).containsKey("client_token"); } @Test void createTokenShouldCreateACustomizedToken() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .displayName("display") // + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().displayName("display") // .explicitMaxTtl(Duration.ofHours(5)) // .ttl(Duration.ofMinutes(30 * 60)) // .policies(Collections.singleton("root")) // @@ -81,23 +80,21 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { .id(UUID.randomUUID().toString()) // .build(); - VaultTokenResponse tokenResponse = tokenOperations.create(tokenRequest); - assertThat(tokenResponse.getAuth()).containsEntry("client_token", - tokenRequest.getId()); + VaultTokenResponse tokenResponse = this.tokenOperations.create(tokenRequest); + assertThat(tokenResponse.getAuth()).containsEntry("client_token", tokenRequest.getId()); } @Test void createOrphanTokenShouldCreateAToken() { - VaultTokenResponse tokenResponse = tokenOperations.createOrphan(); + VaultTokenResponse tokenResponse = this.tokenOperations.createOrphan(); assertThat(tokenResponse.getAuth()).containsKey("client_token"); } @Test void createOrphanTokenShouldCreateACustomizedToken() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .displayName("display") // + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().displayName("display") // .explicitMaxTtl(Duration.ofHours(5)) // .ttl(Duration.ofMinutes(30 * 60)) // .policies(Collections.singleton("root")) // @@ -108,22 +105,20 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { .id(UUID.randomUUID().toString()) // .build(); - VaultTokenResponse tokenResponse = tokenOperations.createOrphan(tokenRequest); - assertThat(tokenResponse.getAuth()).containsEntry("client_token", - tokenRequest.getId()); + VaultTokenResponse tokenResponse = this.tokenOperations.createOrphan(tokenRequest); + assertThat(tokenResponse.getAuth()).containsEntry("client_token", tokenRequest.getId()); } @Test void renewShouldRenewToken() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .explicitMaxTtl(Duration.ofHours(5)) // + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().explicitMaxTtl(Duration.ofHours(5)) // .ttl(Duration.ofMinutes(30 * 60)) // .renewable() // .build(); - VaultTokenResponse tokenResponse = tokenOperations.create(tokenRequest); - VaultTokenResponse renew = tokenOperations.renew(tokenResponse.getToken()); + VaultTokenResponse tokenResponse = this.tokenOperations.create(tokenRequest); + VaultTokenResponse renew = this.tokenOperations.renew(tokenResponse.getToken()); assertThat(renew.getAuth()).containsKey("client_token"); } @@ -131,17 +126,17 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { @Test void renewShouldFailForNonRenewableRenewTokens() { - VaultTokenResponse tokenResponse = tokenOperations.create(); + VaultTokenResponse tokenResponse = this.tokenOperations.create(); assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> tokenOperations.renew(tokenResponse.getToken())); + .isThrownBy(() -> this.tokenOperations.renew(tokenResponse.getToken())); } @Test void revokeShouldRevokeToken() { - final VaultTokenResponse tokenResponse = tokenOperations.create(); - tokenOperations.revoke(tokenResponse.getToken()); + final VaultTokenResponse tokenResponse = this.tokenOperations.create(); + this.tokenOperations.revoke(tokenResponse.getToken()); try { lookupSelf(tokenResponse); @@ -154,7 +149,7 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { @Test void createdTokenShouldBeUsableWithVaultClient() { - final VaultTokenResponse tokenResponse = tokenOperations.create(); + final VaultTokenResponse tokenResponse = this.tokenOperations.create(); ResponseEntity<String> response = lookupSelf(tokenResponse); @@ -164,14 +159,14 @@ class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport { @SuppressWarnings("ConstantConditions") private ResponseEntity<String> lookupSelf(final VaultTokenResponse tokenResponse) { - return vaultOperations.doWithVault(restOperations -> { + return this.vaultOperations.doWithVault(restOperations -> { HttpHeaders headers = new HttpHeaders(); - headers.add(VaultHttpHeaders.VAULT_TOKEN, - tokenResponse.getToken().getToken()); + headers.add(VaultHttpHeaders.VAULT_TOKEN, tokenResponse.getToken().getToken()); - return restOperations.exchange("auth/token/lookup-self", HttpMethod.GET, - new HttpEntity<>(headers), String.class); + return restOperations.exchange("auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>(headers), + String.class); }); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTransitTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTransitTemplateIntegrationTests.java index 9c57b790..6e537113 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTransitTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultTransitTemplateIntegrationTests.java @@ -84,13 +84,13 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - transitOperations = vaultOperations.opsForTransit(); + this.transitOperations = this.vaultOperations.opsForTransit(); - if (!vaultOperations.opsForSys().getMounts().containsKey("transit/")) { - vaultOperations.opsForSys().mount("transit", VaultMount.create("transit")); + if (!this.vaultOperations.opsForSys().getMounts().containsKey("transit/")) { + this.vaultOperations.opsForSys().mount("transit", VaultMount.create("transit")); } - vaultVersion = prepare().getVersion(); + this.vaultVersion = prepare().getVersion(); removeKeys(); } @@ -103,14 +103,14 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { private void deleteKey(String keyName) { try { - transitOperations.configureKey(keyName, + this.transitOperations.configureKey(keyName, VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); } catch (Exception e) { } try { - transitOperations.deleteKey(keyName); + this.transitOperations.deleteKey(keyName); } catch (Exception e) { } @@ -118,8 +118,8 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { private void removeKeys() { - if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { - List<String> keys = vaultOperations.opsForTransit().getKeys(); + if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { + List<String> keys = this.vaultOperations.opsForTransit().getKeys(); for (String keyName : keys) { deleteKey(keyName); } @@ -135,9 +135,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void createKeyShouldCreateKey() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - VaultTransitKey mykey = transitOperations.getKey("mykey"); + VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getType()).startsWith("aes"); @@ -147,7 +147,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { assertThat(mykey.getMinDecryptionVersion()).isEqualTo(1); assertThat(mykey.getLatestVersion()).isEqualTo(1); - if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.7.0"))) { + if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.7.0"))) { assertThat(mykey.supportsDecryption()).isTrue(); assertThat(mykey.supportsEncryption()).isTrue(); @@ -162,7 +162,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); - VaultTransitKey mykey = transitOperations.getKey(keyName); + VaultTransitKey mykey = this.transitOperations.getKey(keyName); assertThat(mykey.getType()).startsWith("ecdsa"); assertThat(mykey.getKeys()).isNotEmpty(); @@ -172,12 +172,11 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void createKeyShouldCreateEdKey() { - VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest - .ofKeyType("ed25519"); + VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.ofKeyType("ed25519"); - transitOperations.createKey("ed-key", request); + this.transitOperations.createKey("ed-key", request); - VaultTransitKey mykey = transitOperations.getKey("ed-key"); + VaultTransitKey mykey = this.transitOperations.getKey("ed-key"); assertThat(mykey.getType()).startsWith("ed"); assertThat(mykey.getKeys()).isNotEmpty(); @@ -191,9 +190,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { .derived(true) // .build(); - transitOperations.createKey("mykey", request); + this.transitOperations.createKey("mykey", request); - VaultTransitKey mykey = transitOperations.getKey("mykey"); + VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getName()).isEqualTo("mykey"); assertThat(mykey.isDeletionAllowed()).isFalse(); @@ -205,21 +204,20 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void shouldConfigureKey() { - transitOperations.createKey("mykey"); - transitOperations.rotate("mykey"); - transitOperations.rotate("mykey"); + this.transitOperations.createKey("mykey"); + this.transitOperations.rotate("mykey"); + this.transitOperations.rotate("mykey"); - VaultTransitKeyConfiguration configuration = VaultTransitKeyConfiguration - .builder().deletionAllowed(true).minDecryptionVersion(1) - .minEncryptionVersion(2).build(); + VaultTransitKeyConfiguration configuration = VaultTransitKeyConfiguration.builder().deletionAllowed(true) + .minDecryptionVersion(1).minEncryptionVersion(2).build(); - transitOperations.configureKey("mykey", configuration); + this.transitOperations.configureKey("mykey", configuration); - VaultTransitKey mykey = transitOperations.getKey("mykey"); + VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getMinDecryptionVersion()).isEqualTo(1); - if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.8.0"))) { + if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.8.0"))) { assertThat(mykey.getMinEncryptionVersion()).isEqualTo(2); } else { @@ -231,17 +229,17 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion("0.6.4") void shouldEnumerateKey() { - assertThat(transitOperations.getKeys()).isEmpty(); + assertThat(this.transitOperations.getKeys()).isEmpty(); - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - assertThat(transitOperations.getKeys()).contains("mykey"); + assertThat(this.transitOperations.getKeys()).contains("mykey"); } @Test void getKeyShouldReturnNullIfKeyNotExists() { - VaultTransitKey key = transitOperations.getKey("hello-world"); + VaultTransitKey key = this.transitOperations.getKey("hello-world"); assertThat(key).isNull(); } @@ -249,7 +247,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { void deleteKeyShouldFailIfKeyNotExists() { try { - transitOperations.deleteKey("hello-world"); + this.transitOperations.deleteKey("hello-world"); fail("Missing VaultException"); } catch (VaultException e) { @@ -260,36 +258,34 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void deleteKeyShouldDeleteKey() { - transitOperations.createKey("mykey"); - transitOperations.configureKey("mykey", + this.transitOperations.createKey("mykey"); + this.transitOperations.configureKey("mykey", VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); - transitOperations.deleteKey("mykey"); + this.transitOperations.deleteKey("mykey"); - assertThat(transitOperations.getKey("mykey")).isNull(); + assertThat(this.transitOperations.getKey("mykey")).isNull(); } @Test void encryptShouldCreateCiphertext() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - String ciphertext = transitOperations.encrypt("mykey", "hello-world"); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); assertThat(ciphertext).startsWith("vault:v"); } @Test void encryptShouldCreateCiphertextWithNonceAndContext() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); - VaultTransitContext transitRequest = VaultTransitContext.builder() - .context("blubb".getBytes()) // + VaultTransitContext transitRequest = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - String ciphertext = transitOperations.encrypt("mykey", "hello-world".getBytes(), - transitRequest); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); assertThat(ciphertext).startsWith("vault:v1:"); } @@ -297,16 +293,14 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void encryptShouldEncryptEmptyValues() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); - VaultTransitContext context = VaultTransitContext.builder() - .context("blubb".getBytes()) // + VaultTransitContext context = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - Ciphertext ciphertext = transitOperations.encrypt("mykey", - Plaintext.of("").with(context)); + Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("").with(context)); assertThat(ciphertext.getCiphertext()).startsWith("vault:v1:"); assertThat(ciphertext.getContext()).isEqualTo(context); @@ -315,16 +309,14 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void encryptShouldCreateWrappedCiphertextWithNonceAndContext() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); - VaultTransitContext context = VaultTransitContext.builder() - .context("blubb".getBytes()) // + VaultTransitContext context = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - Ciphertext ciphertext = transitOperations.encrypt("mykey", - Plaintext.of("hello-world").with(context)); + Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("hello-world").with(context)); assertThat(ciphertext.getCiphertext()).startsWith("vault:v1:"); assertThat(ciphertext.getContext()).isEqualTo(context); @@ -333,10 +325,10 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void decryptShouldCreatePlaintext() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - String ciphertext = transitOperations.encrypt("mykey", "hello-world"); - String plaintext = transitOperations.decrypt("mykey", ciphertext); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); + String plaintext = this.transitOperations.decrypt("mykey", ciphertext); assertThat(plaintext).isEqualTo("hello-world"); } @@ -344,35 +336,33 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void decryptShouldCreatePlaintextWithNonceAndContext() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext transitRequest = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - String ciphertext = transitOperations.encrypt("mykey", "hello-world".getBytes(), - transitRequest); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); - byte[] plaintext = transitOperations.decrypt("mykey", ciphertext, transitRequest); + byte[] plaintext = this.transitOperations.decrypt("mykey", ciphertext, transitRequest); assertThat(new String(plaintext)).isEqualTo("hello-world"); } @Test void decryptShouldCreateWrappedPlaintextWithNonceAndContext() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext context = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - Ciphertext ciphertext = transitOperations.encrypt("mykey", - Plaintext.of("hello-world").with(context)); - Plaintext plaintext = transitOperations.decrypt("mykey", ciphertext); + Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("hello-world").with(context)); + Plaintext plaintext = this.transitOperations.decrypt("mykey", ciphertext); assertThat(plaintext.asString()).isEqualTo("hello-world"); assertThat(plaintext.getContext()).isEqualTo(context); @@ -381,12 +371,12 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void encryptAndRewrapShouldCreateCiphertext() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - String ciphertext = transitOperations.encrypt("mykey", "hello-world"); - transitOperations.rotate("mykey"); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); + this.transitOperations.rotate("mykey"); - String rewrapped = transitOperations.rewrap("mykey", ciphertext); + String rewrapped = this.transitOperations.rewrap("mykey", ciphertext); assertThat(rewrapped).startsWith("vault:v2:"); } @@ -394,15 +384,13 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void shouldEncryptBinaryPlaintext() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); byte[] plaintext = new byte[] { 1, 2, 3, 4, 5 }; - String ciphertext = transitOperations.encrypt("mykey", plaintext, - VaultTransitContext.empty()); + String ciphertext = this.transitOperations.encrypt("mykey", plaintext, VaultTransitContext.empty()); - byte[] decrypted = transitOperations.decrypt("mykey", ciphertext, - VaultTransitContext.empty()); + byte[] decrypted = this.transitOperations.decrypt("mykey", ciphertext, VaultTransitContext.empty()); assertThat(decrypted).isEqualTo(plaintext); } @@ -410,19 +398,18 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @Test void encryptAndRewrapShouldCreateCiphertextWithNonceAndContext() { - transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder() - .convergentEncryption(true).derived(true).build()); + this.transitOperations.createKey("mykey", + VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext transitRequest = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); - String ciphertext = transitOperations.encrypt("mykey", "hello-world".getBytes(), - transitRequest); - transitOperations.rotate("mykey"); + String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); + this.transitOperations.rotate("mykey"); - String rewrapped = transitOperations.rewrap("mykey", ciphertext, transitRequest); + String rewrapped = this.transitOperations.rewrap("mykey", ciphertext, transitRequest); assertThat(rewrapped).startsWith("vault:v2"); } @@ -430,9 +417,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchEncrypt() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - List<VaultEncryptionResult> encrypted = transitOperations.encrypt("mykey", + List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(Plaintext.of("one"), Plaintext.of("two"))); assertThat(encrypted.get(0).get().getCiphertext()).startsWith("vault:"); @@ -443,16 +430,15 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecrypt() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - Ciphertext one = transitOperations.encrypt("mykey", Plaintext.of("one")); - Ciphertext two = transitOperations.encrypt("mykey", Plaintext.of("two")); + Ciphertext one = this.transitOperations.encrypt("mykey", Plaintext.of("one")); + Ciphertext two = this.transitOperations.encrypt("mykey", Plaintext.of("two")); - Plaintext plainOne = transitOperations.decrypt("mykey", one); - Plaintext plainTwo = transitOperations.decrypt("mykey", two); + Plaintext plainOne = this.transitOperations.decrypt("mykey", one); + Plaintext plainTwo = this.transitOperations.decrypt("mykey", two); - List<VaultDecryptionResult> decrypted = transitOperations.decrypt("mykey", - Arrays.asList(one, two)); + List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(one, two)); assertThat(decrypted.get(0).get()).isEqualTo(plainOne); assertThat(decrypted.get(0).getAsString()).isEqualTo("one"); @@ -468,16 +454,15 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { .derived(true) // .build(); - transitOperations.createKey("mykey", request); + this.transitOperations.createKey("mykey", request); - Plaintext one = Plaintext.of("one").with( - VaultTransitContext.builder().context("oneContext".getBytes()).build()); + Plaintext one = Plaintext.of("one") + .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); - Plaintext two = Plaintext.of("two").with( - VaultTransitContext.builder().context("twoContext".getBytes()).build()); + Plaintext two = Plaintext.of("two") + .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); - List<VaultEncryptionResult> encrypted = transitOperations.encrypt("mykey", - Arrays.asList(one, two)); + List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); assertThat(encrypted.get(0).get().getContext()).isEqualTo(one.getContext()); assertThat(encrypted.get(1).get().getContext()).isEqualTo(two.getContext()); @@ -491,17 +476,16 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { .derived(true) // .build(); - transitOperations.createKey("mykey", request); + this.transitOperations.createKey("mykey", request); - Plaintext one = Plaintext.of("one").with( - VaultTransitContext.builder().context("oneContext".getBytes()).build()); + Plaintext one = Plaintext.of("one") + .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); - Plaintext two = Plaintext.of("two").with( - VaultTransitContext.builder().context("twoContext".getBytes()).build()); + Plaintext two = Plaintext.of("two") + .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); - List<VaultEncryptionResult> encrypted = transitOperations.encrypt("mykey", - Arrays.asList(one, two)); - List<VaultDecryptionResult> decrypted = transitOperations.decrypt("mykey", + List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); + List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(encrypted.get(0).get(), encrypted.get(1).get())); assertThat(decrypted.get(0).get()).isEqualTo(one); @@ -516,23 +500,22 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { .derived(true) // .build(); - transitOperations.createKey("mykey", request); + this.transitOperations.createKey("mykey", request); - Plaintext one = Plaintext.of("one").with( - VaultTransitContext.builder().context("oneContext".getBytes()).build()); + Plaintext one = Plaintext.of("one") + .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); - Plaintext two = Plaintext.of("two").with( - VaultTransitContext.builder().context("twoContext".getBytes()).build()); + Plaintext two = Plaintext.of("two") + .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); - List<VaultEncryptionResult> encrypted = transitOperations.encrypt("mykey", - Arrays.asList(one, two)); + List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); Ciphertext encryptedOne = encrypted.get(0).get(); Ciphertext decryptedTwo = encrypted.get(1).get(); Ciphertext tampered = decryptedTwo.with(encryptedOne.getContext()); - List<VaultDecryptionResult> decrypted = transitOperations.decrypt("mykey", + List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(encryptedOne, tampered)); assertThat(decrypted.get(0).get()).isEqualTo(one); @@ -544,11 +527,11 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecryptEmptyPlaintext() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - Ciphertext empty = transitOperations.encrypt("mykey", Plaintext.empty()); + Ciphertext empty = this.transitOperations.encrypt("mykey", Plaintext.empty()); - List<VaultDecryptionResult> decrypted = transitOperations.decrypt("mykey", + List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Collections.singletonList(empty)); assertThat(decrypted.get(0).getAsString()).isEqualTo(""); @@ -562,14 +545,14 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { .derived(true) // .build(); - transitOperations.createKey("mykey", request); + this.transitOperations.createKey("mykey", request); - Plaintext empty = Plaintext.empty().with( - VaultTransitContext.builder().context("oneContext".getBytes()).build()); + Plaintext empty = Plaintext.empty() + .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); - List<VaultEncryptionResult> encrypted = transitOperations.encrypt("mykey", + List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Collections.singletonList(empty)); - List<VaultDecryptionResult> decrypted = transitOperations.decrypt("mykey", + List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Collections.singletonList(encrypted.get(0).get())); assertThat(decrypted.get(0).get()).isEqualTo(empty); @@ -581,7 +564,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); - Hmac hmac = transitOperations.getHmac(keyName, Plaintext.of("hello-world")); + Hmac hmac = this.transitOperations.getHmac(keyName, Plaintext.of("hello-world")); assertThat(hmac.getHmac()).isNotEmpty(); } @@ -590,12 +573,12 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { void generateHmacShouldCreateHmacForRotatedKey() { String keyName = createEcdsaP256Key(); - transitOperations.rotate(keyName); + this.transitOperations.rotate(keyName); - VaultHmacRequest request = VaultHmacRequest.builder() - .plaintext(Plaintext.of("hello-world")).keyVersion(2).build(); + VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")).keyVersion(2) + .build(); - Hmac hmac = transitOperations.getHmac(keyName, request); + Hmac hmac = this.transitOperations.getHmac(keyName, request); assertThat(hmac.getHmac()).isNotEmpty(); } @@ -605,10 +588,10 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); - VaultHmacRequest request = VaultHmacRequest.builder() - .plaintext(Plaintext.of("hello-world")).algorithm("sha2-512").build(); + VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")) + .algorithm("sha2-512").build(); - Hmac hmac = transitOperations.getHmac(keyName, request); + Hmac hmac = this.transitOperations.getHmac(keyName, request); assertThat(hmac.getHmac()).isNotEmpty(); } @@ -617,11 +600,11 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); - VaultHmacRequest request = VaultHmacRequest.builder() - .plaintext(Plaintext.of("hello-world")).algorithm("blah-512").build(); + VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")) + .algorithm("blah-512").build(); assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> transitOperations.getHmac(keyName, request)); + .isThrownBy(() -> this.transitOperations.getHmac(keyName, request)); } @Test @@ -630,8 +613,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); - Signature signature = transitOperations.sign(keyName, - Plaintext.of("hello-world")); + Signature signature = this.transitOperations.sign(keyName, Plaintext.of("hello-world")); assertThat(signature.getSignature()).isNotEmpty(); } @@ -639,22 +621,20 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void signShouldCreateSignatureUsingEd25519() { - VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest - .ofKeyType("ed25519"); - transitOperations.createKey("ed-key", keyCreationRequest); + VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest.ofKeyType("ed25519"); + this.transitOperations.createKey("ed-key", keyCreationRequest); - Signature signature = transitOperations.sign("ed-key", - Plaintext.of("hello-world")); + Signature signature = this.transitOperations.sign("ed-key", Plaintext.of("hello-world")); assertThat(signature.getSignature()).isNotEmpty(); } @Test void signWithInvalidKeyFormatShouldFail() { - transitOperations.createKey("mykey"); + this.transitOperations.createKey("mykey"); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> transitOperations.sign("mykey", Plaintext.of("hello-world"))); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> this.transitOperations.sign("mykey", Plaintext.of("hello-world"))); } @Test @@ -664,10 +644,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); - VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext) - .algorithm("sha2-512").build(); + VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext).algorithm("sha2-512").build(); - Signature signature = transitOperations.sign(keyName, request); + Signature signature = this.transitOperations.sign(keyName, request); assertThat(signature.getSignature()).isNotEmpty(); } @@ -678,9 +657,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); - Signature signature = transitOperations.sign(keyName, plaintext); + Signature signature = this.transitOperations.sign(keyName, plaintext); - boolean valid = transitOperations.verify(keyName, plaintext, signature); + boolean valid = this.transitOperations.verify(keyName, plaintext, signature); assertThat(valid).isTrue(); } @@ -691,9 +670,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); - Hmac hmac = transitOperations.getHmac(keyName, plaintext); + Hmac hmac = this.transitOperations.getHmac(keyName, plaintext); - SignatureValidation valid = transitOperations.verify(keyName, + SignatureValidation valid = this.transitOperations.verify(keyName, VaultSignatureVerificationRequest.create(plaintext, hmac)); assertThat(valid).isEqualTo(SignatureValidation.valid()); } @@ -705,17 +684,14 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); - VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext) - .algorithm("sha2-512").build(); + VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext).algorithm("sha2-512").build(); - Signature signature = transitOperations.sign(keyName, request); + Signature signature = this.transitOperations.sign(keyName, request); - VaultSignatureVerificationRequest verificationRequest = VaultSignatureVerificationRequest - .builder().algorithm("sha2-512").plaintext(plaintext).signature(signature) - .build(); + VaultSignatureVerificationRequest verificationRequest = VaultSignatureVerificationRequest.builder() + .algorithm("sha2-512").plaintext(plaintext).signature(signature).build(); - SignatureValidation valid = transitOperations.verify(keyName, - verificationRequest); + SignatureValidation valid = this.transitOperations.verify(keyName, verificationRequest); assertThat(valid).isEqualTo(SignatureValidation.valid()); } @@ -723,9 +699,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldCreateNewExportableKey() { - VaultTransitOperations vaultTransitOperations = vaultOperations.opsForTransit(); - VaultTransitKeyCreationRequest vaultTransitKeyCreationRequest = VaultTransitKeyCreationRequest - .builder().exportable(true).derived(true).build(); + VaultTransitOperations vaultTransitOperations = this.vaultOperations.opsForTransit(); + VaultTransitKeyCreationRequest vaultTransitKeyCreationRequest = VaultTransitKeyCreationRequest.builder() + .exportable(true).derived(true).build(); vaultTransitOperations.createKey("export-test", vaultTransitKeyCreationRequest); @@ -739,7 +715,7 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldCreateNotExportableKeyByDefault() { - VaultTransitOperations vaultTransitOperations = vaultOperations.opsForTransit(); + VaultTransitOperations vaultTransitOperations = this.vaultOperations.opsForTransit(); vaultTransitOperations.createKey("no-export"); @@ -753,11 +729,9 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportEncryptionKey() { - vaultOperations.write("transit/keys/export", - Collections.singletonMap("exportable", true)); + this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); - RawTransitKey rawTransitKey = transitOperations.exportKey("export", - TransitKeyType.ENCRYPTION_KEY); + RawTransitKey rawTransitKey = this.transitOperations.exportKey("export", TransitKeyType.ENCRYPTION_KEY); assertThat(rawTransitKey.getName()).isEqualTo("export"); assertThat(rawTransitKey.getKeys()).isNotEmpty(); @@ -768,22 +742,19 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldNotAllowExportSigningKey() { - vaultOperations.write("transit/keys/export", - Collections.singletonMap("exportable", true)); + this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); - assertThatExceptionOfType(VaultException.class).isThrownBy( - () -> transitOperations.exportKey("export", TransitKeyType.SIGNING_KEY)); + assertThatExceptionOfType(VaultException.class) + .isThrownBy(() -> this.transitOperations.exportKey("export", TransitKeyType.SIGNING_KEY)); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportHmacKey() { - vaultOperations.write("transit/keys/export", - Collections.singletonMap("exportable", true)); + this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); - RawTransitKey rawTransitKey = transitOperations.exportKey("export", - TransitKeyType.HMAC_KEY); + RawTransitKey rawTransitKey = this.transitOperations.exportKey("export", TransitKeyType.HMAC_KEY); assertThat(rawTransitKey.getName()).isEqualTo("export"); assertThat(rawTransitKey.getKeys()).isNotEmpty(); @@ -794,17 +765,15 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportEcDsaKey() { - VaultTransitOperations transitOperations = vaultOperations.opsForTransit(); + VaultTransitOperations transitOperations = this.vaultOperations.opsForTransit(); - VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() - .type("ecdsa-p256").exportable(true).build(); + VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder().type("ecdsa-p256") + .exportable(true).build(); transitOperations.createKey("ecdsa-key", request); - RawTransitKey hmacKey = transitOperations.exportKey("ecdsa-key", - TransitKeyType.HMAC_KEY); - RawTransitKey signingKey = transitOperations.exportKey("ecdsa-key", - TransitKeyType.SIGNING_KEY); + RawTransitKey hmacKey = transitOperations.exportKey("ecdsa-key", TransitKeyType.HMAC_KEY); + RawTransitKey signingKey = transitOperations.exportKey("ecdsa-key", TransitKeyType.SIGNING_KEY); assertThat(hmacKey.getKeys()).isNotEmpty(); assertThat(signingKey.getKeys()).isNotEmpty(); @@ -814,17 +783,15 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void shouldExportEdKey() { - VaultTransitOperations transitOperations = vaultOperations.opsForTransit(); + VaultTransitOperations transitOperations = this.vaultOperations.opsForTransit(); - VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() - .type("ed25519").exportable(true).build(); + VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder().type("ed25519") + .exportable(true).build(); transitOperations.createKey("ed-key", request); - RawTransitKey hmacKey = transitOperations.exportKey("ed-key", - TransitKeyType.HMAC_KEY); - RawTransitKey signingKey = transitOperations.exportKey("ed-key", - TransitKeyType.SIGNING_KEY); + RawTransitKey hmacKey = transitOperations.exportKey("ed-key", TransitKeyType.HMAC_KEY); + RawTransitKey signingKey = transitOperations.exportKey("ed-key", TransitKeyType.SIGNING_KEY); assertThat(hmacKey.getKeys()).isNotEmpty(); assertThat(signingKey.getKeys()).isNotEmpty(); @@ -833,10 +800,10 @@ class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { private String createEcdsaP256Key() { String keyName = "ecdsa-key"; - VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest - .ofKeyType("ecdsa-p256"); - transitOperations.createKey(keyName, keyCreationRequest); + VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest.ofKeyType("ecdsa-p256"); + this.transitOperations.createKey(keyName, keyCreationRequest); return keyName; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultVersionedKeyValueTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultVersionedKeyValueTemplateIntegrationTests.java index 36b136e2..3b78af32 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultVersionedKeyValueTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultVersionedKeyValueTemplateIntegrationTests.java @@ -56,7 +56,7 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp @BeforeEach void before() { - versionedOperations = vaultOperations.opsForVersionedKeyValue("versioned"); + this.versionedOperations = this.vaultOperations.opsForVersionedKeyValue("versioned"); } @Test @@ -66,11 +66,10 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - Metadata metadata = versionedOperations.put(key, Versioned.create(secret)); + Metadata metadata = this.versionedOperations.put(key, Versioned.create(secret)); assertThat(metadata.isDestroyed()).isFalse(); - assertThat(metadata.getCreatedAt()).isBetween(Instant.now().minusSeconds(60), - Instant.now().plusSeconds(60)); + assertThat(metadata.getCreatedAt()).isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60)); assertThat(metadata.getDeletedAt()).isNull(); } @@ -82,9 +81,9 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp person.setLastname("White"); String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Versioned.create(person)); + this.versionedOperations.put(key, Versioned.create(person)); - Versioned<Person> versioned = versionedOperations.get(key, Person.class); + Versioned<Person> versioned = this.versionedOperations.get(key, Person.class); assertThat(versioned.getRequiredData()).isEqualTo(person); } @@ -96,13 +95,12 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Versioned.create(secret, Version.unversioned())); + this.versionedOperations.put(key, Versioned.create(secret, Version.unversioned())); // this should fail - assertThatThrownBy(() -> versionedOperations.put(key, - Versioned.create(secret, Version.unversioned()))) - .isExactlyInstanceOf(VaultException.class).hasMessageContaining( - "check-and-set parameter did not match the current version"); + assertThatThrownBy(() -> this.versionedOperations.put(key, Versioned.create(secret, Version.unversioned()))) + .isExactlyInstanceOf(VaultException.class) + .hasMessageContaining("check-and-set parameter did not match the current version"); } @Test @@ -112,9 +110,9 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Versioned.create(secret)); + this.versionedOperations.put(key, Versioned.create(secret)); - Versioned<Map<String, Object>> loaded = versionedOperations.get(key); + Versioned<Map<String, Object>> loaded = this.versionedOperations.get(key); assertThat(loaded.getRequiredData()).isEqualTo(secret); assertThat(loaded.getRequiredMetadata()).isNotNull(); @@ -127,9 +125,9 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp Map<String, String> secret = Collections.singletonMap("key", "value"); String key = UUID.randomUUID().toString(); - versionedOperations.put(key, secret); + this.versionedOperations.put(key, secret); - assertThat(versionedOperations.list("")).contains(key); + assertThat(this.versionedOperations.list("")).contains(key); } @Test @@ -137,12 +135,12 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Collections.singletonMap("key", "v1")); - versionedOperations.put(key, Collections.singletonMap("key", "v2")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v1")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v2")); - assertThat(versionedOperations.get(key, Version.from(1)).getRequiredData()) + assertThat(this.versionedOperations.get(key, Version.from(1)).getRequiredData()) .isEqualTo(Collections.singletonMap("key", "v1")); - assertThat(versionedOperations.get(key, Version.from(2)).getRequiredData()) + assertThat(this.versionedOperations.get(key, Version.from(2)).getRequiredData()) .isEqualTo(Collections.singletonMap("key", "v2")); } @@ -151,18 +149,18 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Collections.singletonMap("key", "v1")); - versionedOperations.put(key, Collections.singletonMap("key", "v2")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v1")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v2")); - versionedOperations.delete(key); + this.versionedOperations.delete(key); - Versioned<Map<String, Object>> versioned = versionedOperations.get(key); + Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key); assertThat(versioned.getData()).isNull(); assertThat(versioned.getVersion()).isEqualTo(Version.from(2)); assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse(); - assertThat(versioned.getRequiredMetadata().getDeletedAt()) - .isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60)); + assertThat(versioned.getRequiredMetadata().getDeletedAt()).isBetween(Instant.now().minusSeconds(60), + Instant.now().plusSeconds(60)); } @Test @@ -170,16 +168,15 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Collections.singletonMap("key", "v1")); - versionedOperations.put(key, Collections.singletonMap("key", "v2")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v1")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v2")); - versionedOperations.delete(key, Version.from(2)); - versionedOperations.undelete(key, Version.from(2)); + this.versionedOperations.delete(key, Version.from(2)); + this.versionedOperations.undelete(key, Version.from(2)); - Versioned<Map<String, Object>> versioned = versionedOperations.get(key); + Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key); - assertThat(versioned.getRequiredData()) - .isEqualTo(Collections.singletonMap("key", "v2")); + assertThat(versioned.getRequiredData()).isEqualTo(Collections.singletonMap("key", "v2")); assertThat(versioned.getVersion()).isEqualTo(Version.from(2)); assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse(); assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull(); @@ -190,19 +187,18 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Collections.singletonMap("key", "v1")); - versionedOperations.put(key, Collections.singletonMap("key", "v2")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v1")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v2")); - versionedOperations.delete(key, Version.from(1)); + this.versionedOperations.delete(key, Version.from(1)); - Versioned<Map<String, Object>> versioned = versionedOperations.get(key, - Version.from(1)); + Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key, Version.from(1)); assertThat(versioned.getData()).isNull(); assertThat(versioned.getVersion()).isEqualTo(Version.from(1)); assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse(); - assertThat(versioned.getRequiredMetadata().getDeletedAt()) - .isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60)); + assertThat(versioned.getRequiredMetadata().getDeletedAt()).isBetween(Instant.now().minusSeconds(60), + Instant.now().plusSeconds(60)); } @Test @@ -210,16 +206,17 @@ class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupp String key = UUID.randomUUID().toString(); - versionedOperations.put(key, Collections.singletonMap("key", "v1")); - versionedOperations.put(key, Collections.singletonMap("key", "v2")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v1")); + this.versionedOperations.put(key, Collections.singletonMap("key", "v2")); - versionedOperations.destroy(key, Version.from(2)); + this.versionedOperations.destroy(key, Version.from(2)); - Versioned<Map<String, Object>> versioned = versionedOperations.get(key); + Versioned<Map<String, Object>> versioned = this.versionedOperations.get(key); assertThat(versioned.getData()).isNull(); assertThat(versioned.getVersion()).isEqualTo(Version.from(2)); assertThat(versioned.getRequiredMetadata().isDestroyed()).isTrue(); assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultWrappingTemplateIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultWrappingTemplateIntegrationTests.java index 1b175100..f50c2a73 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/VaultWrappingTemplateIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/VaultWrappingTemplateIntegrationTests.java @@ -60,7 +60,7 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - wrappingOperations = vaultOperations.opsForWrapping(); + this.wrappingOperations = this.vaultOperations.opsForWrapping(); } @Test @@ -68,7 +68,7 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { Map<String, String> map = Collections.singletonMap("key", "value"); - WrappedMetadata metadata = wrappingOperations.wrap(map, Duration.ofSeconds(100)); + WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100)); assertThat(metadata.getTtl()).isEqualTo(Duration.ofSeconds(100)); assertThat(metadata.getToken()).isNotNull(); @@ -81,9 +81,9 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { Map<String, String> map = Collections.singletonMap("key", "value"); - WrappedMetadata metadata = wrappingOperations.wrap(map, Duration.ofSeconds(100)); + WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100)); - WrappedMetadata lookup = wrappingOperations.lookup(metadata.getToken()); + WrappedMetadata lookup = this.wrappingOperations.lookup(metadata.getToken()); assertThat(lookup.getTtl()).isEqualTo(Duration.ofSeconds(100)); assertThat(lookup.getToken()).isNotNull(); @@ -96,11 +96,10 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { Map<String, String> map = Collections.singletonMap("key", "value"); - WrappedMetadata metadata = wrappingOperations.wrap(map, Duration.ofSeconds(100)); - VaultResponse response = wrappingOperations.read(metadata.getToken()); + WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100)); + VaultResponse response = this.wrappingOperations.read(metadata.getToken()); - assertThat(response.getRequiredData()) - .isEqualTo(Collections.singletonMap("key", "value")); + assertThat(response.getRequiredData()).isEqualTo(Collections.singletonMap("key", "value")); } @Test @@ -108,9 +107,8 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { Map<String, String> map = Collections.singletonMap("key", "value"); - WrappedMetadata metadata = wrappingOperations.wrap(map, Duration.ofSeconds(100)); - VaultResponseSupport<Secret> response = wrappingOperations - .read(metadata.getToken(), Secret.class); + WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100)); + VaultResponseSupport<Secret> response = this.wrappingOperations.read(metadata.getToken(), Secret.class); assertThat(response.getRequiredData()).isEqualTo(new Secret("value")); } @@ -118,14 +116,14 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { @Test void shouldReturnNullForNonExistentSecret() { - assertThat(wrappingOperations.read(VaultToken.of("foo"))).isNull(); - assertThat(wrappingOperations.read(VaultToken.of("foo"), Map.class)).isNull(); + assertThat(this.wrappingOperations.read(VaultToken.of("foo"))).isNull(); + assertThat(this.wrappingOperations.read(VaultToken.of("foo"), Map.class)).isNull(); } @Test void shouldLookupAbsentSecret() { - WrappedMetadata lookup = wrappingOperations.lookup(VaultToken.of("foo")); + WrappedMetadata lookup = this.wrappingOperations.lookup(VaultToken.of("foo")); assertThat(lookup).isNull(); } @@ -135,9 +133,9 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { Map<String, String> map = Collections.singletonMap("key", "value"); - WrappedMetadata metadata = wrappingOperations.wrap(map, Duration.ofSeconds(100)); + WrappedMetadata metadata = this.wrappingOperations.wrap(map, Duration.ofSeconds(100)); - WrappedMetadata rewrap = wrappingOperations.rewrap(metadata.getToken()); + WrappedMetadata rewrap = this.wrappingOperations.rewrap(metadata.getToken()); assertThat(rewrap.getTtl()).isEqualTo(Duration.ofSeconds(100)); assertThat(rewrap.getToken()).isNotEqualTo(metadata.getToken()); @@ -148,10 +146,11 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { @Test void shouldRewrapAbsentSecret() { assertThatExceptionOfType(VaultException.class) - .isThrownBy(() -> wrappingOperations.rewrap(VaultToken.of("foo"))); + .isThrownBy(() -> this.wrappingOperations.rewrap(VaultToken.of("foo"))); } static final class Secret { + private final String key; Secret(@JsonProperty("key") String key) { @@ -163,8 +162,7 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { } public String toString() { - return "VaultWrappingTemplateIntegrationTests.Secret(key=" + this.getKey() - + ")"; + return "VaultWrappingTemplateIntegrationTests.Secret(key=" + this.getKey() + ")"; } public boolean equals(final Object o) { @@ -187,5 +185,7 @@ class VaultWrappingTemplateIntegrationTests extends IntegrationTestSupport { result = result * PRIME + ($key == null ? 43 : $key.hashCode()); return result; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySourceUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySourceUnitTests.java index 1f4bd520..35c93e5b 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySourceUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/env/LeaseAwareVaultPropertySourceUnitTests.java @@ -42,6 +42,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for {@link LeaseAwareVaultPropertySource}. + * * @author Mark Paluch */ @ExtendWith(MockitoExtension.class) @@ -59,17 +60,16 @@ class LeaseAwareVaultPropertySourceUnitTests { doAnswer(invocation -> { listeners.add(invocation.getArgument(0)); return null; - }).when(leaseContainer).addLeaseListener(any()); - when(leaseContainer.addRequestedSecret(any())).then(invocation -> { + }).when(this.leaseContainer).addLeaseListener(any()); + when(this.leaseContainer.addRequestedSecret(any())).then(invocation -> { - listeners.forEach(leaseListener -> leaseListener - .onLeaseEvent(new SecretLeaseCreatedEvent(invocation.getArgument(0), + listeners.forEach( + leaseListener -> leaseListener.onLeaseEvent(new SecretLeaseCreatedEvent(invocation.getArgument(0), Lease.none(), Collections.singletonMap("key", "value")))); return invocation.getArgument(0); }); - LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource( - leaseContainer, secret); + LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource(this.leaseContainer, secret); assertThat(propertySource.getPropertyNames()).containsOnly("key"); } @@ -83,16 +83,15 @@ class LeaseAwareVaultPropertySourceUnitTests { doAnswer(invocation -> { listeners.add(invocation.getArgument(0)); return null; - }).when(leaseContainer).addLeaseListener(any()); - when(leaseContainer.addRequestedSecret(any())).then(invocation -> { + }).when(this.leaseContainer).addLeaseListener(any()); + when(this.leaseContainer.addRequestedSecret(any())).then(invocation -> { - listeners.forEach(leaseListener -> leaseListener.onLeaseEvent( - new SecretNotFoundEvent(invocation.getArgument(0), Lease.none()))); + listeners.forEach(leaseListener -> leaseListener + .onLeaseEvent(new SecretNotFoundEvent(invocation.getArgument(0), Lease.none()))); return invocation.getArgument(0); }); - LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource( - leaseContainer, secret); + LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource(this.leaseContainer, secret); assertThat(propertySource.getPropertyNames()).isEmpty(); } @@ -106,20 +105,17 @@ class LeaseAwareVaultPropertySourceUnitTests { doAnswer(invocation -> { errorListeners.add(invocation.getArgument(0)); return null; - }).when(leaseContainer).addErrorListener(any()); - when(leaseContainer.addRequestedSecret(any())).then(invocation -> { + }).when(this.leaseContainer).addErrorListener(any()); + when(this.leaseContainer.addRequestedSecret(any())).then(invocation -> { errorListeners.forEach(leaseListener -> { RuntimeException exception = new RuntimeException("Backend error"); - leaseListener.onLeaseError( - new SecretLeaseErrorEvent(secret, Lease.none(), exception), - exception); + leaseListener.onLeaseError(new SecretLeaseErrorEvent(secret, Lease.none(), exception), exception); }); return invocation.getArgument(0); }); - LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource( - leaseContainer, secret); + LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource(this.leaseContainer, secret); assertThat(propertySource.getPropertyNames()).isEmpty(); } @@ -133,21 +129,19 @@ class LeaseAwareVaultPropertySourceUnitTests { doAnswer(invocation -> { errorListeners.add(invocation.getArgument(0)); return null; - }).when(leaseContainer).addErrorListener(any()); - when(leaseContainer.addRequestedSecret(any())).then(invocation -> { + }).when(this.leaseContainer).addErrorListener(any()); + when(this.leaseContainer.addRequestedSecret(any())).then(invocation -> { errorListeners.forEach(leaseListener -> { RuntimeException exception = new RuntimeException("Backend error"); - leaseListener.onLeaseError( - new SecretLeaseErrorEvent(secret, Lease.none(), exception), - exception); + leaseListener.onLeaseError(new SecretLeaseErrorEvent(secret, Lease.none(), exception), exception); }); return invocation.getArgument(0); }); - assertThatThrownBy(() -> new LeaseAwareVaultPropertySource("name", leaseContainer, - secret, PropertyTransformers.noop(), false)) - .isInstanceOf(VaultPropertySourceNotFoundException.class) + assertThatThrownBy(() -> new LeaseAwareVaultPropertySource("name", this.leaseContainer, secret, + PropertyTransformers.noop(), false)).isInstanceOf(VaultPropertySourceNotFoundException.class) .hasRootCauseExactlyInstanceOf(RuntimeException.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/env/VaultPropertySourceUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/env/VaultPropertySourceUnitTests.java index fcda167f..c96915e3 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/env/VaultPropertySourceUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/env/VaultPropertySourceUnitTests.java @@ -47,44 +47,39 @@ class VaultPropertySourceUnitTests { @Test void shouldRejectEmptyPath() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new VaultPropertySource("hello", vaultTemplate, "", - PropertyTransformers.noop())); + assertThatIllegalArgumentException().isThrownBy( + () -> new VaultPropertySource("hello", this.vaultTemplate, "", PropertyTransformers.noop())); } @Test void shouldRejectPathStartingWithSlash() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new VaultPropertySource("hello", vaultTemplate, - "/secret", PropertyTransformers.noop())); + assertThatIllegalArgumentException().isThrownBy( + () -> new VaultPropertySource("hello", this.vaultTemplate, "/secret", PropertyTransformers.noop())); } @Test void propertiesNotFoundShouldFailOnIgnoreSecretNotFoundDisabled() { - assertThatThrownBy(() -> new VaultPropertySource("hello", vaultTemplate, - "secret/myapp", PropertyTransformers.noop(), false)) - .isInstanceOf(VaultPropertySourceNotFoundException.class) + assertThatThrownBy(() -> new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop(), false)).isInstanceOf(VaultPropertySourceNotFoundException.class) .hasNoCause(); } @Test void shouldPropagateFetchErrorIgnoreSecretNotFoundDisabled() { - when(vaultTemplate.read("secret/myapp")) - .thenThrow(new VaultException("HTTP error")); - assertThatThrownBy(() -> new VaultPropertySource("hello", vaultTemplate, - "secret/myapp", PropertyTransformers.noop(), false)) - .isInstanceOf(VaultPropertySourceNotFoundException.class) + when(this.vaultTemplate.read("secret/myapp")).thenThrow(new VaultException("HTTP error")); + assertThatThrownBy(() -> new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop(), false)).isInstanceOf(VaultPropertySourceNotFoundException.class) .hasRootCauseExactlyInstanceOf(VaultException.class); } @Test void propertiesNotFoundShouldBeIgnoredByDefault() { - VaultPropertySource source = new VaultPropertySource("hello", vaultTemplate, - "secret/myapp", PropertyTransformers.noop()); + VaultPropertySource source = new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop()); assertThat(source.getPropertyNames()).isEmpty(); } @@ -92,11 +87,10 @@ class VaultPropertySourceUnitTests { @Test void shouldIgnoreFetchErrorByDefault() { - when(vaultTemplate.read("secret/myapp")) - .thenThrow(new VaultException("HTTP error")); + when(this.vaultTemplate.read("secret/myapp")).thenThrow(new VaultException("HTTP error")); - VaultPropertySource source = new VaultPropertySource("hello", vaultTemplate, - "secret/myapp", PropertyTransformers.noop()); + VaultPropertySource source = new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop()); assertThat(source.getPropertyNames()).isEmpty(); } @@ -106,8 +100,8 @@ class VaultPropertySourceUnitTests { prepareResponse(); - VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", - vaultTemplate, "secret/myapp", PropertyTransformers.noop()); + VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop()); assertThat(vaultPropertySource.getProperty("key")).isEqualTo("value"); assertThat(vaultPropertySource.getProperty("integer")).isEqualTo(1); @@ -121,8 +115,7 @@ class VaultPropertySourceUnitTests { prepareResponse(); - VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", - vaultTemplate, "secret/myapp", + VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", PropertyTransformers.propertyNamePrefix("database.")); assertThat(vaultPropertySource.containsProperty("database.key")).isTrue(); @@ -130,8 +123,7 @@ class VaultPropertySourceUnitTests { assertThat(vaultPropertySource.getProperty("database.key")).isEqualTo("value"); assertThat(vaultPropertySource.getProperty("key")).isNull(); assertThat(vaultPropertySource.getProperty("database.integer")).isEqualTo(1); - assertThat(vaultPropertySource.getProperty("database.complex.key")) - .isEqualTo("value"); + assertThat(vaultPropertySource.getProperty("database.complex.key")).isEqualTo("value"); } @Test @@ -139,11 +131,10 @@ class VaultPropertySourceUnitTests { prepareResponse(); - VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", - vaultTemplate, "secret/myapp", PropertyTransformers.noop()); + VaultPropertySource vaultPropertySource = new VaultPropertySource("hello", this.vaultTemplate, "secret/myapp", + PropertyTransformers.noop()); - assertThat(vaultPropertySource.getPropertyNames()).contains("key", "integer", - "complex.key"); + assertThat(vaultPropertySource.getPropertyNames()).contains("key", "integer", "complex.key"); } private void prepareResponse() { @@ -157,6 +148,7 @@ class VaultPropertySourceUnitTests { VaultResponse vaultResponse = new VaultResponse(); vaultResponse.setData(data); - when(vaultTemplate.read("secret/myapp")).thenReturn(vaultResponse); + when(this.vaultTemplate.read("secret/myapp")).thenReturn(vaultResponse); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/env/VersionedKeyValueBackendIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/env/VersionedKeyValueBackendIntegrationTests.java index 2bd842bb..90bf8566 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/env/VersionedKeyValueBackendIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/env/VersionedKeyValueBackendIntegrationTests.java @@ -50,12 +50,14 @@ class VersionedKeyValueBackendIntegrationTests extends IntegrationTestSupport { @VaultPropertySource("versioned/my/path") @Configuration static class NonRotatingSecret { + } @VaultPropertySource(value = "versioned/my/path", renewal = VaultPropertySource.Renewal.ROTATE) @PropertySource(value = "http://foo", ignoreResourceNotFound = true) @Configuration static class RotatingSecret { + } @BeforeAll @@ -63,8 +65,8 @@ class VersionedKeyValueBackendIntegrationTests extends IntegrationTestSupport { PrepareVault prepare = initializer.prepare(); - VaultKeyValueOperations versionedKv = prepare.getVaultOperations().opsForKeyValue( - "versioned", VaultKeyValueOperationsSupport.KeyValueBackend.versioned()); + VaultKeyValueOperations versionedKv = prepare.getVaultOperations().opsForKeyValue("versioned", + VaultKeyValueOperationsSupport.KeyValueBackend.versioned()); versionedKv.put("my/path", Collections.singletonMap("my-key", "my-value")); } @@ -92,4 +94,5 @@ class VersionedKeyValueBackendIntegrationTests extends IntegrationTestSupport { context.stop(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/RotatingGenericSecretsIntegrationTestConfiguration.java b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/RotatingGenericSecretsIntegrationTestConfiguration.java index d305aa4d..c9f90057 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/RotatingGenericSecretsIntegrationTestConfiguration.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/RotatingGenericSecretsIntegrationTestConfiguration.java @@ -38,7 +38,8 @@ public class RotatingGenericSecretsIntegrationTestConfiguration { * Utility class which will give our tests a reference to the * {@link LeaseAwareVaultPropertySource} which holds our secrets. */ - @VaultPropertySource(propertyNamePrefix = "generic.rotating.", value = "secret/rotating", renewal = VaultPropertySource.Renewal.ROTATE) + @VaultPropertySource(propertyNamePrefix = "generic.rotating.", value = "secret/rotating", + renewal = VaultPropertySource.Renewal.ROTATE) public static class PropertySourceHolder implements InitializingBean { @Autowired @@ -50,24 +51,21 @@ public class RotatingGenericSecretsIntegrationTestConfiguration { * Searches the {@link ApplicationContext} for the * {@link LeaseAwareVaultPropertySource} corresponding to the secret path we are * testing. - * * @throws Exception if bad things happen (for example, if the property source - * does not exist). + * does not exist). */ @Override public void afterPropertiesSet() throws Exception { - Assert.notNull(appContext, "application context must be set"); - Map<String, LeaseAwareVaultPropertySource> leaseAwareVaultPropertySources = appContext + Assert.notNull(this.appContext, "application context must be set"); + Map<String, LeaseAwareVaultPropertySource> leaseAwareVaultPropertySources = this.appContext .getBeansOfType(LeaseAwareVaultPropertySource.class); - for (LeaseAwareVaultPropertySource candidate : leaseAwareVaultPropertySources - .values()) { + for (LeaseAwareVaultPropertySource candidate : leaseAwareVaultPropertySources.values()) { if (candidate.getRequestedSecret().getPath().equals("secret/rotating")) { this.propertySource = candidate; break; } } - Assert.notNull(propertySource, - "Vault property source for generic secret not found"); + Assert.notNull(this.propertySource, "Vault property source for generic secret not found"); } /** @@ -75,14 +73,13 @@ public class RotatingGenericSecretsIntegrationTestConfiguration { * @return the property source for our tested secrets */ public LeaseAwareVaultPropertySource getPropertySource() { - return propertySource; + return this.propertySource; } } /** * Creates a {@link PropertySourceHolder}. - * * @return the {@link PropertySourceHolder} */ @Bean diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/SecretLeaseContainerUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/SecretLeaseContainerUnitTests.java index f7984444..7d34863f 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/SecretLeaseContainerUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/SecretLeaseContainerUnitTests.java @@ -95,41 +95,41 @@ class SecretLeaseContainerUnitTests { @BeforeEach void before() throws Exception { - secretLeaseContainer = new SecretLeaseContainer(vaultOperations, taskScheduler); - secretLeaseContainer.addLeaseListener(leaseListenerAdapter); - secretLeaseContainer.addErrorListener(leaseListenerAdapter); - secretLeaseContainer.afterPropertiesSet(); + this.secretLeaseContainer = new SecretLeaseContainer(this.vaultOperations, this.taskScheduler); + this.secretLeaseContainer.addLeaseListener(this.leaseListenerAdapter); + this.secretLeaseContainer.addErrorListener(this.leaseListenerAdapter); + this.secretLeaseContainer.afterPropertiesSet(); } @Test void shouldSetProperties() { - secretLeaseContainer.setMinRenewal(Duration.ofMinutes(2)); - secretLeaseContainer.setExpiryThreshold(Duration.ofMinutes(3)); + this.secretLeaseContainer.setMinRenewal(Duration.ofMinutes(2)); + this.secretLeaseContainer.setExpiryThreshold(Duration.ofMinutes(3)); - assertThat(secretLeaseContainer.getMinRenewal().getSeconds()).isEqualTo(120); - assertThat(secretLeaseContainer.getMinRenewalSeconds()).isEqualTo(120); - assertThat(secretLeaseContainer.getExpiryThreshold().getSeconds()).isEqualTo(180); - assertThat(secretLeaseContainer.getExpiryThresholdSeconds()).isEqualTo(180); + assertThat(this.secretLeaseContainer.getMinRenewal().getSeconds()).isEqualTo(120); + assertThat(this.secretLeaseContainer.getMinRenewalSeconds()).isEqualTo(120); + assertThat(this.secretLeaseContainer.getExpiryThreshold().getSeconds()).isEqualTo(180); + assertThat(this.secretLeaseContainer.getExpiryThresholdSeconds()).isEqualTo(180); } @Test void shouldWorkIfNoSecretsRequested() { - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); - verifyZeroInteractions(leaseListenerAdapter); + verifyZeroInteractions(this.leaseListenerAdapter); } @Test void shouldWorkIfNoSecretsFound() { - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); - secretLeaseContainer.requestRenewableSecret(requestedSecret.getPath()); + this.secretLeaseContainer.requestRenewableSecret(this.requestedSecret.getPath()); - verify(leaseListenerAdapter).onLeaseEvent(any(SecretNotFoundEvent.class)); - verifyNoMoreInteractions(leaseListenerAdapter); + verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretNotFoundEvent.class)); + verifyNoMoreInteractions(this.leaseListenerAdapter); } @Test @@ -138,18 +138,17 @@ class SecretLeaseContainerUnitTests { VaultResponse secrets = new VaultResponse(); secrets.setData(Collections.singletonMap("key", (Object) "value")); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(secrets); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(secrets); - secretLeaseContainer.addRequestedSecret(requestedSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); + this.secretLeaseContainer.start(); - verifyZeroInteractions(taskScheduler); - verify(leaseListenerAdapter).onLeaseEvent(captor.capture()); + verifyZeroInteractions(this.taskScheduler); + verify(this.leaseListenerAdapter).onLeaseEvent(this.captor.capture()); - SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) captor - .getValue(); + SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) this.captor.getValue(); - assertThat(leaseCreatedEvent.getSource()).isEqualTo(requestedSecret); + assertThat(leaseCreatedEvent.getSource()).isEqualTo(this.requestedSecret); assertThat(leaseCreatedEvent.getLease()).isNotNull(); assertThat(leaseCreatedEvent.getSecrets()).containsKey("key"); } @@ -162,18 +161,17 @@ class SecretLeaseContainerUnitTests { secrets.setRenewable(false); secrets.setData(Collections.singletonMap("key", "value")); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(secrets); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(secrets); - secretLeaseContainer.addRequestedSecret(requestedSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); + this.secretLeaseContainer.start(); - verifyZeroInteractions(taskScheduler); - verify(leaseListenerAdapter).onLeaseEvent(captor.capture()); + verifyZeroInteractions(this.taskScheduler); + verify(this.leaseListenerAdapter).onLeaseEvent(this.captor.capture()); - SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) captor - .getValue(); + SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) this.captor.getValue(); - assertThat(leaseCreatedEvent.getSource()).isEqualTo(requestedSecret); + assertThat(leaseCreatedEvent.getSource()).isEqualTo(this.requestedSecret); assertThat(leaseCreatedEvent.getLease()).isNotNull(); assertThat(leaseCreatedEvent.getSecrets()).containsKey("key"); } @@ -182,18 +180,18 @@ class SecretLeaseContainerUnitTests { void shouldPropagateErrorsToListenerOnInitialRetrieval() { VaultException e = new VaultException("error"); - when(vaultOperations.read(requestedSecret.getPath())).thenThrow(e); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenThrow(e); - secretLeaseContainer.addRequestedSecret(requestedSecret); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); - verify(leaseListenerAdapter).onLeaseError(captor.capture(), eq(e)); - verifyNoMoreInteractions(leaseListenerAdapter); + verify(this.leaseListenerAdapter).onLeaseError(this.captor.capture(), eq(e)); + verifyNoMoreInteractions(this.leaseListenerAdapter); - SecretLeaseEvent leaseEvent = captor.getValue(); + SecretLeaseEvent leaseEvent = this.captor.getValue(); - assertThat(leaseEvent.getSource()).isEqualTo(requestedSecret); + assertThat(leaseEvent.getSource()).isEqualTo(this.requestedSecret); assertThat(leaseEvent.getLease()).isEqualTo(Lease.none()); } @@ -201,15 +199,14 @@ class SecretLeaseContainerUnitTests { @SuppressWarnings("unchecked") void shouldAcceptSecretsWithRenewableLease() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(createSecrets()); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(createSecrets()); - secretLeaseContainer.addRequestedSecret(requestedSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); + this.secretLeaseContainer.start(); - verify(taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); + verify(this.taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); } @Test @@ -218,17 +215,17 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenReturn(Lease.of("new_lease", Duration.ofSeconds(70), true)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verifyZeroInteractions(scheduledFuture); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verifyZeroInteractions(this.scheduledFuture); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); } @Test @@ -237,19 +234,19 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenReturn(Lease.of("new_lease", Duration.ofSeconds(70), true)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); - secretLeaseContainer.renew(requestedSecret); + this.secretLeaseContainer.renew(this.requestedSecret); - verify(vaultOperations).doWithSession(any(RestOperationsCallback.class)); - verify(scheduledFuture).cancel(false); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.vaultOperations).doWithSession(any(RestOperationsCallback.class)); + verify(this.scheduledFuture).cancel(false); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); } @Test @@ -258,31 +255,29 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); AtomicInteger attempts = new AtomicInteger(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) - .then(invocation -> { + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))).then(invocation -> { - int attempt = attempts.incrementAndGet(); - if (attempt == 1) { - throw new VaultException("Renewal failure"); - } + int attempt = attempts.incrementAndGet(); + if (attempt == 1) { + throw new VaultException("Renewal failure"); + } - return Lease.of("new_lease", Duration.ofSeconds(70), true); - }); + return Lease.of("new_lease", Duration.ofSeconds(70), true); + }); - secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError()); - secretLeaseContainer.start(); + this.secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError()); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - boolean renewed = secretLeaseContainer.renew(requestedSecret); + boolean renewed = this.secretLeaseContainer.renew(this.requestedSecret); assertThat(renewed).isTrue(); - verify(vaultOperations, times(2)) - .doWithSession(any(RestOperationsCallback.class)); - verify(scheduledFuture).cancel(false); - verify(taskScheduler, times(3)).schedule(captor.capture(), any(Trigger.class)); + verify(this.vaultOperations, times(2)).doWithSession(any(RestOperationsCallback.class)); + verify(this.scheduledFuture).cancel(false); + verify(this.taskScheduler, times(3)).schedule(captor.capture(), any(Trigger.class)); } @Test @@ -290,50 +285,46 @@ class SecretLeaseContainerUnitTests { void shouldRetainLeaseAfterRenewalFailure() { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenThrow(new VaultException("Renewal failure")); - secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError()); - secretLeaseContainer.start(); + this.secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError()); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verify(vaultOperations, times(2)) - .doWithSession(any(RestOperationsCallback.class)); + verify(this.vaultOperations, times(2)).doWithSession(any(RestOperationsCallback.class)); } @Test void shouldRotateNonRenewableLease() { final List<SecretLeaseEvent> events = new ArrayList<SecretLeaseEvent>(); - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn( - createSecrets("key", "value", false), + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(createSecrets("key", "value", false), createSecrets("key", "value2", false)); - secretLeaseContainer - .addRequestedSecret(RequestedSecret.rotating(requestedSecret.getPath())); - secretLeaseContainer.addLeaseListener(new LeaseListenerAdapter() { + this.secretLeaseContainer.addRequestedSecret(RequestedSecret.rotating(this.requestedSecret.getPath())); + this.secretLeaseContainer.addLeaseListener(new LeaseListenerAdapter() { @Override public void onLeaseEvent(SecretLeaseEvent leaseEvent) { events.add(leaseEvent); } }); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); assertThat(events).hasSize(3); assertThat(events.get(0)).isInstanceOf(SecretLeaseCreatedEvent.class); @@ -347,126 +338,116 @@ class SecretLeaseContainerUnitTests { @Test void shouldRotateGenericSecret() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(rotatingGenericSecret.getPath())).thenReturn( + when(this.vaultOperations.read(this.rotatingGenericSecret.getPath())).thenReturn( createGenericSecrets(Collections.singletonMap("key", (Object) "value")), createGenericSecrets(Collections.singletonMap("foo", (Object) "bar"))); - secretLeaseContainer.addRequestedSecret(rotatingGenericSecret); + this.secretLeaseContainer.addRequestedSecret(this.rotatingGenericSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verifyZeroInteractions(scheduledFuture); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verifyZeroInteractions(this.scheduledFuture); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); - ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor - .forClass(SecretLeaseEvent.class); - verify(leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); + ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor.forClass(SecretLeaseEvent.class); + verify(this.leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); List<SecretLeaseEvent> events = createdEvents.getAllValues(); assertThat(events).hasSize(3); assertThat(events.get(0)).isInstanceOf(SecretLeaseCreatedEvent.class); - assertThat(((SecretLeaseCreatedEvent) events.get(0)).getSecrets()) - .containsOnlyKeys("key"); + assertThat(((SecretLeaseCreatedEvent) events.get(0)).getSecrets()).containsOnlyKeys("key"); assertThat(events.get(1)).isInstanceOf(SecretLeaseExpiredEvent.class); assertThat(events.get(2)).isInstanceOf(SecretLeaseCreatedEvent.class); - assertThat(((SecretLeaseCreatedEvent) events.get(2)).getSecrets()) - .containsOnlyKeys("foo"); + assertThat(((SecretLeaseCreatedEvent) events.get(2)).getSecrets()).containsOnlyKeys("foo"); } @Test void shouldRotateGenericSecretNow() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(rotatingGenericSecret.getPath())).thenReturn( + when(this.vaultOperations.read(this.rotatingGenericSecret.getPath())).thenReturn( createGenericSecrets(Collections.singletonMap("key", "value")), createGenericSecrets(Collections.singletonMap("foo", "bar"))); - secretLeaseContainer.addRequestedSecret(rotatingGenericSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.rotatingGenericSecret); + this.secretLeaseContainer.start(); - secretLeaseContainer.rotate(rotatingGenericSecret); + this.secretLeaseContainer.rotate(this.rotatingGenericSecret); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); - verify(scheduledFuture).cancel(false); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.scheduledFuture).cancel(false); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); - ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor - .forClass(SecretLeaseEvent.class); - verify(leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); + ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor.forClass(SecretLeaseEvent.class); + verify(this.leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); } @Test void shouldNotRenewExpiringLease() { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenReturn(Lease.of("new_lease", Duration.ofSeconds(5), true)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verifyZeroInteractions(scheduledFuture); - verify(taskScheduler, times(1)).schedule(captor.capture(), any(Trigger.class)); - verify(leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); - verify(leaseListenerAdapter).onLeaseEvent(any(SecretLeaseExpiredEvent.class)); + verifyZeroInteractions(this.scheduledFuture); + verify(this.taskScheduler, times(1)).schedule(captor.capture(), any(Trigger.class)); + verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); + verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretLeaseExpiredEvent.class)); } @Test void shouldNotRotateExpiringLease() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); VaultResponse first = createSecrets(); VaultResponse second = createSecrets(); second.setData(Collections.singletonMap("foo", (Object) "bar")); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(first, second); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(first, second); + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenReturn(Lease.of("new_lease", Duration.ofSeconds(5), true)); - secretLeaseContainer.requestRotatingSecret("my-secret"); + this.secretLeaseContainer.requestRotatingSecret("my-secret"); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); captor.getValue().run(); - verify(taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class)); - ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor - .forClass(SecretLeaseEvent.class); - verify(leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); + ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor.forClass(SecretLeaseEvent.class); + verify(this.leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture()); List<SecretLeaseEvent> events = createdEvents.getAllValues(); assertThat(events).hasSize(3); assertThat(events.get(0)).isInstanceOf(SecretLeaseCreatedEvent.class); - assertThat(((SecretLeaseCreatedEvent) events.get(0)).getSecrets()) - .containsOnlyKeys("key"); + assertThat(((SecretLeaseCreatedEvent) events.get(0)).getSecrets()).containsOnlyKeys("key"); assertThat(events.get(1)).isInstanceOf(SecretLeaseExpiredEvent.class); assertThat(events.get(2)).isInstanceOf(SecretLeaseCreatedEvent.class); - assertThat(((SecretLeaseCreatedEvent) events.get(2)).getSecrets()) - .containsOnlyKeys("foo"); + assertThat(((SecretLeaseCreatedEvent) events.get(2)).getSecrets()).containsOnlyKeys("foo"); } @Test @@ -474,14 +455,13 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Trigger> captor = ArgumentCaptor.forClass(Trigger.class); - verify(taskScheduler).schedule(any(Runnable.class), captor.capture()); + verify(this.taskScheduler).schedule(any(Runnable.class), captor.capture()); Date nextExecutionTime = captor.getValue().nextExecutionTime(null); - assertThat(nextExecutionTime).isBetween( - new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(35)), + assertThat(nextExecutionTime).isBetween(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(35)), new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(41))); } @@ -489,24 +469,23 @@ class SecretLeaseContainerUnitTests { void shouldPublishRenewalErrors() { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenThrow(new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); - verify(leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); - verify(leaseListenerAdapter).onLeaseError(captor.capture(), - any(VaultException.class)); - verifyNoMoreInteractions(leaseListenerAdapter); + verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); + verify(this.leaseListenerAdapter).onLeaseError(this.captor.capture(), any(VaultException.class)); + verifyNoMoreInteractions(this.leaseListenerAdapter); - SecretLeaseEvent leaseEvent = captor.getValue(); + SecretLeaseEvent leaseEvent = this.captor.getValue(); - assertThat(leaseEvent.getSource()).isEqualTo(requestedSecret); + assertThat(leaseEvent.getSource()).isEqualTo(this.requestedSecret); assertThat(leaseEvent.getLease()).isNotNull(); } @@ -516,18 +495,18 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - when(vaultOperations.doWithSession(any(RestOperationsCallback.class))) + when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class))) .thenReturn(Lease.of("new_lease", Duration.ofSeconds(70), true)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class)); runnableCaptor.getValue().run(); ArgumentCaptor<Trigger> captor = ArgumentCaptor.forClass(Trigger.class); - verify(taskScheduler, times(2)).schedule(any(Runnable.class), captor.capture()); + verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), captor.capture()); assertThat(captor.getAllValues().get(0).nextExecutionTime(null)).isBetween( new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(35)), @@ -543,10 +522,10 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Trigger> captor = ArgumentCaptor.forClass(Trigger.class); - verify(taskScheduler).schedule(any(Runnable.class), captor.capture()); + verify(this.taskScheduler).schedule(any(Runnable.class), captor.capture()); Trigger trigger = captor.getValue(); @@ -559,15 +538,15 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); - verifyNoMoreInteractions(scheduledFuture); - verifyNoMoreInteractions(taskScheduler); + verifyNoMoreInteractions(this.scheduledFuture); + verifyNoMoreInteractions(this.taskScheduler); } @Test @@ -575,20 +554,20 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - secretLeaseContainer.start(); + this.secretLeaseContainer.start(); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); - verify(taskScheduler).schedule(captor.capture(), any(Trigger.class)); - verify(vaultOperations).read(eq("sys/internal/ui/mounts/my-secret")); - verify(vaultOperations).read(eq("my-secret")); + verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class)); + verify(this.vaultOperations).read(eq("sys/internal/ui/mounts/my-secret")); + verify(this.vaultOperations).read(eq("my-secret")); - secretLeaseContainer.stop(); + this.secretLeaseContainer.stop(); - verify(scheduledFuture).cancel(false); + verify(this.scheduledFuture).cancel(false); captor.getValue().run(); - verifyNoMoreInteractions(vaultOperations); + verifyNoMoreInteractions(this.vaultOperations); } @Test @@ -596,16 +575,14 @@ class SecretLeaseContainerUnitTests { prepareRenewal(); - secretLeaseContainer.start(); - secretLeaseContainer.destroy(); + this.secretLeaseContainer.start(); + this.secretLeaseContainer.destroy(); - verify(vaultOperations).doWithSession(any(RestOperationsCallback.class)); - verify(scheduledFuture).cancel(false); - verify(leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); - verify(leaseListenerAdapter) - .onLeaseEvent(any(BeforeSecretLeaseRevocationEvent.class)); - verify(leaseListenerAdapter) - .onLeaseEvent(any(AfterSecretLeaseRevocationEvent.class)); + verify(this.vaultOperations).doWithSession(any(RestOperationsCallback.class)); + verify(this.scheduledFuture).cancel(false); + verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class)); + verify(this.leaseListenerAdapter).onLeaseEvent(any(BeforeSecretLeaseRevocationEvent.class)); + verify(this.leaseListenerAdapter).onLeaseEvent(any(AfterSecretLeaseRevocationEvent.class)); } @Test @@ -614,39 +591,34 @@ class SecretLeaseContainerUnitTests { VaultResponse secrets = new VaultResponse(); secrets.setData(Collections.singletonMap("key", (Object) "value")); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(secrets); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(secrets); - secretLeaseContainer.addRequestedSecret(requestedSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); + this.secretLeaseContainer.start(); - secretLeaseContainer.destroy(); + this.secretLeaseContainer.destroy(); - verifyZeroInteractions(taskScheduler); + verifyZeroInteractions(this.taskScheduler); - verify(leaseListenerAdapter, never()) - .onLeaseEvent(any(BeforeSecretLeaseRevocationEvent.class)); - verify(leaseListenerAdapter, never()) - .onLeaseEvent(any(AfterSecretLeaseRevocationEvent.class)); + verify(this.leaseListenerAdapter, never()).onLeaseEvent(any(BeforeSecretLeaseRevocationEvent.class)); + verify(this.leaseListenerAdapter, never()).onLeaseEvent(any(AfterSecretLeaseRevocationEvent.class)); } @Test void shouldRequestRotatingGenericSecrets() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(rotatingGenericSecret.getPath())) - .thenReturn(createGenericSecrets()); + when(this.vaultOperations.read(this.rotatingGenericSecret.getPath())).thenReturn(createGenericSecrets()); - secretLeaseContainer.addRequestedSecret(rotatingGenericSecret); - secretLeaseContainer.start(); + this.secretLeaseContainer.addRequestedSecret(this.rotatingGenericSecret); + this.secretLeaseContainer.start(); - verify(leaseListenerAdapter).onLeaseEvent(captor.capture()); + verify(this.leaseListenerAdapter).onLeaseEvent(this.captor.capture()); - SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) captor - .getValue(); + SecretLeaseCreatedEvent leaseCreatedEvent = (SecretLeaseCreatedEvent) this.captor.getValue(); - assertThat(leaseCreatedEvent.getSource()).isEqualTo(rotatingGenericSecret); + assertThat(leaseCreatedEvent.getSource()).isEqualTo(this.rotatingGenericSecret); assertThat(leaseCreatedEvent.getLease()).isNotNull(); assertThat(leaseCreatedEvent.getSecrets()).containsKey("key"); } @@ -654,12 +626,11 @@ class SecretLeaseContainerUnitTests { @SuppressWarnings("unchecked") private void prepareRenewal() { - when(taskScheduler.schedule(any(Runnable.class), any(Trigger.class))) - .thenReturn(scheduledFuture); + when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture); - when(vaultOperations.read(requestedSecret.getPath())).thenReturn(createSecrets()); + when(this.vaultOperations.read(this.requestedSecret.getPath())).thenReturn(createSecrets()); - secretLeaseContainer.addRequestedSecret(requestedSecret); + this.secretLeaseContainer.addRequestedSecret(this.requestedSecret); } private VaultResponse createSecrets() { @@ -692,4 +663,5 @@ class SecretLeaseContainerUnitTests { return secrets; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/domain/RequestedSecretTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/domain/RequestedSecretTests.java index 228ecb86..91336cff 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/lease/domain/RequestedSecretTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/lease/domain/RequestedSecretTests.java @@ -43,4 +43,5 @@ class RequestedSecretTests { assertThat(requestedSecret.getMode()).isEqualTo(Mode.RENEW); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/util/KeyValueDelegateUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/util/KeyValueDelegateUnitTests.java index 74e3f3dc..a825e72f 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/util/KeyValueDelegateUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/util/KeyValueDelegateUnitTests.java @@ -52,27 +52,22 @@ class KeyValueDelegateUnitTests { void shouldConsiderKeyValueVersion() { assertThat(MountInfo.from("foo", Collections.singletonMap("version", "1")) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)) - .isTrue(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)).isTrue(); assertThat(MountInfo.from("foo", Collections.singletonMap("version", 1)) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)) - .isTrue(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)).isTrue(); assertThat(MountInfo.from("foo", Collections.singletonMap("version", "2")) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_2)) - .isTrue(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_2)).isTrue(); assertThat(MountInfo.from("foo", Collections.singletonMap("version", 2)) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)) - .isFalse(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)).isFalse(); assertThat(MountInfo.from("foo", Collections.singletonMap("version", "2")) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)) - .isFalse(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)).isFalse(); assertThat(MountInfo.from("foo", Collections.emptyMap()) - .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)) - .isFalse(); + .isKeyValue(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1)).isFalse(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/core/util/PropertyTransformersUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/core/util/PropertyTransformersUnitTests.java index bc51ea31..c7396d7a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/core/util/PropertyTransformersUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/core/util/PropertyTransformersUnitTests.java @@ -32,21 +32,19 @@ class PropertyTransformersUnitTests { @Test void propertyNamePrefix() { - PropertyTransformer propertyTransformer = PropertyTransformers - .propertyNamePrefix("my-prefix."); + PropertyTransformer propertyTransformer = PropertyTransformers.propertyNamePrefix("my-prefix."); - assertThat(propertyTransformer.transformProperties(properties)).hasSize(1) - .containsEntry("my-prefix.key", "value"); + assertThat(propertyTransformer.transformProperties(this.properties)).hasSize(1).containsEntry("my-prefix.key", + "value"); } @Test void propertyNamePrefixChaining() { - PropertyTransformer propertyTransformer = PropertyTransformers - .propertyNamePrefix("my-prefix.") + PropertyTransformer propertyTransformer = PropertyTransformers.propertyNamePrefix("my-prefix.") .andThen(PropertyTransformers.propertyNamePrefix("foo-bar.")); - assertThat(propertyTransformer.transformProperties(properties)).hasSize(1) + assertThat(propertyTransformer.transformProperties(this.properties)).hasSize(1) .containsEntry("foo-bar.my-prefix.key", "value"); } @@ -59,11 +57,11 @@ class PropertyTransformersUnitTests { PropertyTransformer middle = PropertyTransformers.propertyNamePrefix("middle.") .andThen(PropertyTransformers.propertyNamePrefix("after-middle.")); - PropertyTransformer propertyTransformer = PropertyTransformers - .propertyNamePrefix("inner.") + PropertyTransformer propertyTransformer = PropertyTransformers.propertyNamePrefix("inner.") .andThen(PropertyTransformers.noop().andThen(middle)).andThen(last); - assertThat(propertyTransformer.transformProperties(properties)).hasSize(1) + assertThat(propertyTransformer.transformProperties(this.properties)).hasSize(1) .containsEntry("last.after-middle.middle.inner.key", "value"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/demo/SecurePropertyUsage.java b/spring-vault-core/src/test/java/org/springframework/vault/demo/SecurePropertyUsage.java index 02246c2e..4bf06446 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/demo/SecurePropertyUsage.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/demo/SecurePropertyUsage.java @@ -60,11 +60,9 @@ public class SecurePropertyUsage { vaultOperations.write("secret/secure-introduction", data); - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - Config.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); - System.out.println(context.getEnvironment() - .getProperty("my-property-that-references-vault")); + System.out.println(context.getEnvironment().getProperty("my-property-that-references-vault")); System.out.println(context.getEnvironment().getProperty("encrypted")); System.out.println(context.getBean(Client.class).myValue); @@ -72,8 +70,7 @@ public class SecurePropertyUsage { context.stop(); } - @PropertySources({ - @PropertySource("classpath:/org/springframework/vault/demo/secure-introduction.properties"), + @PropertySources({ @PropertySource("classpath:/org/springframework/vault/demo/secure-introduction.properties"), @PropertySource("classpath:/org/springframework/vault/demo/other.properties") }) @VaultPropertySource({ "secret/secure-introduction" }) @Configuration @@ -84,6 +81,7 @@ public class SecurePropertyUsage { public ClientAuthentication clientAuthentication() { return new TokenAuthentication(getEnvironment().getProperty("vault.token")); } + } @Component @@ -93,4 +91,5 @@ public class SecurePropertyUsage { String myValue; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/demo/VaultApp.java b/spring-vault-core/src/test/java/org/springframework/vault/demo/VaultApp.java index 9c24787f..2f6055fa 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/demo/VaultApp.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/demo/VaultApp.java @@ -36,8 +36,7 @@ public class VaultApp { vaultTemplate.write("secret/myapp", secrets); - VaultResponseSupport<Secrets> response = vaultTemplate.read("secret/myapp", - Secrets.class); + VaultResponseSupport<Secrets> response = vaultTemplate.read("secret/myapp", Secrets.class); System.out.println(response.getRequiredData().getUsername()); vaultTemplate.delete("secret/myapp"); @@ -46,14 +45,17 @@ public class VaultApp { static class Secrets { String username; + String password; String getUsername() { - return username; + return this.username; } public String getPassword() { - return password; + return this.password; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/domain/Person.java b/spring-vault-core/src/test/java/org/springframework/vault/domain/Person.java index 0338b745..689c75bc 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/domain/Person.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/domain/Person.java @@ -34,7 +34,7 @@ public class Person { private String password; public String getId() { - return id; + return this.id; } public void setId(String id) { @@ -42,7 +42,7 @@ public class Person { } public String getFirstname() { - return firstname; + return this.firstname; } public void setFirstname(String firstname) { @@ -50,7 +50,7 @@ public class Person { } public String getLastname() { - return lastname; + return this.lastname; } public void setLastname(String lastname) { @@ -58,7 +58,7 @@ public class Person { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { @@ -72,13 +72,13 @@ public class Person { if (!(o instanceof Person)) return false; Person person = (Person) o; - return Objects.equals(id, person.id) - && Objects.equals(firstname, person.firstname) - && Objects.equals(password, person.password); + return Objects.equals(this.id, person.id) && Objects.equals(this.firstname, person.firstname) + && Objects.equals(this.password, person.password); } @Override public int hashCode() { - return Objects.hash(id, firstname, password); + return Objects.hash(this.id, this.firstname, this.password); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/MultipleSpringDataModulesIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/MultipleSpringDataModulesIntegrationTests.java index ac47a332..16d78706 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/MultipleSpringDataModulesIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/MultipleSpringDataModulesIntegrationTests.java @@ -52,8 +52,8 @@ class MultipleSpringDataModulesIntegrationTests extends IntegrationTestSupport { excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = VaultRepository.class)) @EnableVaultRepositories(considerNestedRepositories = true, // excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = MapRepository.class)) - static class MultipleModulesActiveTestConfiguration - extends VaultIntegrationTestConfiguration { + static class MultipleModulesActiveTestConfiguration extends VaultIntegrationTestConfiguration { + } @Autowired @@ -67,7 +67,7 @@ class MultipleSpringDataModulesIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - vaultRepository.deleteAll(); + this.vaultRepository.deleteAll(); } @Test @@ -77,39 +77,42 @@ class MultipleSpringDataModulesIntegrationTests extends IntegrationTestSupport { person.setId("foo-key"); person.setFirstname("bar"); - vaultRepository.save(person); + this.vaultRepository.save(person); - Iterable<Person> all = vaultRepository.findAll(); + Iterable<Person> all = this.vaultRepository.findAll(); assertThat(all).contains(person); - assertThat(vaultRepository.findByIdStartsWith("foo-key")).contains(person); + assertThat(this.vaultRepository.findByIdStartsWith("foo-key")).contains(person); } @Test void loadAndSaveMapRepository() { - vaultRepository.findAll().forEach(vaultRepository::delete); + this.vaultRepository.findAll().forEach(this.vaultRepository::delete); Person person = new Person(); person.setId("foo-key"); person.setFirstname("bar"); - mapRepository.save(person); + this.mapRepository.save(person); - Iterable<Person> all = mapRepository.findAll(); + Iterable<Person> all = this.mapRepository.findAll(); assertThat(all).contains(person); - assertThat(mapRepository.findByFirstnameStartsWith("bar")).contains(person); - assertThat(vaultRepository.findById("foo-key")).isEmpty(); + assertThat(this.mapRepository.findByFirstnameStartsWith("bar")).contains(person); + assertThat(this.vaultRepository.findById("foo-key")).isEmpty(); } interface VaultRepository extends CrudRepository<Person, String> { List<Person> findByIdStartsWith(String prefix); + } interface MapRepository extends CrudRepository<Person, String> { List<Person> findByFirstnameStartsWith(String prefix); + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/VaultRepositoryIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/VaultRepositoryIntegrationTests.java index d19418a8..afb1d015 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/VaultRepositoryIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/VaultRepositoryIntegrationTests.java @@ -50,8 +50,8 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { @Configuration @EnableVaultRepositories(considerNestedRepositories = true) - static class VaultRepositoryTestConfiguration - extends VaultIntegrationTestConfiguration { + static class VaultRepositoryTestConfiguration extends VaultIntegrationTestConfiguration { + } @Autowired @@ -62,7 +62,7 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - vaultRepository.deleteAll(); + this.vaultRepository.deleteAll(); } @Test @@ -72,12 +72,12 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { person.setId("foo-key"); person.setFirstname("bar"); - vaultRepository.save(person); + this.vaultRepository.save(person); - Iterable<Person> all = vaultRepository.findAll(); + Iterable<Person> all = this.vaultRepository.findAll(); assertThat(all).contains(person); - assertThat(vaultRepository.findById("foo-key")).contains(person); + assertThat(this.vaultRepository.findById("foo-key")).contains(person); } @Test @@ -87,15 +87,15 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { walter.setId("walter"); walter.setFirstname("Walter"); - vaultRepository.save(walter); + this.vaultRepository.save(walter); Person skyler = new Person(); skyler.setId("skyler"); skyler.setFirstname("Skyler"); - vaultRepository.save(skyler); + this.vaultRepository.save(skyler); - Iterable<Person> all = vaultRepository.findByIdStartsWith("walt"); + Iterable<Person> all = this.vaultRepository.findByIdStartsWith("walt"); assertThat(all).contains(walter).doesNotContain(skyler); } @@ -107,18 +107,16 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { walter.setId("walter"); walter.setFirstname("Walter"); - vaultRepository.save(walter); + this.vaultRepository.save(walter); Person skyler = new Person(); skyler.setId("skyler"); skyler.setFirstname("Skyler"); - vaultRepository.save(skyler); + this.vaultRepository.save(skyler); - assertThat(vaultRepository.findAllByOrderByFirstnameAsc()) - .containsSequence(skyler, walter); - assertThat(vaultRepository.findAllByOrderByFirstnameDesc()) - .containsSequence(walter, skyler); + assertThat(this.vaultRepository.findAllByOrderByFirstnameAsc()).containsSequence(skyler, walter); + assertThat(this.vaultRepository.findAllByOrderByFirstnameDesc()).containsSequence(walter, skyler); } @Test @@ -128,22 +126,21 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { walter.setId("walter"); walter.setFirstname("Walter"); - vaultRepository.save(walter); + this.vaultRepository.save(walter); Person skyler = new Person(); skyler.setId("skyler"); skyler.setFirstname("Skyler"); - vaultRepository.save(skyler); + this.vaultRepository.save(skyler); - assertThat(vaultRepository.findTop1By(Sort.by(asc("firstname")))) - .containsOnly(skyler); + assertThat(this.vaultRepository.findTop1By(Sort.by(asc("firstname")))).containsOnly(skyler); } @Test void shouldFailForNonIdCriteria() { assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) - .isThrownBy(() -> vaultRepository.findInvalidByFirstname("foo")); + .isThrownBy(() -> this.vaultRepository.findInvalidByFirstname("foo")); } interface VaultRepository extends CrudRepository<Person, String> { @@ -157,5 +154,7 @@ class VaultRepositoryIntegrationTests extends IntegrationTestSupport { List<Person> findTop1By(Sort sort); List<Person> findInvalidByFirstname(String name); + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapperUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapperUnitTests.java index 98524bbf..905cafb5 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapperUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/DefaultVaultTypeMapperUnitTests.java @@ -61,8 +61,8 @@ class DefaultVaultTypeMapperUnitTests { @Test void writesMapKeyForType() { - typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - Collections.singletonList(configurableTypeInformationMapper)); + this.typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, + Collections.singletonList(this.configurableTypeInformationMapper)); writesTypeToField(new LinkedHashMap<>(), String.class, "1"); writesTypeToField(new LinkedHashMap<>(), Object.class, null); @@ -71,9 +71,8 @@ class DefaultVaultTypeMapperUnitTests { @Test void writesClassNamesForUnmappedValuesIfConfigured() { - typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - Arrays.asList(configurableTypeInformationMapper, - simpleTypeInformationMapper)); + this.typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, + Arrays.asList(this.configurableTypeInformationMapper, this.simpleTypeInformationMapper)); writesTypeToField(new LinkedHashMap<>(), String.class, "1"); writesTypeToField(new LinkedHashMap<>(), Object.class, Object.class.getName()); } @@ -81,110 +80,90 @@ class DefaultVaultTypeMapperUnitTests { @Test void readsTypeForMapKey() { - typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - Collections.singletonList(configurableTypeInformationMapper)); + this.typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, + Collections.singletonList(this.configurableTypeInformationMapper)); - readsTypeFromField( - Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "1"), - String.class); - readsTypeFromField(Collections - .singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "unmapped"), null); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "1"), String.class); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "unmapped"), null); } @Test void readsTypeLoadingClassesForUnmappedTypesIfConfigured() { - typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - Arrays.asList(configurableTypeInformationMapper, - simpleTypeInformationMapper)); + this.typeMapper = new DefaultVaultTypeMapper(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, + Arrays.asList(this.configurableTypeInformationMapper, this.simpleTypeInformationMapper)); - readsTypeFromField( - Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "1"), - String.class); - readsTypeFromField( - Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - Object.class.getName()), + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "1"), String.class); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, Object.class.getName()), Object.class); } @Test void addsFullyQualifiedClassNameUnderDefaultKeyByDefault() { - writesTypeToField(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, new LinkedHashMap<>(), - String.class); + writesTypeToField(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, new LinkedHashMap<>(), String.class); } @Test void writesTypeToCustomFieldIfConfigured() { - typeMapper = new DefaultVaultTypeMapper("_custom"); + this.typeMapper = new DefaultVaultTypeMapper("_custom"); writesTypeToField("_custom", new LinkedHashMap<>(), String.class); } @Test void doesNotWriteTypeInformationInCaseKeyIsSetToNull() { - typeMapper = new DefaultVaultTypeMapper(null); + this.typeMapper = new DefaultVaultTypeMapper(null); writesTypeToField(null, new LinkedHashMap<>(), String.class); } @Test void readsTypeFromDefaultKeyByDefault() { - readsTypeFromField( - Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - String.class.getName()), + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, String.class.getName()), String.class); } @Test void readsTypeFromCustomFieldConfigured() { - typeMapper = new DefaultVaultTypeMapper("_custom"); - readsTypeFromField(Collections.singletonMap("_custom", String.class.getName()), - String.class); + this.typeMapper = new DefaultVaultTypeMapper("_custom"); + readsTypeFromField(Collections.singletonMap("_custom", String.class.getName()), String.class); } @Test void returnsNullIfNoTypeInfoInDocument() { readsTypeFromField(new LinkedHashMap<>(), null); - readsTypeFromField( - Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, ""), - null); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, ""), null); } @Test void returnsNullIfClassCannotBeLoaded() { - readsTypeFromField(Collections - .singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "fooBar"), null); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, "fooBar"), null); } @Test void returnsNullIfTypeKeySetToNull() { - typeMapper = new DefaultVaultTypeMapper(null); - readsTypeFromField(Collections.singletonMap( - DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, String.class), null); + this.typeMapper = new DefaultVaultTypeMapper(null); + readsTypeFromField(Collections.singletonMap(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, String.class), null); } @Test void returnsCorrectTypeKey() { - assertThat(typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)) - .isTrue(); + assertThat(this.typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)).isTrue(); - typeMapper = new DefaultVaultTypeMapper("_custom"); - assertThat(typeMapper.isTypeKey("_custom")).isTrue(); - assertThat(typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)) - .isFalse(); + this.typeMapper = new DefaultVaultTypeMapper("_custom"); + assertThat(this.typeMapper.isTypeKey("_custom")).isTrue(); + assertThat(this.typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)).isFalse(); - typeMapper = new DefaultVaultTypeMapper(null); - assertThat(typeMapper.isTypeKey("_custom")).isFalse(); - assertThat(typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)) - .isFalse(); + this.typeMapper = new DefaultVaultTypeMapper(null); + assertThat(this.typeMapper.isTypeKey("_custom")).isFalse(); + assertThat(this.typeMapper.isTypeKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY)).isFalse(); } - private void readsTypeFromField(Map<String, Object> document, - @Nullable Class<?> type) { + private void readsTypeFromField(Map<String, Object> document, @Nullable Class<?> type) { - TypeInformation<?> typeInfo = typeMapper.readType(document); + TypeInformation<?> typeInfo = this.typeMapper.readType(document); if (type != null) { assertThat(typeInfo).isNotNull(); @@ -195,10 +174,9 @@ class DefaultVaultTypeMapperUnitTests { } } - private void writesTypeToField(@Nullable String field, Map<String, Object> document, - Class<?> type) { + private void writesTypeToField(@Nullable String field, Map<String, Object> document, Class<?> type) { - typeMapper.writeType(type, document); + this.typeMapper.writeType(type, document); if (field == null) { assertThat(document.keySet()).isEmpty(); @@ -209,18 +187,17 @@ class DefaultVaultTypeMapperUnitTests { } } - private void writesTypeToField(Map<String, Object> document, Class<?> type, - @Nullable Object value) { + private void writesTypeToField(Map<String, Object> document, Class<?> type, @Nullable Object value) { - typeMapper.writeType(type, document); + this.typeMapper.writeType(type, document); if (value == null) { assertThat(document.keySet()).isEmpty(); } else { assertThat(document).containsKey(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY); - assertThat(document).containsEntry(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, - value); + assertThat(document).containsEntry(DefaultVaultTypeMapper.DEFAULT_TYPE_KEY, value); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/MappingVaultConverterUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/MappingVaultConverterUnitTests.java index e3852467..0553c31d 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/MappingVaultConverterUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/convert/MappingVaultConverterUnitTests.java @@ -39,15 +39,15 @@ class MappingVaultConverterUnitTests { VaultMappingContext context = new VaultMappingContext(); - MappingVaultConverter converter = new MappingVaultConverter(context); + MappingVaultConverter converter = new MappingVaultConverter(this.context); @BeforeEach void before() { - VaultCustomConversions conversions = new VaultCustomConversions(Arrays.asList( - DocumentToPersonConverter.INSTANCE, PersonToDocumentConverter.INSTANCE)); - converter.setCustomConversions(conversions); - converter.afterPropertiesSet(); + VaultCustomConversions conversions = new VaultCustomConversions( + Arrays.asList(DocumentToPersonConverter.INSTANCE, PersonToDocumentConverter.INSTANCE)); + this.converter.setCustomConversions(conversions); + this.converter.afterPropertiesSet(); } @Test @@ -57,7 +57,7 @@ class MappingVaultConverterUnitTests { document.put("username", "walter"); document.put("password", "hb"); - SimpleEntity entity = converter.read(SimpleEntity.class, document); + SimpleEntity entity = this.converter.read(SimpleEntity.class, document); assertThat(entity.getId()).isEqualTo("heisenberg"); assertThat(entity.getUsername()).isEqualTo("walter"); @@ -70,7 +70,7 @@ class MappingVaultConverterUnitTests { SecretDocument document = new SecretDocument("heisenberg"); document.put("the_name", "walter"); - Person entity = converter.read(Person.class, document); + Person entity = this.converter.read(Person.class, document); assertThat(entity.getName()).isEqualTo("walter"); } @@ -84,7 +84,7 @@ class MappingVaultConverterUnitTests { document.put("password", "hb"); document.put("location", "Albuquerque"); - SimpleEntity entity = converter.read(SimpleEntity.class, document); + SimpleEntity entity = this.converter.read(SimpleEntity.class, document); assertThat(entity).isInstanceOf(ExtendedEntity.class); assertThat(entity.getId()).isEqualTo("heisenberg"); @@ -99,7 +99,7 @@ class MappingVaultConverterUnitTests { SecretDocument document = new SecretDocument(); document.put("condition", "BAD"); - EntityWithEnum entity = converter.read(EntityWithEnum.class, document); + EntityWithEnum entity = this.converter.read(EntityWithEnum.class, document); assertThat(entity.getCondition()).isEqualTo(Condition.BAD); } @@ -111,7 +111,7 @@ class MappingVaultConverterUnitTests { document.put("username", "walter"); document.put("password", "hb"); - ConstructorCreation entity = converter.read(ConstructorCreation.class, document); + ConstructorCreation entity = this.converter.read(ConstructorCreation.class, document); assertThat(entity.getId()).isEqualTo("heisenberg"); assertThat(entity.getUsername()).isEqualTo("walter"); @@ -121,11 +121,10 @@ class MappingVaultConverterUnitTests { @Test void shouldReadEntityWithList() { - SecretDocument document = new SecretDocument(Collections.singletonMap("usernames", - Arrays.asList("walter", "heisenberg"))); + SecretDocument document = new SecretDocument( + Collections.singletonMap("usernames", Arrays.asList("walter", "heisenberg"))); - EntityWithListOfStrings entity = converter.read(EntityWithListOfStrings.class, - document); + EntityWithListOfStrings entity = this.converter.read(EntityWithListOfStrings.class, document); assertThat(entity.getUsernames()).containsSequence("walter", "heisenberg"); } @@ -137,10 +136,9 @@ class MappingVaultConverterUnitTests { keyVersions.put("foo", 1); keyVersions.put("bar", 2); - SecretDocument document = new SecretDocument( - Collections.singletonMap("keyVersions", keyVersions)); + SecretDocument document = new SecretDocument(Collections.singletonMap("keyVersions", keyVersions)); - EntityWithMap entity = converter.read(EntityWithMap.class, document); + EntityWithMap entity = this.converter.read(EntityWithMap.class, document); assertThat(entity.getKeyVersions()).containsAllEntriesOf(keyVersions); } @@ -155,8 +153,7 @@ class MappingVaultConverterUnitTests { SecretDocument document = new SecretDocument(); document.put("nested", walter); - EntityWithNestedType entity = converter.read(EntityWithNestedType.class, - document); + EntityWithNestedType entity = this.converter.read(EntityWithNestedType.class, document); assertThat(entity.getNested()).isEqualTo(new NestedType("heisenberg", "hb")); } @@ -175,11 +172,9 @@ class MappingVaultConverterUnitTests { SecretDocument document = new SecretDocument(); document.put("nested", Arrays.asList(walter, skyler)); - EntityWithListOfEntities entity = converter.read(EntityWithListOfEntities.class, - document); + EntityWithListOfEntities entity = this.converter.read(EntityWithListOfEntities.class, document); - assertThat(entity.getNested()).contains(new NestedType("heisenberg", "hb"), - new NestedType("skyler", "marie")); + assertThat(entity.getNested()).contains(new NestedType("heisenberg", "hb"), new NestedType("skyler", "marie")); } @Test @@ -197,7 +192,7 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(entity, sink); + this.converter.write(entity, sink); assertThat(sink).isEqualTo(expected); } @@ -210,7 +205,7 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(new Person("walter"), sink); + this.converter.write(new Person("walter"), sink); assertThat(sink).isEqualTo(expected); } @@ -223,7 +218,7 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(entity, sink); + this.converter.write(entity, sink); assertThat(sink.getBody()).containsEntry("condition", "BAD"); } @@ -236,10 +231,9 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(entity, sink); + this.converter.write(entity, sink); - assertThat(sink.getBody()).containsEntry("usernames", - Arrays.asList("walter", "heisenberg")); + assertThat(sink.getBody()).containsEntry("usernames", Arrays.asList("walter", "heisenberg")); } @Test @@ -254,7 +248,7 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(entity, sink); + this.converter.write(entity, sink); assertThat(sink.getBody()).containsEntry("keyVersions", keyVersions); } @@ -264,8 +258,7 @@ class MappingVaultConverterUnitTests { void shouldWriteEntityWithListOfEntities() { EntityWithListOfEntities entity = new EntityWithListOfEntities(); - entity.setNested(Arrays.asList(new NestedType("heisenberg", "hb"), - new NestedType("skyler", "marie"))); + entity.setNested(Arrays.asList(new NestedType("heisenberg", "hb"), new NestedType("skyler", "marie"))); Map<String, Object> walter = new LinkedHashMap<>(); walter.put("username", "heisenberg"); @@ -277,16 +270,17 @@ class MappingVaultConverterUnitTests { SecretDocument sink = new SecretDocument(); - converter.write(entity, sink); + this.converter.write(entity, sink); - assertThat((List<Map<String, Object>>) sink.get("nested")).contains(walter, - skyler); + assertThat((List<Map<String, Object>>) sink.get("nested")).contains(walter, skyler); } static class SimpleEntity { String id; + String username; + String password; public String getId() { @@ -312,6 +306,7 @@ class MappingVaultConverterUnitTests { public void setPassword(String password) { this.password = password; } + } static class ExtendedEntity extends SimpleEntity { @@ -325,6 +320,7 @@ class MappingVaultConverterUnitTests { public void setLocation(String location) { this.location = location; } + } static class EntityWithNestedType { @@ -338,6 +334,7 @@ class MappingVaultConverterUnitTests { public void setNested(NestedType nested) { this.nested = nested; } + } static class EntityWithEnum { @@ -351,12 +348,15 @@ class MappingVaultConverterUnitTests { public void setCondition(Condition condition) { this.condition = condition; } + } static class ConstructorCreation { final String id; + final String username; + String password; public ConstructorCreation(String id, String username) { @@ -379,6 +379,7 @@ class MappingVaultConverterUnitTests { public void setPassword(String password) { this.password = password; } + } static class EntityWithListOfStrings { @@ -392,6 +393,7 @@ class MappingVaultConverterUnitTests { public void setUsernames(List<String> usernames) { this.usernames = usernames; } + } static class EntityWithListOfEntities { @@ -405,6 +407,7 @@ class MappingVaultConverterUnitTests { public void setNested(List<NestedType> nested) { this.nested = nested; } + } static class EntityWithMap { @@ -421,11 +424,13 @@ class MappingVaultConverterUnitTests { public void setKeyVersions(Map<String, Integer> keyVersions) { this.keyVersions = keyVersions; } + } static class NestedType { String username; + String password; public NestedType(String username, String password) { @@ -456,21 +461,24 @@ class MappingVaultConverterUnitTests { if (!(o instanceof NestedType)) return false; NestedType that = (NestedType) o; - return Objects.equals(username, that.username) - && Objects.equals(password, that.password); + return Objects.equals(this.username, that.username) && Objects.equals(this.password, that.password); } @Override public int hashCode() { - return Objects.hash(username, password); + return Objects.hash(this.username, this.password); } + } enum Condition { + GOOD, BAD + } static class Person { + final String name; public Person(String name) { @@ -480,6 +488,7 @@ class MappingVaultConverterUnitTests { public String getName() { return this.name; } + } enum DocumentToPersonConverter implements Converter<SecretDocument, Person> { @@ -490,6 +499,7 @@ class MappingVaultConverterUnitTests { public Person convert(SecretDocument secretDocument) { return new Person((String) secretDocument.get("the_name")); } + } enum PersonToDocumentConverter implements Converter<Person, SecretDocument> { @@ -503,5 +513,7 @@ class MappingVaultConverterUnitTests { document.put("the_name", person.getName()); return document; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntityUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntityUnitTests.java index 8e6b0be5..dfbf1b7f 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntityUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/BasicVaultPersistentEntityUnitTests.java @@ -39,8 +39,7 @@ class BasicVaultPersistentEntityUnitTests { @Test void shouldSetIdPropertyThroughName() { - VaultPersistentEntity<?> persistentEntity = mappingContext - .getPersistentEntity(IdProperty.class); + VaultPersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(IdProperty.class); assertThat(persistentEntity.getIdProperty()).isNotNull(); } @@ -48,8 +47,7 @@ class BasicVaultPersistentEntityUnitTests { @Test void shouldSetIdPropertyThroughAnnotation() { - VaultPersistentEntity<?> persistentEntity = mappingContext - .getPersistentEntity(ExplicitId.class); + VaultPersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(ExplicitId.class); assertThat(persistentEntity.getIdProperty()).isNotNull(); } @@ -57,12 +55,10 @@ class BasicVaultPersistentEntityUnitTests { @Test void shouldEvaluateExpression() { - VaultPersistentEntity<?> persistentEntity = mappingContext - .getPersistentEntity(ExpressionEntity.class); + VaultPersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(ExpressionEntity.class); - persistentEntity - .setEvaluationContextProvider(new ExtensionAwareEvaluationContextProvider( - Collections.singletonList(new SampleExtension()))); + persistentEntity.setEvaluationContextProvider( + new ExtensionAwareEvaluationContextProvider(Collections.singletonList(new SampleExtension()))); assertThat(persistentEntity.getSecretBackend()).isEqualTo("collectionName"); @@ -70,18 +66,24 @@ class BasicVaultPersistentEntityUnitTests { } private static class IdProperty { + String id, username; + } private static class ExplicitId { + @Id String username; + } @Secret(backend = "#{myProperty}", value = "#{myKeySpace}") private static class ExpressionEntity { + @Id String username; + } static class SampleExtension implements EvaluationContextExtension { @@ -99,5 +101,7 @@ class BasicVaultPersistentEntityUnitTests { properties.put("myKeySpace", "foo"); return properties; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/VaultMappingContextUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/VaultMappingContextUnitTests.java index bc5751d2..0eab5306 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/VaultMappingContextUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/mapping/VaultMappingContextUnitTests.java @@ -31,7 +31,7 @@ class VaultMappingContextUnitTests { @Test void shouldCreatePersistentEntity() { - VaultPersistentEntity<?> entity = context.getPersistentEntity(Person.class); + VaultPersistentEntity<?> entity = this.context.getPersistentEntity(Person.class); assertThat(entity).isNotNull(); assertThat(entity.getSecretBackend()).isEqualTo("secret"); @@ -41,26 +41,25 @@ class VaultMappingContextUnitTests { @Test void shouldDetermineKeyspace() { - assertThat(context.getRequiredPersistentEntity(Login.class).getSecretBackend()) - .isEqualTo("secret"); - assertThat(context.getRequiredPersistentEntity(Login.class).getKeySpace()) - .isEqualTo("secret/login"); + assertThat(this.context.getRequiredPersistentEntity(Login.class).getSecretBackend()).isEqualTo("secret"); + assertThat(this.context.getRequiredPersistentEntity(Login.class).getKeySpace()).isEqualTo("secret/login"); - assertThat( - context.getRequiredPersistentEntity(Credentials.class).getSecretBackend()) - .isEqualTo("shared"); - assertThat(context.getRequiredPersistentEntity(Credentials.class).getKeySpace()) - .isEqualTo("shared/Email"); + assertThat(this.context.getRequiredPersistentEntity(Credentials.class).getSecretBackend()).isEqualTo("shared"); + assertThat(this.context.getRequiredPersistentEntity(Credentials.class).getKeySpace()).isEqualTo("shared/Email"); } private static class Person { + } @Secret private static class Login { + } @Secret(value = "Email", backend = "shared") private static class Credentials { + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/repository/query/VaultQueryCreatorUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/repository/query/VaultQueryCreatorUnitTests.java index 45e9f672..7d5b073c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/repository/query/VaultQueryCreatorUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/repository/query/VaultQueryCreatorUnitTests.java @@ -191,28 +191,24 @@ class VaultQueryCreatorUnitTests { VaultQuery createQuery(String methodName, String value) { - DefaultParameters defaultParameters = new DefaultParameters(ReflectionUtils - .findMethod(dummy.class, "someUnrelatedMethod", String.class)); + DefaultParameters defaultParameters = new DefaultParameters( + ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class)); PartTree partTree = new PartTree(methodName, Credentials.class); VaultQueryCreator queryCreator = new VaultQueryCreator(partTree, - new ParametersParameterAccessor(defaultParameters, - new Object[] { value }), - mappingContext); + new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext); return queryCreator.createQuery().getCriteria(); } VaultQuery createQuery(String methodName, List<String> value) { - DefaultParameters defaultParameters = new DefaultParameters(ReflectionUtils - .findMethod(dummy.class, "someUnrelatedMethod", List.class)); + DefaultParameters defaultParameters = new DefaultParameters( + ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", List.class)); PartTree partTree = new PartTree(methodName, Credentials.class); VaultQueryCreator queryCreator = new VaultQueryCreator(partTree, - new ParametersParameterAccessor(defaultParameters, - new Object[] { value }), - mappingContext); + new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext); return queryCreator.createQuery().getCriteria(); } @@ -220,14 +216,12 @@ class VaultQueryCreatorUnitTests { VaultQuery createQuery(String methodName, String value, String anotherValue) { DefaultParameters defaultParameters = new DefaultParameters( - ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", - String.class, String.class)); + ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class, String.class)); PartTree partTree = new PartTree(methodName, Credentials.class); VaultQueryCreator queryCreator = new VaultQueryCreator(partTree, - new ParametersParameterAccessor(defaultParameters, - new Object[] { value, anotherValue }), - mappingContext); + new ParametersParameterAccessor(defaultParameters, new Object[] { value, anotherValue }), + this.mappingContext); return queryCreator.createQuery().getCriteria(); } @@ -239,10 +233,13 @@ class VaultQueryCreatorUnitTests { Object someUnrelatedMethod(List<String> arg); Object someUnrelatedMethod(String from, String to); + } private static class Credentials { String id, name; + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesEncryptorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesEncryptorIntegrationTests.java index ad0b18c5..2331b845 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesEncryptorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesEncryptorIntegrationTests.java @@ -43,21 +43,21 @@ class VaultBytesEncryptorIntegrationTests extends IntegrationTestSupport { @BeforeEach void before() { - transit = prepare().getVaultOperations().opsForTransit(); - vaultVersion = prepare().getVersion(); + this.transit = prepare().getVaultOperations().opsForTransit(); + this.vaultVersion = prepare().getVersion(); if (!prepare().hasSecret("transit")) { prepare().mountSecret("transit"); } removeKeys(); - transit.createKey(KEY_NAME); + this.transit.createKey(KEY_NAME); } private void removeKeys() { - if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { - List<String> keys = transit.getKeys(); + if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { + List<String> keys = this.transit.getKeys(); keys.forEach(this::deleteKey); } else { @@ -68,14 +68,13 @@ class VaultBytesEncryptorIntegrationTests extends IntegrationTestSupport { private void deleteKey(String keyName) { try { - transit.configureKey(keyName, - VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); + this.transit.configureKey(keyName, VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); } catch (Exception e) { } try { - transit.deleteKey(keyName); + this.transit.deleteKey(keyName); } catch (Exception e) { } @@ -84,7 +83,7 @@ class VaultBytesEncryptorIntegrationTests extends IntegrationTestSupport { @Test void shouldEncryptAndDecrypt() { - VaultBytesEncryptor encryptor = new VaultBytesEncryptor(transit, KEY_NAME); + VaultBytesEncryptor encryptor = new VaultBytesEncryptor(this.transit, KEY_NAME); byte[] plaintext = "foo-bar+ü¿ß~€¢".getBytes(); byte[] ciphertext = encryptor.encrypt(plaintext); @@ -94,4 +93,5 @@ class VaultBytesEncryptorIntegrationTests extends IntegrationTestSupport { assertThat(ciphertext).isNotEqualTo(plaintext).startsWith("vault:v1".getBytes()); assertThat(result).isEqualTo(plaintext); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesKeyGeneratorIntegrationTests.java b/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesKeyGeneratorIntegrationTests.java index 08a015d9..c8e94a12 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesKeyGeneratorIntegrationTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/security/VaultBytesKeyGeneratorIntegrationTests.java @@ -42,10 +42,10 @@ class VaultBytesKeyGeneratorIntegrationTests extends IntegrationTestSupport { @Test void shouldGenerateRandomBytes() { - VaultBytesKeyGenerator generator = new VaultBytesKeyGenerator( - prepare().getVaultOperations(), "transit", 16); + VaultBytesKeyGenerator generator = new VaultBytesKeyGenerator(prepare().getVaultOperations(), "transit", 16); assertThat(generator.generateKey()).hasSize(16); assertThat(generator.getKeyLength()).isEqualTo(16); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateBundleUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateBundleUnitTests.java index 53804fa2..3f942234 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateBundleUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateBundleUnitTests.java @@ -40,18 +40,17 @@ class CertificateBundleUnitTests { @SuppressWarnings("unchecked") @BeforeEach void before() throws Exception { - Map<String, String> data = OBJECT_MAPPER - .readValue(getClass().getResource("/certificate.json"), Map.class); + Map<String, String> data = this.OBJECT_MAPPER.readValue(getClass().getResource("/certificate.json"), Map.class); - certificateBundle = CertificateBundle.of(data.get("serial_number"), - data.get("certificate"), data.get("issuing_ca"), data.get("private_key")); + this.certificateBundle = CertificateBundle.of(data.get("serial_number"), data.get("certificate"), + data.get("issuing_ca"), data.get("private_key")); } @Test void getPrivateKeySpecShouldCreatePrivateKey() throws Exception { KeyFactory kf = KeyFactory.getInstance("RSA"); - PrivateKey privateKey = kf.generatePrivate(certificateBundle.getPrivateKeySpec()); + PrivateKey privateKey = kf.generatePrivate(this.certificateBundle.getPrivateKeySpec()); assertThat(privateKey.getAlgorithm()).isEqualTo("RSA"); assertThat(privateKey.getFormat()).isEqualTo("PKCS#8"); @@ -60,9 +59,10 @@ class CertificateBundleUnitTests { @Test void getAsKeystore() throws Exception { - KeyStore keyStore = certificateBundle.createKeyStore("mykey"); + KeyStore keyStore = this.certificateBundle.createKeyStore("mykey"); assertThat(keyStore.size()).isEqualTo(1); assertThat(keyStore.getCertificateChain("mykey")).hasSize(2); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateUnitTests.java index aa181118..cb48529c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/CertificateUnitTests.java @@ -39,36 +39,33 @@ class CertificateUnitTests { @SuppressWarnings("unchecked") @BeforeEach void before() throws Exception { - Map<String, String> data = OBJECT_MAPPER - .readValue(getClass().getResource("/certificate.json"), Map.class); + Map<String, String> data = this.OBJECT_MAPPER.readValue(getClass().getResource("/certificate.json"), Map.class); - certificate = Certificate.of(data.get("serial_number"), data.get("certificate"), - data.get("issuing_ca")); + this.certificate = Certificate.of(data.get("serial_number"), data.get("certificate"), data.get("issuing_ca")); } @Test void getX509CertificateShouldReturnCertificate() { - X509Certificate x509Certificate = certificate.getX509Certificate(); + X509Certificate x509Certificate = this.certificate.getX509Certificate(); - assertThat(x509Certificate.getSubjectDN().getName()) - .isEqualTo("CN=hello.example.com"); + assertThat(x509Certificate.getSubjectDN().getName()).isEqualTo("CN=hello.example.com"); } @Test void getX509IssuerCertificateShouldReturnCertificate() { - X509Certificate x509Certificate = certificate.getX509IssuerCertificate(); + X509Certificate x509Certificate = this.certificate.getX509IssuerCertificate(); - assertThat(x509Certificate.getSubjectDN().getName()) - .startsWith("CN=Intermediate CA Certificate"); + assertThat(x509Certificate.getSubjectDN().getName()).startsWith("CN=Intermediate CA Certificate"); } @Test void getAsTrustStore() throws Exception { - KeyStore keyStore = certificate.createTrustStore(); + KeyStore keyStore = this.certificate.createTrustStore(); assertThat(keyStore.size()).isEqualTo(2); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/JsonMapFlattenerUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/JsonMapFlattenerUnitTests.java index 8b279f5d..43513c73 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/JsonMapFlattenerUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/JsonMapFlattenerUnitTests.java @@ -36,16 +36,14 @@ class JsonMapFlattenerUnitTests { @Test void shouldPreserveFlatMap() { - Map<String, Object> result = JsonMapFlattener - .flatten(Collections.singletonMap("key", "value")); + Map<String, Object> result = JsonMapFlattener.flatten(Collections.singletonMap("key", "value")); assertThat(result).containsEntry("key", "value"); } @Test void shouldFlattenNestedObject() throws Exception { - Map<String, Object> map = OBJECT_MAPPER - .readValue("{\"key\": { \"nested\":true} }", Map.class); + Map<String, Object> map = this.OBJECT_MAPPER.readValue("{\"key\": { \"nested\":true} }", Map.class); Map<String, Object> result = JsonMapFlattener.flatten(map); assertThat(result).containsEntry("key.nested", true); @@ -54,8 +52,8 @@ class JsonMapFlattenerUnitTests { @Test void shouldFlattenDeeplyNestedObject() throws Exception { - Map<String, Object> map = OBJECT_MAPPER.readValue( - "{\"key\": { \"nested\": {\"anotherLevel\": \"value\"} } }", Map.class); + Map<String, Object> map = this.OBJECT_MAPPER + .readValue("{\"key\": { \"nested\": {\"anotherLevel\": \"value\"} } }", Map.class); Map<String, Object> result = JsonMapFlattener.flatten(map); assertThat(result).containsEntry("key.nested.anotherLevel", "value"); @@ -64,37 +62,33 @@ class JsonMapFlattenerUnitTests { @Test void shouldFlattenNestedListOfSimpleObjects() throws Exception { - Map<String, Object> map = OBJECT_MAPPER.readValue( - "{\"key\": [\"one\", \"two\"], \"dotted.key\": [\"one\", \"two\"] }", - Map.class); + Map<String, Object> map = this.OBJECT_MAPPER + .readValue("{\"key\": [\"one\", \"two\"], \"dotted.key\": [\"one\", \"two\"] }", Map.class); Map<String, Object> result = JsonMapFlattener.flatten(map); assertThat(result).containsEntry("key[0]", "one").containsEntry("key[1]", "two"); - assertThat(result).containsEntry("dotted.key[0]", "one") - .containsEntry("dotted.key[1]", "two"); + assertThat(result).containsEntry("dotted.key[0]", "one").containsEntry("dotted.key[1]", "two"); } @Test void shouldFlattenNestedListOfComplexObject() throws Exception { - Map<String, Object> map = OBJECT_MAPPER.readValue( - "{\"key\": [{ \"nested\":\"value\"}, { \"nested\":\"other-value\"}] }", - Map.class); + Map<String, Object> map = this.OBJECT_MAPPER + .readValue("{\"key\": [{ \"nested\":\"value\"}, { \"nested\":\"other-value\"}] }", Map.class); Map<String, Object> result = JsonMapFlattener.flatten(map); - assertThat(result).containsEntry("key[0].nested", "value") - .containsEntry("key[1].nested", "other-value"); + assertThat(result).containsEntry("key[0].nested", "value").containsEntry("key[1].nested", "other-value"); } @Test void shouldFlattenDeeplyNestedListOfComplexObject() throws Exception { - Map<String, Object> map = OBJECT_MAPPER.readValue( - "{\"key\": { \"level1\": [{ \"nested\":\"value\"}, { \"nested\":\"other-value\"}]} }", - Map.class); + Map<String, Object> map = this.OBJECT_MAPPER.readValue( + "{\"key\": { \"level1\": [{ \"nested\":\"value\"}, { \"nested\":\"other-value\"}]} }", Map.class); Map<String, Object> result = JsonMapFlattener.flatten(map); - assertThat(result).containsEntry("key.level1[0].nested", "value") - .containsEntry("key.level1[1].nested", "other-value"); + assertThat(result).containsEntry("key.level1[0].nested", "value").containsEntry("key.level1[1].nested", + "other-value"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/ObjectMapperSupplier.java b/spring-vault-core/src/test/java/org/springframework/vault/support/ObjectMapperSupplier.java index 00b537ef..abf827b7 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/ObjectMapperSupplier.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/ObjectMapperSupplier.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; /** * {@link ObjectMapper} supplier for testing holding a singleton {@link ObjectMapper} * instance. + * * @author Mark Paluch */ public class ObjectMapperSupplier { @@ -31,4 +32,5 @@ public class ObjectMapperSupplier { public static ObjectMapper get() { return instance.objectMapper; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/PolicySerializationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/PolicySerializationUnitTests.java index 02206ccb..4ce19f77 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/PolicySerializationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/PolicySerializationUnitTests.java @@ -43,12 +43,10 @@ class PolicySerializationUnitTests { @Test void shouldSerialize() throws Exception { - Rule rule = Rule.builder().path("secret/*") - .capabilities("create", "read", "update") + Rule rule = Rule.builder().path("secret/*").capabilities("create", "read", "update") .allowedParameter("ttl", "1h", "2h").deniedParameter("password").build(); - Rule another = Rule.builder().path("secret/foo") - .capabilities("create", "read", "update", "delete", "list") + Rule another = Rule.builder().path("secret/foo").capabilities("create", "read", "update", "delete", "list") .minWrappingTtl(Duration.ofMinutes(1)).maxWrappingTtl(Duration.ofHours(1)) .allowedParameter("ttl", "1h", "2h").deniedParameter("password").build(); @@ -57,29 +55,26 @@ class PolicySerializationUnitTests { try (InputStream is = new ClassPathResource("policy.json").getInputStream()) { String expected = StreamUtils.copyToString(is, StandardCharsets.UTF_8); - JSONAssert.assertEquals(expected, OBJECT_MAPPER.writeValueAsString(policy), - JSONCompareMode.STRICT); + JSONAssert.assertEquals(expected, this.OBJECT_MAPPER.writeValueAsString(policy), JSONCompareMode.STRICT); } } @Test void shouldDeserialize() throws Exception { - Rule rule = Rule.builder().path("secret/*") - .capabilities("create", "read", "update", "update") + Rule rule = Rule.builder().path("secret/*").capabilities("create", "read", "update", "update") .allowedParameter("ttl", "1h", "2h").deniedParameter("password").build(); - Rule another = Rule.builder().path("secret/foo") - .capabilities("create", "read", "update", "delete", "list") + Rule another = Rule.builder().path("secret/foo").capabilities("create", "read", "update", "delete", "list") .minWrappingTtl(Duration.ofMinutes(1)).maxWrappingTtl(Duration.ofHours(1)) - .allowedParameter("ttl", "1h", "2h").allowedParameter("ttl", "1h", "2h") - .deniedParameter("password").build(); + .allowedParameter("ttl", "1h", "2h").allowedParameter("ttl", "1h", "2h").deniedParameter("password") + .build(); Policy expected = Policy.of(rule, another); try (InputStream is = new ClassPathResource("policy.json").getInputStream()) { - Policy actual = OBJECT_MAPPER.readValue(is, Policy.class); + Policy actual = this.OBJECT_MAPPER.readValue(is, Policy.class); assertThat(actual.getRules()).hasSameClassAs(expected.getRules()); @@ -87,45 +82,39 @@ class PolicySerializationUnitTests { assertThat(secretAll.getPath()).isEqualTo(rule.getPath()); assertThat(secretAll.getCapabilities()).isEqualTo(rule.getCapabilities()); - assertThat(secretAll.getAllowedParameters()) - .isEqualTo(rule.getAllowedParameters()); - assertThat(secretAll.getDeniedParameters()) - .isEqualTo(rule.getDeniedParameters()); + assertThat(secretAll.getAllowedParameters()).isEqualTo(rule.getAllowedParameters()); + assertThat(secretAll.getDeniedParameters()).isEqualTo(rule.getDeniedParameters()); Rule secretFoo = actual.getRule("secret/foo"); assertThat(secretFoo.getPath()).isEqualTo(another.getPath()); assertThat(secretFoo.getCapabilities()).isEqualTo(another.getCapabilities()); - assertThat(secretFoo.getMinWrappingTtl()) - .isEqualTo(another.getMinWrappingTtl()); - assertThat(secretFoo.getMaxWrappingTtl()) - .isEqualTo(another.getMaxWrappingTtl()); - assertThat(secretFoo.getAllowedParameters()) - .isEqualTo(another.getAllowedParameters()); - assertThat(secretFoo.getDeniedParameters()) - .isEqualTo(another.getDeniedParameters()); + assertThat(secretFoo.getMinWrappingTtl()).isEqualTo(another.getMinWrappingTtl()); + assertThat(secretFoo.getMaxWrappingTtl()).isEqualTo(another.getMaxWrappingTtl()); + assertThat(secretFoo.getAllowedParameters()).isEqualTo(another.getAllowedParameters()); + assertThat(secretFoo.getDeniedParameters()).isEqualTo(another.getDeniedParameters()); } } @Test void shouldDeserializeEmptyPolicy() throws Exception { - assertThat(OBJECT_MAPPER.readValue("{}", Policy.class)).isEqualTo(Policy.empty()); + assertThat(this.OBJECT_MAPPER.readValue("{}", Policy.class)).isEqualTo(Policy.empty()); } @Test void shouldRejectUnknownFieldNames() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> OBJECT_MAPPER - .readValue("{\"foo\":1, \"path\": {} }", Policy.class)); - assertThatIllegalArgumentException().isThrownBy( - () -> OBJECT_MAPPER.readValue("{\"foo\":\"bar\"}", Policy.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.OBJECT_MAPPER.readValue("{\"foo\":1, \"path\": {} }", Policy.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.OBJECT_MAPPER.readValue("{\"foo\":\"bar\"}", Policy.class)); } @Test void shouldDeserializePolicyWithEmptyRules() throws Exception { - Policy actual = OBJECT_MAPPER.readValue("{ \"path\": {} }", Policy.class); + Policy actual = this.OBJECT_MAPPER.readValue("{ \"path\": {} }", Policy.class); assertThat(actual).isEqualTo(Policy.empty()); } @@ -133,11 +122,11 @@ class PolicySerializationUnitTests { @Test void shouldDeserializeRuleWithHour() throws Exception { - Policy actual = OBJECT_MAPPER.readValue( - "{ \"path\": { \"secret\" : {\"min_wrapping_ttl\":\"1h\"} } }", + Policy actual = this.OBJECT_MAPPER.readValue("{ \"path\": { \"secret\" : {\"min_wrapping_ttl\":\"1h\"} } }", Policy.class); Rule rule = actual.getRule("secret"); assertThat(rule.getMinWrappingTtl()).isEqualTo(Duration.ofHours(1)); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/SslConfigurationUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/SslConfigurationUnitTests.java index fd04c616..71af410f 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/SslConfigurationUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/SslConfigurationUnitTests.java @@ -51,18 +51,16 @@ class SslConfigurationUnitTests { @Test void shouldCreateConfiguration() { - KeyStoreConfiguration keystore = KeyStoreConfiguration - .of(new ClassPathResource("certificate.json")); - SslConfiguration ksConfig = SslConfiguration.unconfigured() - .withKeyStore(keystore); + KeyStoreConfiguration keystore = KeyStoreConfiguration.of(new ClassPathResource("certificate.json")); + SslConfiguration ksConfig = SslConfiguration.unconfigured().withKeyStore(keystore); assertThat(ksConfig.getKeyStoreConfiguration()).isSameAs(keystore); assertThat(ksConfig.getTrustStoreConfiguration().isPresent()).isFalse(); - SslConfiguration tsConfig = SslConfiguration.unconfigured() - .withTrustStore(keystore); + SslConfiguration tsConfig = SslConfiguration.unconfigured().withTrustStore(keystore); assertThat(tsConfig.getTrustStoreConfiguration()).isSameAs(keystore); assertThat(tsConfig.getKeyStoreConfiguration().isPresent()).isFalse(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultCertificateRequestUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultCertificateRequestUnitTests.java index e386247a..a859183a 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultCertificateRequestUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultCertificateRequestUnitTests.java @@ -36,8 +36,7 @@ class VaultCertificateRequestUnitTests { @Test void shouldBuildRequestWithCommonName() { - VaultCertificateRequest request = VaultCertificateRequest.builder() - .commonName("hello.com").build(); + VaultCertificateRequest request = VaultCertificateRequest.builder().commonName("hello.com").build(); assertThat(request.getCommonName()).isEqualTo("hello.com"); } @@ -60,4 +59,5 @@ class VaultCertificateRequestUnitTests { assertThat(request.isExcludeCommonNameFromSubjectAltNames()).isTrue(); assertThat(request.getCommonName()).isEqualTo("hello.com"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTokenRequestUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTokenRequestUnitTests.java index a93bab29..7b0efc22 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTokenRequestUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTokenRequestUnitTests.java @@ -41,8 +41,8 @@ class VaultTokenRequestUnitTests { @Test void shouldBuildRequestWithMeta() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .meta(Collections.singletonMap("key", "value")).build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().meta(Collections.singletonMap("key", "value")) + .build(); assertThat(tokenRequest.getMeta()).containsEntry("key", "value"); } @@ -50,8 +50,7 @@ class VaultTokenRequestUnitTests { @Test void shouldBuildRequestWithPolicies() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder().withPolicy("foo") - .build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().withPolicy("foo").build(); assertThat(tokenRequest.getPolicies()).containsOnly("foo"); } @@ -59,11 +58,11 @@ class VaultTokenRequestUnitTests { @Test void shouldRequestWithDuration() { - VaultTokenRequest tokenRequest = VaultTokenRequest.builder() - .ttl(Duration.ofSeconds(10)).explicitMaxTtl(Duration.ofSeconds(20)) - .build(); + VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(10)) + .explicitMaxTtl(Duration.ofSeconds(20)).build(); assertThat(tokenRequest.getTtl()).isEqualTo("10s"); assertThat(tokenRequest.getExplicitMaxTtl()).isEqualTo("20s"); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTransitContextUnitTests.java b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTransitContextUnitTests.java index 5125e413..063b9faf 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTransitContextUnitTests.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/support/VaultTransitContextUnitTests.java @@ -29,8 +29,7 @@ class VaultTransitContextUnitTests { @Test void rejectsNullContext() { - assertThatIllegalArgumentException() - .isThrownBy(() -> VaultTransitContext.fromContext(null)); + assertThatIllegalArgumentException().isThrownBy(() -> VaultTransitContext.fromContext(null)); } @Test @@ -46,8 +45,7 @@ class VaultTransitContextUnitTests { @Test void rejectsNullNonce() { - assertThatIllegalArgumentException() - .isThrownBy(() -> VaultTransitContext.fromNonce(null)); + assertThatIllegalArgumentException().isThrownBy(() -> VaultTransitContext.fromNonce(null)); } @Test @@ -60,4 +58,5 @@ class VaultTransitContextUnitTests { assertThat(context.getNonce()).isEqualTo(bytes); assertThat(context.getContext()).isEmpty(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/CanConnect.java b/spring-vault-core/src/test/java/org/springframework/vault/util/CanConnect.java index 5bcc2d4e..6aceccc1 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/CanConnect.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/CanConnect.java @@ -31,7 +31,6 @@ class CanConnect { /** * Performs a check whether a connection can be established to the * {@code socketAddress}. - * * @param socketAddress the address to test, must not be {@literal null}. * @return {@literal true}, if a connection can be established */ @@ -54,4 +53,5 @@ class CanConnect { } } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/IntegrationTestSupport.java b/spring-vault-core/src/test/java/org/springframework/vault/util/IntegrationTestSupport.java index 39062cc4..7236da1e 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/IntegrationTestSupport.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/IntegrationTestSupport.java @@ -28,6 +28,7 @@ public abstract class IntegrationTestSupport { private final VaultInitializer initializer = new VaultInitializer(); protected final PrepareVault prepare() { - return initializer.prepare(); + return this.initializer.prepare(); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/PrepareVault.java b/spring-vault-core/src/test/java/org/springframework/vault/util/PrepareVault.java index a2194bb4..d7588874 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/PrepareVault.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/PrepareVault.java @@ -52,13 +52,11 @@ public class PrepareVault { /** * Create a new {@link PrepareVault} object. - * * @param webClient must not be {@literal null}. * @param restTemplate must not be {@literal null}. * @param vaultOperations must not be {@literal null}. */ - public PrepareVault(WebClient webClient, RestTemplate restTemplate, - VaultOperations vaultOperations) { + public PrepareVault(WebClient webClient, RestTemplate restTemplate, VaultOperations vaultOperations) { this.webClient = webClient; this.restTemplate = restTemplate; @@ -68,7 +66,6 @@ public class PrepareVault { /** * Initialize Vault and unseal the vault. - * * @return the root token. */ public VaultToken initializeVault() { @@ -76,13 +73,12 @@ public class PrepareVault { int createKeys = 2; int requiredKeys = 2; - VaultInitializationResponse initialized = vaultOperations.opsForSys() + VaultInitializationResponse initialized = this.vaultOperations.opsForSys() .initialize(VaultInitializationRequest.create(createKeys, requiredKeys)); for (int i = 0; i < requiredKeys; i++) { - VaultUnsealStatus unsealStatus = vaultOperations.opsForSys() - .unseal(initialized.getKeys().get(i)); + VaultUnsealStatus unsealStatus = this.vaultOperations.opsForSys().unseal(initialized.getKeys().get(i)); if (!unsealStatus.isSealed()) { break; @@ -94,7 +90,6 @@ public class PrepareVault { /** * Create a token for the given {@code tokenId} and {@code policy}. - * * @param tokenId must not be {@literal null}. * @param policy must not be {@literal null}. * @return the created {@link VaultToken}. @@ -107,35 +102,31 @@ public class PrepareVault { builder.withPolicy(policy); } - VaultTokenResponse vaultTokenResponse = vaultOperations.opsForToken() - .create(builder.build()); + VaultTokenResponse vaultTokenResponse = this.vaultOperations.opsForToken().create(builder.build()); return vaultTokenResponse.getToken(); } /** * Check whether Vault is available (vault created and unsealed). - * * @return {@literal true} if Vault is available (vault created and unsealed). */ public boolean isAvailable() { - return adminOperations.isInitialized() && !adminOperations.health().isSealed(); + return this.adminOperations.isInitialized() && !this.adminOperations.health().isSealed(); } /** * Mount an auth backend. - * * @param authBackend must not be {@literal null} or empty. */ public void mountAuth(String authBackend) { Assert.hasText(authBackend, "AuthBackend must not be empty"); - adminOperations.authMount(authBackend, VaultMount.create(authBackend)); + this.adminOperations.authMount(authBackend, VaultMount.create(authBackend)); } /** * Check whether a auth-backend is enabled. - * * @param authBackend must not be {@literal null} or empty. * @return {@literal true} if a auth-backend is enabled. */ @@ -143,12 +134,11 @@ public class PrepareVault { Assert.hasText(authBackend, "AuthBackend must not be empty"); - return adminOperations.getAuthMounts().containsKey(authBackend + "/"); + return this.adminOperations.getAuthMounts().containsKey(authBackend + "/"); } /** * Mount an secret backend. - * * @param secretBackend must not be {@literal null} or empty. */ public void mountSecret(String secretBackend) { @@ -157,33 +147,29 @@ public class PrepareVault { /** * Mount an secret backend {@code secretBackend} at {@code path}. - * * @param secretBackend must not be {@literal null} or empty. * @param path must not be {@literal null} or empty. * @param config must not be {@literal null}. */ - private void mountSecret(String secretBackend, String path, - Map<String, Object> config) { + private void mountSecret(String secretBackend, String path, Map<String, Object> config) { Assert.hasText(secretBackend, "SecretBackend must not be empty"); Assert.hasText(path, "Mount path must not be empty"); Assert.notNull(config, "Configuration must not be null"); - VaultMount mount = VaultMount.builder().type(secretBackend).config(config) - .build(); - adminOperations.mount(path, mount); + VaultMount mount = VaultMount.builder().type(secretBackend).config(config).build(); + this.adminOperations.mount(path, mount); } /** * Check whether a auth-backend is enabled. - * * @param secretBackend must not be {@literal null} or empty. * @return {@literal true} if a auth-backend is enabled. */ public boolean hasSecret(String secretBackend) { Assert.hasText(secretBackend, "SecretBackend must not be empty"); - return adminOperations.getMounts().containsKey(secretBackend + "/"); + return this.adminOperations.getMounts().containsKey(secretBackend + "/"); } /** @@ -214,29 +200,29 @@ public class PrepareVault { */ public void disableGenericVersioning() { - vaultOperations.opsForSys().unmount("secret"); + this.vaultOperations.opsForSys().unmount("secret"); - VaultMount kv = VaultMount.builder().type("kv") - .config(Collections.singletonMap("versioned", false)).build(); - vaultOperations.opsForSys().mount("secret", kv); + VaultMount kv = VaultMount.builder().type("kv").config(Collections.singletonMap("versioned", false)).build(); + this.vaultOperations.opsForSys().mount("secret", kv); } public void mountVersionedKvBackend() { mountSecret("kv", "versioned", Collections.emptyMap()); - vaultOperations.write("sys/mounts/versioned/tune", Collections - .singletonMap("options", Collections.singletonMap("version", "2"))); + this.vaultOperations.write("sys/mounts/versioned/tune", + Collections.singletonMap("options", Collections.singletonMap("version", "2"))); } public VaultOperations getVaultOperations() { - return vaultOperations; + return this.vaultOperations; } public RestTemplate getRestTemplate() { - return restTemplate; + return this.restTemplate; } public WebClient getWebClient() { - return webClient; + return this.webClient; } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/RequiresVaultVersion.java b/spring-vault-core/src/test/java/org/springframework/vault/util/RequiresVaultVersion.java index a47606ea..cee4dc6c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/RequiresVaultVersion.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/RequiresVaultVersion.java @@ -51,4 +51,5 @@ public @interface RequiresVaultVersion { * Minimum version to run a test. */ String value(); + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/Settings.java b/spring-vault-core/src/test/java/org/springframework/vault/util/Settings.java index e1d27b55..f157e488 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/Settings.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/Settings.java @@ -35,8 +35,7 @@ public class Settings { File workDir = findWorkDir(); - return SslConfiguration.forTrustStore( - new FileSystemResource(new File(workDir, "keystore.jks")), + return SslConfiguration.forTrustStore(new FileSystemResource(new File(workDir, "keystore.jks")), "changeit".toCharArray()); } @@ -59,8 +58,7 @@ public class Settings { public static File findWorkDir(File directory) { File searchLevel = directory; - while (searchLevel.getParentFile() != null - && searchLevel.getParentFile() != searchLevel) { + while (searchLevel.getParentFile() != null && searchLevel.getParentFile() != searchLevel) { File work = new File(searchLevel, "work"); if (work.isDirectory() && work.exists()) { @@ -70,8 +68,7 @@ public class Settings { searchLevel = searchLevel.getParentFile(); } - throw new IllegalStateException(String.format( - "Cannot find work directory in %s or any parent directories", + throw new IllegalStateException(String.format("Cannot find work directory in %s or any parent directories", directory.getAbsoluteFile())); } @@ -79,8 +76,7 @@ public class Settings { * @return the token to use during tests. */ public static VaultToken token() { - return VaultToken.of( - System.getProperty("vault.token", "00000000-0000-0000-0000-000000000000") - .toCharArray()); + return VaultToken.of(System.getProperty("vault.token", "00000000-0000-0000-0000-000000000000").toCharArray()); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/TestRestTemplateFactory.java b/spring-vault-core/src/test/java/org/springframework/vault/util/TestRestTemplateFactory.java index 2fb1b3c7..89aea2d2 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/TestRestTemplateFactory.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/TestRestTemplateFactory.java @@ -47,7 +47,6 @@ public class TestRestTemplateFactory { * underlying {@link ClientHttpRequestFactory} is cached. See * {@link #create(ClientHttpRequestFactory)} to create {@link RestTemplate} for a * given {@link ClientHttpRequestFactory}. - * * @param sslConfiguration must not be {@literal null}. * @return */ @@ -70,7 +69,6 @@ public class TestRestTemplateFactory { * {@link org.springframework.web.client.HttpStatusCodeException exceptions} in error * cases and behave in that aspect like the regular * {@link org.springframework.web.client.RestTemplate}. - * * @param requestFactory must not be {@literal null}. * @return */ @@ -81,8 +79,7 @@ public class TestRestTemplateFactory { return VaultClients.createRestTemplate(TEST_VAULT_ENDPOINT, requestFactory); } - private static void initializeClientHttpRequestFactory( - SslConfiguration sslConfiguration) throws Exception { + private static void initializeClientHttpRequestFactory(SslConfiguration sslConfiguration) throws Exception { if (factoryCache.get() != null) { return; @@ -99,20 +96,20 @@ public class TestRestTemplateFactory { if (clientHttpRequestFactory instanceof DisposableBean) { - Runtime.getRuntime().addShutdownHook( - new Thread("ClientHttpRequestFactory Shutdown Hook") { + Runtime.getRuntime().addShutdownHook(new Thread("ClientHttpRequestFactory Shutdown Hook") { - @Override - public void run() { - try { - ((DisposableBean) clientHttpRequestFactory).destroy(); - } - catch (Exception e) { - e.printStackTrace(); - } - } - }); + @Override + public void run() { + try { + ((DisposableBean) clientHttpRequestFactory).destroy(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + }); } } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/TestWebClientFactory.java b/spring-vault-core/src/test/java/org/springframework/vault/util/TestWebClientFactory.java index 5b926a1d..6ce4aba0 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/TestWebClientFactory.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/TestWebClientFactory.java @@ -35,7 +35,6 @@ public class TestWebClientFactory { * Create a new {@link WebClient} using the {@link SslConfiguration}. See * {@link ReactiveVaultClients#createWebClient(VaultEndpoint, ClientHttpConnector)} to * create {@link WebClient} for a given {@link ClientHttpConnector}. - * * @param sslConfiguration must not be {@literal null}. * @return */ @@ -44,12 +43,12 @@ public class TestWebClientFactory { Assert.notNull(sslConfiguration, "SslConfiguration must not be null!"); try { - ClientHttpConnector connector = ClientHttpConnectorFactory - .create(new ClientOptions(), sslConfiguration); + ClientHttpConnector connector = ClientHttpConnectorFactory.create(new ClientOptions(), sslConfiguration); return ReactiveVaultClients.createWebClient(TEST_VAULT_ENDPOINT, connector); } catch (Exception e) { throw new IllegalStateException(e); } } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultExtension.java b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultExtension.java index 8353d665..b306231c 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultExtension.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultExtension.java @@ -30,8 +30,7 @@ import org.junit.jupiter.api.extension.ParameterResolver; */ public class VaultExtension implements BeforeAllCallback, ParameterResolver { - private static final ExtensionContext.Namespace VAULT = ExtensionContext.Namespace - .create("vault.initializer"); + private static final ExtensionContext.Namespace VAULT = ExtensionContext.Namespace.create("vault.initializer"); @Override public void beforeAll(ExtensionContext extensionContext) throws Exception { @@ -41,21 +40,20 @@ public class VaultExtension implements BeforeAllCallback, ParameterResolver { } @Override - public boolean supportsParameter(ParameterContext parameterContext, - ExtensionContext extensionContext) throws ParameterResolutionException { - return parameterContext.getParameter().getType() - .isAssignableFrom(VaultInitializer.class); + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return parameterContext.getParameter().getType().isAssignableFrom(VaultInitializer.class); } @Override - public Object resolveParameter(ParameterContext parameterContext, - ExtensionContext extensionContext) throws ParameterResolutionException { + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { return getInitializer(extensionContext); } private VaultInitializer getInitializer(ExtensionContext extensionContext) { ExtensionContext.Store store = extensionContext.getStore(VAULT); - return store.getOrComputeIfAbsent(VaultInitializer.class, - k -> new VaultInitializer(), VaultInitializer.class); + return store.getOrComputeIfAbsent(VaultInitializer.class, k -> new VaultInitializer(), VaultInitializer.class); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultInitializer.java b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultInitializer.java index bd9d2496..8ac40132 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultInitializer.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultInitializer.java @@ -40,8 +40,7 @@ public class VaultInitializer { public static final String VERSIONING_INTRODUCED_WITH_VALUE = "0.10.0"; - private static final Version VERSIONING_INTRODUCED_WITH = Version - .parse(VERSIONING_INTRODUCED_WITH_VALUE); + private static final Version VERSIONING_INTRODUCED_WITH = Version.parse(VERSIONING_INTRODUCED_WITH_VALUE); private final VaultEndpoint vaultEndpoint; @@ -62,12 +61,10 @@ public class VaultInitializer { /** * Create a new {@link VaultInitializer} with the given {@link SslConfiguration} and * {@link VaultEndpoint}. - * * @param sslConfiguration must not be {@literal null}. * @param vaultEndpoint must not be {@literal null}. */ - public VaultInitializer(SslConfiguration sslConfiguration, - VaultEndpoint vaultEndpoint) { + public VaultInitializer(SslConfiguration sslConfiguration, VaultEndpoint vaultEndpoint) { Assert.notNull(sslConfiguration, "SslConfiguration must not be null"); Assert.notNull(vaultEndpoint, "VaultEndpoint must not be null"); @@ -75,14 +72,13 @@ public class VaultInitializer { RestTemplate restTemplate = TestRestTemplateFactory.create(sslConfiguration); WebClient webClient = TestWebClientFactory.create(sslConfiguration); - VaultTemplate vaultTemplate = new VaultTemplate( - TestRestTemplateFactory.TEST_VAULT_ENDPOINT, + VaultTemplate vaultTemplate = new VaultTemplate(TestRestTemplateFactory.TEST_VAULT_ENDPOINT, restTemplate.getRequestFactory(), new PreparingSessionManager()); this.token = Settings.token(); - this.prepareVault = new PrepareVault(webClient, - TestRestTemplateFactory.create(sslConfiguration), vaultTemplate); + this.prepareVault = new PrepareVault(webClient, TestRestTemplateFactory.create(sslConfiguration), + vaultTemplate); this.vaultEndpoint = vaultEndpoint; } @@ -91,11 +87,10 @@ public class VaultInitializer { assertRunningVault(); if (!this.prepareVault.isAvailable()) { - this.token = prepareVault.initializeVault(); + this.token = this.prepareVault.initializeVault(); this.prepareVault.createToken(Settings.token().getToken(), "root"); - if (this.prepareVault.getVersion() - .isGreaterThanOrEqualTo(VERSIONING_INTRODUCED_WITH)) { + if (this.prepareVault.getVersion().isGreaterThanOrEqualTo(VERSIONING_INTRODUCED_WITH)) { this.prepareVault.disableGenericVersioning(); this.prepareVault.mountVersionedKvBackend(); } @@ -106,13 +101,12 @@ public class VaultInitializer { try (Socket socket = new Socket()) { - socket.connect(new InetSocketAddress(InetAddress.getByName("localhost"), - vaultEndpoint.getPort())); + socket.connect(new InetSocketAddress(InetAddress.getByName("localhost"), this.vaultEndpoint.getPort())); } catch (Exception ex) { - throw new IllegalStateException(String.format( - "Vault is not running on localhost:%d which is required to run a test using @Rule %s", - vaultEndpoint.getPort(), getClass().getSimpleName())); + throw new IllegalStateException( + String.format("Vault is not running on localhost:%d which is required to run a test using @Rule %s", + this.vaultEndpoint.getPort(), getClass().getSimpleName())); } } @@ -120,14 +114,16 @@ public class VaultInitializer { * @return the {@link PrepareVault} object. */ public PrepareVault prepare() { - return prepareVault; + return this.prepareVault; } private class PreparingSessionManager implements SessionManager { @Override public VaultToken getSessionToken() { - return token; + return VaultInitializer.this.token; } + } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultVersionExtension.java b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultVersionExtension.java index d415ffee..5a467aa1 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/VaultVersionExtension.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/VaultVersionExtension.java @@ -32,18 +32,16 @@ import org.junit.platform.commons.util.AnnotationUtils; */ class VaultVersionExtension implements ExecutionCondition { - private static final ExtensionContext.Namespace VAULT = ExtensionContext.Namespace - .create("vault.version"); + private static final ExtensionContext.Namespace VAULT = ExtensionContext.Namespace.create("vault.version"); private static final ConditionEvaluationResult ENABLED_BY_DEFAULT = ConditionEvaluationResult .enabled("@VaultVersion is not present"); @Override - public ConditionEvaluationResult evaluateExecutionCondition( - ExtensionContext context) { + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { - Optional<RequiresVaultVersion> optional = AnnotationUtils - .findAnnotation(context.getElement(), RequiresVaultVersion.class); + Optional<RequiresVaultVersion> optional = AnnotationUtils.findAnnotation(context.getElement(), + RequiresVaultVersion.class); if (!optional.isPresent()) { return ENABLED_BY_DEFAULT; @@ -51,26 +49,24 @@ class VaultVersionExtension implements ExecutionCondition { ExtensionContext.Store store = context.getStore(VAULT); - Version runningVersion = store.getOrComputeIfAbsent(Version.class, - versionClass -> { + Version runningVersion = store.getOrComputeIfAbsent(Version.class, versionClass -> { - VaultInitializer initializer = new VaultInitializer(); - initializer.initialize(); - return initializer.prepare().getVersion(); - }, Version.class); + VaultInitializer initializer = new VaultInitializer(); + initializer.initialize(); + return initializer.prepare().getVersion(); + }, Version.class); RequiresVaultVersion requiredVersion = optional.get(); Version required = Version.parse(requiredVersion.value()); if (runningVersion.isGreaterThanOrEqualTo(required)) { - return ConditionEvaluationResult.enabled(String.format( - "@VaultVersion check passed current Vault version is %s", - runningVersion)); + return ConditionEvaluationResult + .enabled(String.format("@VaultVersion check passed current Vault version is %s", runningVersion)); } return ConditionEvaluationResult.disabled(String.format( - "@VaultVersion requires since version %s, current Vault version is %s", - required, runningVersion)); + "@VaultVersion requires since version %s, current Vault version is %s", required, runningVersion)); } + } diff --git a/spring-vault-core/src/test/java/org/springframework/vault/util/Version.java b/spring-vault-core/src/test/java/org/springframework/vault/util/Version.java index 7bc7c408..f9043659 100644 --- a/spring-vault-core/src/test/java/org/springframework/vault/util/Version.java +++ b/spring-vault-core/src/test/java/org/springframework/vault/util/Version.java @@ -44,14 +44,12 @@ public class Version implements Comparable<Version> { /** * Creates a new {@link Version} from the given integer values. At least one value has * to be given but a maximum of 4. - * * @param parts must not be {@literal null} or empty. */ private Version(boolean enterprise, int... parts) { Assert.notNull(parts, "Parts must not be null"); - Assert.isTrue(parts.length > 0 && parts.length < 5, - "Parts must contain one to four segments"); + Assert.isTrue(parts.length > 0 && parts.length < 5, "Parts must contain one to four segments"); this.major = parts[0]; this.minor = parts.length > 1 ? parts[1] : 0; @@ -59,15 +57,14 @@ public class Version implements Comparable<Version> { this.build = parts.length > 3 ? parts[3] : 0; this.enterprise = enterprise; - Assert.isTrue(major >= 0, "Major version must be greater or equal zero!"); - Assert.isTrue(minor >= 0, "Minor version must be greater or equal zero!"); - Assert.isTrue(bugfix >= 0, "Bugfix version must be greater or equal zero!"); - Assert.isTrue(build >= 0, "Build version must be greater or equal zero!"); + Assert.isTrue(this.major >= 0, "Major version must be greater or equal zero!"); + Assert.isTrue(this.minor >= 0, "Minor version must be greater or equal zero!"); + Assert.isTrue(this.bugfix >= 0, "Bugfix version must be greater or equal zero!"); + Assert.isTrue(this.build >= 0, "Build version must be greater or equal zero!"); } /** * Parses the given string representation of a version into a {@link Version} object. - * * @param version must not be {@literal null} or empty. * @return */ @@ -81,16 +78,14 @@ public class Version implements Comparable<Version> { for (int i = 0; i < parts.length; i++) { - String input = i == parts.length - 1 ? parts[i].replaceAll("\\D.*", "") - : parts[i]; + String input = i == parts.length - 1 ? parts[i].replaceAll("\\D.*", "") : parts[i]; if (StringUtils.hasText(input)) { try { intParts[i] = Integer.parseInt(input); } catch (IllegalArgumentException o_O) { - throw new IllegalArgumentException( - String.format(VERSION_PARSE_ERROR, input, version), o_O); + throw new IllegalArgumentException(String.format(VERSION_PARSE_ERROR, input, version), o_O); } } } @@ -100,7 +95,6 @@ public class Version implements Comparable<Version> { /** * Returns whether the current {@link Version} is greater (newer) than the given one. - * * @param version * @return */ @@ -111,7 +105,6 @@ public class Version implements Comparable<Version> { /** * Returns whether the current {@link Version} is greater (newer) or the same as the * given one. - * * @param version * @return */ @@ -121,7 +114,6 @@ public class Version implements Comparable<Version> { /** * Returns whether the current {@link Version} is the same as the given one. - * * @param version * @return */ @@ -131,7 +123,6 @@ public class Version implements Comparable<Version> { /** * Returns whether the current {@link Version} is less (older) than the given one. - * * @param version * @return */ @@ -142,7 +133,6 @@ public class Version implements Comparable<Version> { /** * Returns whether the current {@link Version} is less (older) or equal to the current * one. - * * @param version * @return */ @@ -161,27 +151,27 @@ public class Version implements Comparable<Version> { return 1; } - if (major != that.major) { - return major - that.major; + if (this.major != that.major) { + return this.major - that.major; } - if (minor != that.minor) { - return minor - that.minor; + if (this.minor != that.minor) { + return this.minor - that.minor; } - if (bugfix != that.bugfix) { - return bugfix - that.bugfix; + if (this.bugfix != that.bugfix) { + return this.bugfix - that.bugfix; } - if (build != that.build) { - return build - that.build; + if (this.build != that.build) { + return this.build - that.build; } return 0; } public boolean isEnterprise() { - return enterprise; + return this.enterprise; } /* @@ -193,19 +183,18 @@ public class Version implements Comparable<Version> { public String toString() { List<Integer> digits = new ArrayList<Integer>(); - digits.add(major); - digits.add(minor); + digits.add(this.major); + digits.add(this.minor); - if (build != 0 || bugfix != 0) { - digits.add(bugfix); + if (this.build != 0 || this.bugfix != 0) { + digits.add(this.bugfix); } - if (build != 0) { - digits.add(build); + if (this.build != 0) { + digits.add(this.build); } - return StringUtils.collectionToDelimitedString(digits, ".") - + (isEnterprise() ? "+ent" : ""); + return StringUtils.collectionToDelimitedString(digits, ".") + (isEnterprise() ? "+ent" : ""); } @Override @@ -215,13 +204,13 @@ public class Version implements Comparable<Version> { if (!(o instanceof Version)) return false; Version version = (Version) o; - return major == version.major && minor == version.minor - && bugfix == version.bugfix && build == version.build - && enterprise == version.enterprise; + return this.major == version.major && this.minor == version.minor && this.bugfix == version.bugfix + && this.build == version.build && this.enterprise == version.enterprise; } @Override public int hashCode() { - return Objects.hash(major, minor, bugfix, build, enterprise); + return Objects.hash(this.major, this.minor, this.bugfix, this.build, this.enterprise); } + }