Skip to content

Commit

Permalink
Update code to use recent language features.
Browse files Browse the repository at this point in the history
Closes #881
  • Loading branch information
mp911de committed Aug 20, 2024
1 parent a140b5c commit 1cdaa49
Show file tree
Hide file tree
Showing 114 changed files with 533 additions and 614 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/
package org.springframework.vault.authentication;

import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.*;
import static org.springframework.vault.authentication.AuthenticationUtil.*;

import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -43,9 +46,6 @@
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;

import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.*;
import static org.springframework.vault.authentication.AuthenticationUtil.*;

/**
* AppRole implementation of {@link ClientAuthentication}. RoleId and SecretId (optional)
* are sent in the login request to Vault to obtain a {@link VaultToken}.
Expand Down Expand Up @@ -217,8 +217,8 @@ private String getRoleId(RoleId roleId) throws VaultLoginException {
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("Cannot get Role id using AppRole: %s"
.formatted(VaultResponses.getError(e.getResponseBodyAsString())), e);
}
}

Expand All @@ -236,8 +236,8 @@ private String getRoleId(RoleId roleId) throws VaultLoginException {
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("Cannot unwrap Role id using AppRole: %s"
.formatted(VaultResponses.getError(e.getResponseBodyAsString())), e);
}
}

Expand All @@ -260,8 +260,8 @@ private String getSecretId(SecretId secretId) throws VaultLoginException {
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("Cannot get Secret id using AppRole: %s"
.formatted(VaultResponses.getError(e.getResponseBodyAsString())), e);
}
}

Expand All @@ -280,8 +280,8 @@ private String getSecretId(SecretId secretId) throws VaultLoginException {
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("Cannot unwrap Role id using AppRole: %s"
.formatted(VaultResponses.getError(e.getResponseBodyAsString())), e);
}
}

Expand Down Expand Up @@ -331,11 +331,11 @@ private static Map<String, String> getAppRoleLoginBody(String roleId, @Nullable
}

private static String getSecretIdPath(AppRoleAuthenticationOptions options) {
return String.format("auth/%s/role/%s/secret-id", options.getPath(), options.getAppRole());
return "auth/%s/role/%s/secret-id".formatted(options.getPath(), options.getAppRole());
}

private static String getRoleIdIdPath(AppRoleAuthenticationOptions options) {
return String.format("auth/%s/role/%s/role-id", options.getPath(), options.getAppRole());
return "auth/%s/role/%s/role-id".formatted(options.getPath(), options.getAppRole());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ public static class HttpRequest<T> {

@Override
public String toString() {
return String.format("%s %s AS %s", getMethod(), getUri() != null ? getUri() : getUriTemplate(),
return "%s %s AS %s".formatted(getMethod(), getUri() != null ? getUri() : getUriTemplate(),
getResponseType());
}

Expand Down Expand Up @@ -529,9 +529,8 @@ public Node<?> getPrevious() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof HttpRequestNode))
if (!(o instanceof HttpRequestNode<?> that))
return false;
HttpRequestNode<?> that = (HttpRequestNode<?>) o;
return this.definition.equals(that.definition) && this.previous.equals(that.previous);
}

Expand Down Expand Up @@ -574,9 +573,8 @@ public Node<?> getPrevious() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MapStep))
if (!(o instanceof MapStep<?, ?> mapStep))
return false;
MapStep<?, ?> mapStep = (MapStep<?, ?>) o;
return this.mapper.equals(mapStep.mapper) && this.previous.equals(mapStep.previous);
}

Expand Down Expand Up @@ -620,9 +618,8 @@ public List<Node<?>> getRight() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ZipStep))
if (!(o instanceof ZipStep<?, ?> zipStep))
return false;
ZipStep<?, ?> zipStep = (ZipStep<?, ?>) o;
return this.left.equals(zipStep.left) && this.right.equals(zipStep.right);
}

Expand Down Expand Up @@ -666,9 +663,8 @@ public AuthenticationSteps.Node<?> getPrevious() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OnNextStep))
if (!(o instanceof OnNextStep<?> that))
return false;
OnNextStep<?> that = (OnNextStep<?>) o;
return this.consumer.equals(that.consumer) && this.previous.equals(that.previous);
}

Expand Down Expand Up @@ -707,9 +703,8 @@ public Node<?> getPrevious() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ScalarValueStep))
if (!(o instanceof ScalarValueStep<?> that))
return false;
ScalarValueStep<?> that = (ScalarValueStep<?>) o;
return this.value.equals(that.value) && this.previous.equals(that.previous);
}

Expand Down Expand Up @@ -752,9 +747,8 @@ public Node<?> getPrevious() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SupplierStep))
if (!(o instanceof SupplierStep<?> that))
return false;
SupplierStep<?> that = (SupplierStep<?>) o;
return this.supplier.equals(that.supplier) && this.previous.equals(that.previous);
}

Expand Down Expand Up @@ -819,9 +813,8 @@ public R getRight() {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Pair))
if (!(o instanceof Pair<?, ?> pair))
return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return this.left.equals(pair.left) && this.right.equals(pair.right);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,14 @@ public VaultToken login() throws VaultException {
return (VaultToken) state;
}

if (state instanceof VaultResponse) {
if (state instanceof VaultResponse response) {

VaultResponse response = (VaultResponse) state;
Assert.state(response.getAuth() != null, "Auth field must not be null");
return LoginTokenUtil.from(response.getAuth());
}

throw new IllegalStateException(
String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", state));
"Cannot retrieve VaultToken from authentication chain. Got instead %s".formatted(state));
}

@SuppressWarnings({ "unchecked", "ConstantConditions" })
Expand All @@ -101,7 +100,7 @@ private Object evaluate(Iterable<Node<?>> steps) {
for (Node<?> o : steps) {

if (logger.isDebugEnabled()) {
logger.debug(String.format("Executing %s with current state %s", o, state));
logger.debug("Executing %s with current state %s".formatted(o, state));
}

try {
Expand Down Expand Up @@ -130,17 +129,15 @@ private Object evaluate(Iterable<Node<?>> steps) {
}

if (logger.isDebugEnabled()) {
logger.debug(String.format("Executed %s with current state %s", o, state));
logger.debug("Executed %s with current state %s".formatted(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.getStatusCode().value(), VaultResponses.getError(e.getResponseBodyAsString())),
e);
throw new VaultLoginException("HTTP request %s in state %s failed with Status %s and body %s".formatted(
o, state, e.getStatusCode().value(), VaultResponses.getError(e.getResponseBodyAsString())), e);
}
catch (RuntimeException e) {
throw new VaultLoginException(String.format("Authentication execution failed in %s", o), e);
throw new VaultLoginException("Authentication execution failed in %s".formatted(o), e);
}
}
return state;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.vault.VaultException;
import org.springframework.vault.authentication.AuthenticationSteps.HttpRequest;
Expand Down Expand Up @@ -102,17 +100,15 @@ public Mono<VaultToken> getVaultToken() throws VaultException {
return (VaultToken) stateObject;
}

if (stateObject instanceof VaultResponse) {

VaultResponse response = (VaultResponse) stateObject;
if (stateObject instanceof VaultResponse response) {

Assert.state(response.getAuth() != null, "Auth field must not be null");

return LoginTokenUtil.from(response.getAuth());
}

throw new IllegalStateException(
String.format("Cannot retrieve VaultToken from authentication chain. Got instead %s", stateObject));
"Cannot retrieve VaultToken from authentication chain. Got instead %s".formatted(stateObject));
}).onErrorMap(t -> new VaultLoginException("Cannot retrieve VaultToken from authentication chain", t));
}

Expand All @@ -124,7 +120,7 @@ private Mono<Object> createMono(Iterable<Node<?>> steps) {
for (Node<?> o : steps) {

if (logger.isDebugEnabled()) {
logger.debug(String.format("Executing %s with current state %s", o, state));
logger.debug("Executing %s with current state %s".formatted(o, state));
}

if (o instanceof HttpRequestNode) {
Expand Down Expand Up @@ -153,7 +149,7 @@ private Mono<Object> createMono(Iterable<Node<?>> steps) {
}

if (logger.isDebugEnabled()) {
logger.debug(String.format("Executed %s with current state %s", o, state));
logger.debug("Executed %s with current state %s".formatted(o, state));
}
}
return state;
Expand Down Expand Up @@ -205,20 +201,18 @@ private Mono<Object> doSupplierStepLater(SupplierStep<Object> supplierStep) {

Supplier<?> supplier = supplierStep.getSupplier();

if (!(supplier instanceof ResourceCredentialSupplier)) {
if (!(supplier instanceof ResourceCredentialSupplier resourceSupplier)) {
return Mono.fromSupplier(supplierStep.getSupplier()).subscribeOn(Schedulers.boundedElastic());
}

ResourceCredentialSupplier resourceSupplier = (ResourceCredentialSupplier) supplier;

return DataBufferUtils.join(DataBufferUtils.read(resourceSupplier.getResource(), this.factory, 4096))
.map(dataBuffer -> {
String result = dataBuffer.toString(ResourceCredentialSupplier.CHARSET);
DataBufferUtils.release(dataBuffer);
return (Object) result;
})
.onErrorMap(IOException.class, e -> new VaultException(
String.format("Credential retrieval from %s failed", resourceSupplier.getResource()), e));
"Credential retrieval from %s failed".formatted(resourceSupplier.getResource()), e));
}

enum Undefinded {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ abstract class AuthenticationUtil {
* @return
*/
static String getLoginPath(String authMount) {
return String.format("auth/%s/login", authMount);
return "auth/%s/login".formatted(authMount);
}

private AuthenticationUtil() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ private VaultToken createTokenUsingAwsEc2() {

if (response.getAuth().get("metadata") instanceof Map) {
Map<Object, Object> metadata = (Map<Object, Object>) 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")));
logger.debug("Login successful using AWS-EC2 authentication for instance %s, AMI %s"
.formatted(metadata.get("instance_id"), metadata.get("instance_id")));
}
else {
logger.debug("Login successful using AWS-EC2 authentication");
Expand Down Expand Up @@ -240,7 +240,7 @@ protected Map<String, String> getEc2Login() {
}
catch (RestClientException e) {
throw new VaultLoginException(
String.format("Cannot obtain Identity Document from %s", this.options.getIdentityDocumentUri()), e);
"Cannot obtain Identity Document from %s".formatted(this.options.getIdentityDocumentUri()), e);
}
}

Expand All @@ -260,7 +260,7 @@ private String createIMDSv2Token() {
}
catch (RestClientException e) {
throw new VaultLoginException(
String.format("Cannot obtain IMDSv2 Token from %s", this.options.getMetadataTokenRequestUri()), e);
"Cannot obtain IMDSv2 Token from %s".formatted(this.options.getMetadataTokenRequestUri()), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ private VaultToken createTokenUsingAwsIam() {

if (response.getAuth().get("metadata") instanceof Map) {
Map<Object, Object> metadata = (Map<Object, Object>) 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")));
logger.debug("Login successful using AWS-IAM authentication for user id %s, ARN %s"
.formatted(metadata.get("client_user_id"), metadata.get("canonical_arn")));
}
else {
logger.debug("Login successful using AWS-IAM authentication");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package org.springframework.vault.authentication;

import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.*;

import java.util.Map;

import org.apache.commons.logging.Log;
Expand All @@ -33,8 +35,6 @@
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;

import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.method;

/**
* Cubbyhole {@link ClientAuthentication} implementation.
* <p>
Expand Down Expand Up @@ -225,9 +225,7 @@ private boolean shouldEnhanceTokenWithSelfLookup(VaultToken token) {
return false;
}

if (token instanceof LoginToken) {

LoginToken loginToken = (LoginToken) token;
if (token instanceof LoginToken loginToken) {

if (loginToken.getLeaseDuration().isZero()) {
return false;
Expand Down Expand Up @@ -273,17 +271,17 @@ private static VaultToken getToken(CubbyholeAuthenticationOptions options, Vault
Map<String, Object> 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()));
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token"
.formatted(options.getPath()));
}

if (data.size() == 1) {
String token = (String) data.get(data.keySet().iterator().next());
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(
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token".formatted(url));
}

}
Loading

0 comments on commit 1cdaa49

Please sign in to comment.