From 208f499e8b060106f4ec0432134c15dbfe4a484a Mon Sep 17 00:00:00 2001 From: Luca Bassi Date: Thu, 31 Oct 2024 15:45:45 +0100 Subject: [PATCH] Fix sonar issues --- .../ErrorPageAuthenticationEntryPoint.java | 4 +- .../storm/webdav/authn/PrincipalHelper.java | 6 +- .../authz/VOMSAuthenticationFilter.java | 4 +- .../authz/VOMSPreAuthDetailsSource.java | 2 +- .../authz/pdp/LocalAuthorizationPdp.java | 5 +- .../vomap/DefaultVOMembershipProvider.java | 1 - .../vomap/VOMapDetailServiceBuilder.java | 14 +---- .../voters/FineGrainedCopyMoveAuthzVoter.java | 3 +- .../voters/WlcgScopeAuthzCopyMoveVoter.java | 3 +- .../config/FineGrainedAuthzPolicyParser.java | 2 +- .../webdav/config/SAConfigurationParser.java | 21 +++---- .../DefaultExtendedFileAttributesHelper.java | 20 +++---- .../webdav/milton/StoRMFileResource.java | 15 +++-- .../webdav/milton/StoRMMiltonRequest.java | 6 +- .../oauth/StormJwtAuthoritiesConverter.java | 2 +- .../oauth/authzserver/ErrorResponseDTO.java | 6 +- .../ResourceAccessTokenRequest.java | 2 +- .../oauth/authzserver/TokenResponseDTO.java | 4 +- .../authzserver/web/AuthzServerMetadata.java | 4 +- .../utils/TrustedJwtDecoderCacheLoader.java | 2 +- .../oauth/validator/WlcgProfileValidator.java | 19 +++--- .../oidc/ClientRegistrationCacheLoader.java | 6 +- .../webdav/redirector/RedirectConstants.java | 6 +- .../webdav/redirector/RedirectFilter.java | 4 +- .../webdav/server/servlet/MiltonFilter.java | 2 +- .../webdav/server/util/CANLListener.java | 6 +- .../storm/webdav/spring/AppConfig.java | 14 ++--- .../webdav/spring/web/SecurityConfig.java | 2 +- .../spring/web/ServletConfiguration.java | 13 ++--- .../storm/webdav/tpc/TpcUtils.java | 18 +++--- .../storm/webdav/tpc/TransferConstants.java | 40 +++++++------ .../storm/webdav/tpc/TransferFilter.java | 18 +++--- .../webdav/tpc/TransferFilterSupport.java | 50 +++++++++------- .../webdav/tpc/http/HttpTransferClient.java | 16 ++--- .../tpc/utils/Adler32DigestHeaderHelper.java | 4 +- .../storm/webdav/tpc/utils/ClientInfo.java | 14 +++-- .../storm/webdav/tpc/utils/UrlHelper.java | 8 +-- .../storm/webdav/utils/RangeCopyHelper.java | 2 + .../webdav/web/ViewUtilsInterceptor.java | 4 +- src/main/resources/templates/400.html | 4 +- src/main/resources/templates/401.html | 4 +- src/main/resources/templates/403.html | 4 +- src/main/resources/templates/404.html | 4 +- src/main/resources/templates/405.html | 4 +- src/main/resources/templates/authn-info.html | 4 +- src/main/resources/templates/error.html | 4 +- src/main/resources/templates/jetty-dir.html | 4 +- src/main/resources/templates/layout.html | 4 +- src/main/resources/templates/oidc-login.html | 4 +- src/main/resources/templates/sa-index.html | 4 +- .../LocalAuthzIntegrationTests.java | 10 ++-- .../webdav/test/authz/pdp/AuthzPdpTests.java | 18 +++--- .../test/authz/pdp/LocalAuthzPdpTests.java | 12 ++-- .../test/authz/pdp/PolicyParserTests.java | 6 +- .../pdp/PolicyPropertiesValidationTests.java | 10 ++-- .../test/authz/vomap/PathResolverTests.java | 12 ++-- .../webdav/test/authz/vomap/VOMSMapTests.java | 14 ++--- .../test/checksum/ChecksumHelperTest.java | 8 +-- .../MacaroonRequestIntegrationTests.java | 10 ++-- .../OAuthAuthzServerIntegrationTests.java | 16 ++--- .../webdav/test/oauth/jwt/JwtIssuerTest.java | 12 ++-- .../test/oauth/jwt/TokenServiceTest.java | 2 +- .../validator/AudienceValidatorTests.java | 14 ++--- .../RandomReplicaSelectorTests.java | 8 +-- .../test/redirector/RedirectFilterTests.java | 16 ++--- .../redirector/RedirectionServiceTests.java | 10 ++-- .../webdav/test/tpc/ClientInfoParserTest.java | 4 +- .../webdav/test/tpc/PullTransferTest.java | 20 ++++--- .../webdav/test/tpc/PushTransferTest.java | 20 ++++--- .../test/tpc/SciTagFilterActivationTest.java | 3 +- .../tpc/TransferFilterActivationTest.java | 39 +++++++------ .../test/tpc/TransferFilterTestSupport.java | 5 +- .../tpc/TransferRequestValidationTest.java | 58 ++++++++++--------- .../test/tpc/TransferReturnStatusTest.java | 16 ++--- .../webdav/test/tpc/TransferStatsTest.java | 6 +- .../webdav/test/tpc/http/ClientTest.java | 7 ++- .../webdav/test/tpc/http/DigestTest.java | 4 +- .../test/tpc/http/GetResponseHandlerTest.java | 21 +++---- .../integration/TpcClientRedirectionTest.java | 11 +--- .../http/integration/TpcIntegrationTest.java | 10 ++-- .../test/tpc/urlservice/URLServiceTest.java | 10 ++-- .../storm/webdav/test/utils/IOUtilsTest.java | 12 ++-- 82 files changed, 421 insertions(+), 419 deletions(-) diff --git a/src/main/java/org/italiangrid/storm/webdav/authn/ErrorPageAuthenticationEntryPoint.java b/src/main/java/org/italiangrid/storm/webdav/authn/ErrorPageAuthenticationEntryPoint.java index 7f869a1c..80216572 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authn/ErrorPageAuthenticationEntryPoint.java +++ b/src/main/java/org/italiangrid/storm/webdav/authn/ErrorPageAuthenticationEntryPoint.java @@ -35,7 +35,7 @@ public class ErrorPageAuthenticationEntryPoint implements AuthenticationEntryPoint { - final String errorPage = "/errors/401"; + static final String ERROR_PAGE = "/errors/401"; @Override public void commence(HttpServletRequest request, HttpServletResponse response, @@ -73,7 +73,7 @@ public void commence(HttpServletRequest request, HttpServletResponse response, request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, authException); - RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage); + RequestDispatcher dispatcher = request.getRequestDispatcher(ERROR_PAGE); dispatcher.forward(request, response); } } diff --git a/src/main/java/org/italiangrid/storm/webdav/authn/PrincipalHelper.java b/src/main/java/org/italiangrid/storm/webdav/authn/PrincipalHelper.java index d2f0de9b..1b2427dc 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authn/PrincipalHelper.java +++ b/src/main/java/org/italiangrid/storm/webdav/authn/PrincipalHelper.java @@ -43,13 +43,11 @@ public PrincipalHelper(ServiceConfigurationProperties config) throws MalformedUR public String getPrincipalAsString(Authentication authn) { if (authn == null || authn instanceof AnonymousAuthenticationToken) { - return "anonymous"; + return ANONYMOUS; } else if (authn instanceof OAuth2AuthenticationToken) { OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) authn; Map attributes = authToken.getPrincipal().getAttributes(); - String subjectIssuer = String.format("%s@%s", attributes.get("sub"), attributes.get("iss")); - return subjectIssuer; - + return String.format("%s@%s", attributes.get("sub"), attributes.get("iss")); } else if (authn instanceof PreAuthenticatedAuthenticationToken) { return authn.getName(); } else if (authn instanceof JwtAuthenticationToken) { diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/VOMSAuthenticationFilter.java b/src/main/java/org/italiangrid/storm/webdav/authz/VOMSAuthenticationFilter.java index d6ea1680..843424ec 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/VOMSAuthenticationFilter.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/VOMSAuthenticationFilter.java @@ -50,9 +50,9 @@ protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { public Object extractPrincipal(X509Certificate cert) { - return cert.getSubjectDN().getName(); + return cert.getSubjectX500Principal().getName(); } - + @Override public boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) { diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/VOMSPreAuthDetailsSource.java b/src/main/java/org/italiangrid/storm/webdav/authz/VOMSPreAuthDetailsSource.java index fa4c3cd9..8bd704fc 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/VOMSPreAuthDetailsSource.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/VOMSPreAuthDetailsSource.java @@ -109,7 +109,7 @@ protected Optional getSubjectAuthority(HttpServletRequest Optional chain = Utils.getCertificateChainFromRequest(request); if (chain.isPresent()) { return Optional.of(new X509SubjectAuthority( - ProxyUtils.getEndUserCertificate(chain.get()).getSubjectDN().getName())); + ProxyUtils.getEndUserCertificate(chain.get()).getSubjectX500Principal().getName())); } return Optional.empty(); diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/pdp/LocalAuthorizationPdp.java b/src/main/java/org/italiangrid/storm/webdav/authz/pdp/LocalAuthorizationPdp.java index f762177a..03c294df 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/pdp/LocalAuthorizationPdp.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/pdp/LocalAuthorizationPdp.java @@ -25,6 +25,7 @@ import java.net.URL; import java.util.EnumSet; import java.util.Optional; +import java.util.Set; import java.util.function.Supplier; import javax.servlet.http.HttpServletRequest; @@ -42,8 +43,8 @@ public class LocalAuthorizationPdp implements PathAuthorizationPdp, TpcUtils { public static final Logger LOG = LoggerFactory.getLogger(LocalAuthorizationPdp.class); - public static final EnumSet READ_PERMS = EnumSet.of(Permission.r, Permission.rw); - public static final EnumSet WRITE_PERMS = EnumSet.of(Permission.w, Permission.rw); + private static final Set READ_PERMS = EnumSet.of(Permission.r, Permission.rw); + private static final Set WRITE_PERMS = EnumSet.of(Permission.w, Permission.rw); private final URL localAuthzServerIssuer; diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/vomap/DefaultVOMembershipProvider.java b/src/main/java/org/italiangrid/storm/webdav/authz/vomap/DefaultVOMembershipProvider.java index 331b1d34..a4676653 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/vomap/DefaultVOMembershipProvider.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/vomap/DefaultVOMembershipProvider.java @@ -58,7 +58,6 @@ public boolean hasSubjectAsMember(String subject) { } finally { refreshLock.readLock().unlock(); - ; } } diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/vomap/VOMapDetailServiceBuilder.java b/src/main/java/org/italiangrid/storm/webdav/authz/vomap/VOMapDetailServiceBuilder.java index 5c5e4de2..e2657a8c 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/vomap/VOMapDetailServiceBuilder.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/vomap/VOMapDetailServiceBuilder.java @@ -18,7 +18,6 @@ import static java.util.Collections.emptySet; import java.io.File; -import java.io.FilenameFilter; import java.util.HashSet; import java.util.Set; @@ -76,15 +75,7 @@ public VOMapDetailsService build() { File configDir = new File(serviceConf.getVOMapFilesConfigDir()); directorySanityChecks(configDir); - File[] files = configDir.listFiles(new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - - return name.endsWith(VOMAPFILE_SUFFIX); - - } - }); + File[] files = configDir.listFiles((dir, name) -> name.endsWith(VOMAPFILE_SUFFIX)); if (files.length == 0) { logger.warn("No mapfiles found in {}. Was looking for files ending in {}", configDir, @@ -94,7 +85,7 @@ public boolean accept(File dir, String name) { - Set providers = new HashSet(); + Set providers = new HashSet<>(); for (File f : files) { try { String voName = FilenameUtils.removeExtension(f.getName()); @@ -106,7 +97,6 @@ public boolean accept(File dir, String name) { } catch (Throwable t) { logger.error("Error parsing mapfile {}: {}", f.getAbsolutePath(), t.getMessage(), t); - continue; } } diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/voters/FineGrainedCopyMoveAuthzVoter.java b/src/main/java/org/italiangrid/storm/webdav/authz/voters/FineGrainedCopyMoveAuthzVoter.java index 87dc77fd..1de3c859 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/voters/FineGrainedCopyMoveAuthzVoter.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/voters/FineGrainedCopyMoveAuthzVoter.java @@ -28,6 +28,7 @@ import org.italiangrid.storm.webdav.config.StorageAreaInfo; import org.italiangrid.storm.webdav.server.PathResolver; import org.italiangrid.storm.webdav.tpc.LocalURLService; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.ConfigAttribute; @@ -51,7 +52,7 @@ public int vote(Authentication authentication, FilterInvocation filter, return ACCESS_ABSTAIN; } - String destination = filter.getRequest().getHeader(DESTINATION_HEADER); + String destination = filter.getRequest().getHeader(TransferConstants.DESTINATION_HEADER); if (destination == null) { return ACCESS_ABSTAIN; diff --git a/src/main/java/org/italiangrid/storm/webdav/authz/voters/WlcgScopeAuthzCopyMoveVoter.java b/src/main/java/org/italiangrid/storm/webdav/authz/voters/WlcgScopeAuthzCopyMoveVoter.java index 83f16dd2..f1714411 100644 --- a/src/main/java/org/italiangrid/storm/webdav/authz/voters/WlcgScopeAuthzCopyMoveVoter.java +++ b/src/main/java/org/italiangrid/storm/webdav/authz/voters/WlcgScopeAuthzCopyMoveVoter.java @@ -28,6 +28,7 @@ import org.italiangrid.storm.webdav.config.StorageAreaInfo; import org.italiangrid.storm.webdav.server.PathResolver; import org.italiangrid.storm.webdav.tpc.LocalURLService; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.ConfigAttribute; @@ -57,7 +58,7 @@ public int vote(Authentication authentication, FilterInvocation filter, return ACCESS_ABSTAIN; } - String destination = filter.getRequest().getHeader(DESTINATION_HEADER); + String destination = filter.getRequest().getHeader(TransferConstants.DESTINATION_HEADER); if (destination == null) { return ACCESS_ABSTAIN; diff --git a/src/main/java/org/italiangrid/storm/webdav/config/FineGrainedAuthzPolicyParser.java b/src/main/java/org/italiangrid/storm/webdav/config/FineGrainedAuthzPolicyParser.java index 1d7922b9..715a61e1 100644 --- a/src/main/java/org/italiangrid/storm/webdav/config/FineGrainedAuthzPolicyParser.java +++ b/src/main/java/org/italiangrid/storm/webdav/config/FineGrainedAuthzPolicyParser.java @@ -162,7 +162,7 @@ PathAuthorizationPolicy parsePolicy(FineGrainedAuthzPolicyProperties policy) { policy.getPrincipals() .stream() .map(this::parsePrincipal) - .forEach(builder::withPrincipalMatcher);; + .forEach(builder::withPrincipalMatcher); return builder.build(); } diff --git a/src/main/java/org/italiangrid/storm/webdav/config/SAConfigurationParser.java b/src/main/java/org/italiangrid/storm/webdav/config/SAConfigurationParser.java index 569eba8f..753c352d 100644 --- a/src/main/java/org/italiangrid/storm/webdav/config/SAConfigurationParser.java +++ b/src/main/java/org/italiangrid/storm/webdav/config/SAConfigurationParser.java @@ -17,7 +17,6 @@ import java.io.File; import java.io.FileReader; -import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -32,12 +31,12 @@ public class SAConfigurationParser implements StorageAreaConfiguration { - private final Set RESERVED_SA_NAMES = - Sets.newHashSet("oauth", ".well-known", "actuator", "assets", "authn-info", "logout", "oidc-login"); + private static final Set RESERVED_SA_NAMES = Sets.newHashSet("oauth", ".well-known", + "actuator", "assets", "authn-info", "logout", "oidc-login"); private final ServiceConfiguration serviceConfig; - private String PROPERTIES_FILENAME_SUFFIX = ".properties"; + private static final String PROPERTIES_FILENAME_SUFFIX = ".properties"; private List saInfos; @@ -54,15 +53,11 @@ public SAConfigurationParser(ServiceConfiguration sc) { File dir = new File(saConfDir); directorySanityChecks(dir); - File[] saFiles = dir.listFiles(new FilenameFilter() { - - @Override - public boolean accept(File file, String name) { - if (RESERVED_SA_NAMES.contains(name) && name.endsWith(PROPERTIES_FILENAME_SUFFIX)) { - log.warn("Skipping {} as it is a reserved storage area name"); - } - return (!RESERVED_SA_NAMES.contains(name) && name.endsWith(PROPERTIES_FILENAME_SUFFIX)); + File[] saFiles = dir.listFiles((file, name) -> { + if (RESERVED_SA_NAMES.contains(name) && name.endsWith(PROPERTIES_FILENAME_SUFFIX)) { + log.warn("Skipping {} as it is a reserved storage area name", name); } + return (!RESERVED_SA_NAMES.contains(name) && name.endsWith(PROPERTIES_FILENAME_SUFFIX)); }); if (saFiles.length == 0) { @@ -72,7 +67,7 @@ public boolean accept(File file, String name) { throw new StoRMIntializationError(msg); } - saInfos = new ArrayList(); + saInfos = new ArrayList<>(); for (File f : saFiles) { diff --git a/src/main/java/org/italiangrid/storm/webdav/fs/attrs/DefaultExtendedFileAttributesHelper.java b/src/main/java/org/italiangrid/storm/webdav/fs/attrs/DefaultExtendedFileAttributesHelper.java index 8bb6a7dc..04392647 100644 --- a/src/main/java/org/italiangrid/storm/webdav/fs/attrs/DefaultExtendedFileAttributesHelper.java +++ b/src/main/java/org/italiangrid/storm/webdav/fs/attrs/DefaultExtendedFileAttributesHelper.java @@ -31,6 +31,9 @@ public class DefaultExtendedFileAttributesHelper implements ExtendedAttributesHelper { + private static final String USERDEFINEDFILEATTRIBUTEVIEW_NOT_SUPPORTED_MESSAGE = + "UserDefinedFileAttributeView not supported on file "; + public static final String STORM_ADLER32_CHECKSUM_ATTR_NAME = "storm.checksum.adler32"; public DefaultExtendedFileAttributesHelper() { @@ -62,8 +65,7 @@ public void setExtendedFileAttribute(File f, String attributeName, if (faView == null) { throw new IOException( - "UserDefinedFileAttributeView not supported on file " - + f.getAbsolutePath()); + USERDEFINEDFILEATTRIBUTEVIEW_NOT_SUPPORTED_MESSAGE + f.getAbsolutePath()); } faView.write(attributeName, StandardCharsets.UTF_8.encode(attributeValue)); @@ -75,14 +77,13 @@ public String getExtendedFileAttributeValue(File f, String attributeName) checkNotNull(f); checkArgument(!isNullOrEmpty(attributeName)); - + UserDefinedFileAttributeView faView = Files.getFileAttributeView( f.toPath(), UserDefinedFileAttributeView.class); if (faView == null) { throw new IOException( - "UserDefinedFileAttributeView not supported on file " - + f.getAbsolutePath()); + USERDEFINEDFILEATTRIBUTEVIEW_NOT_SUPPORTED_MESSAGE + f.getAbsolutePath()); } return getAttributeValue(faView, attributeName); @@ -93,14 +94,13 @@ public String getExtendedFileAttributeValue(File f, String attributeName) public List getExtendedFileAttributeNames(File f) throws IOException { checkNotNull(f); - + UserDefinedFileAttributeView faView = Files.getFileAttributeView( f.toPath(), UserDefinedFileAttributeView.class); if (faView == null) { throw new IOException( - "UserDefinedFileAttributeView not supported on file " - + f.getAbsolutePath()); + USERDEFINEDFILEATTRIBUTEVIEW_NOT_SUPPORTED_MESSAGE + f.getAbsolutePath()); } return faView.list(); @@ -127,7 +127,7 @@ public String getChecksumAttribute(File f) throws IOException { public boolean fileSupportsExtendedAttributes(File f) throws IOException { checkNotNull(f); - + UserDefinedFileAttributeView faView = Files.getFileAttributeView( f.toPath(), UserDefinedFileAttributeView.class); @@ -137,7 +137,7 @@ public boolean fileSupportsExtendedAttributes(File f) throws IOException { @Override public void setChecksumAttribute(Path p, String checksumValue) throws IOException { setChecksumAttribute(p.toFile(), checksumValue); - + } @Override diff --git a/src/main/java/org/italiangrid/storm/webdav/milton/StoRMFileResource.java b/src/main/java/org/italiangrid/storm/webdav/milton/StoRMFileResource.java index 5b56cc2a..14812812 100644 --- a/src/main/java/org/italiangrid/storm/webdav/milton/StoRMFileResource.java +++ b/src/main/java/org/italiangrid/storm/webdav/milton/StoRMFileResource.java @@ -184,14 +184,13 @@ protected void calculateChecksum() { @Override public Object getProperty(QName name) { - if (name.getNamespaceURI().equals(STORM_NAMESPACE_URI)) { - if (name.getLocalPart().equals(PROPERTY_CHECKSUM)) { - try { - return getExtendedAttributesHelper().getChecksumAttribute(getFile()); - } catch (IOException e) { - logger.warn("Errror getting checksum value for file: {}", getFile().getAbsolutePath(), e); - return null; - } + if (name.getNamespaceURI().equals(STORM_NAMESPACE_URI) + && name.getLocalPart().equals(PROPERTY_CHECKSUM)) { + try { + return getExtendedAttributesHelper().getChecksumAttribute(getFile()); + } catch (IOException e) { + logger.warn("Errror getting checksum value for file: {}", getFile().getAbsolutePath(), e); + return null; } } diff --git a/src/main/java/org/italiangrid/storm/webdav/milton/StoRMMiltonRequest.java b/src/main/java/org/italiangrid/storm/webdav/milton/StoRMMiltonRequest.java index ecc0d7c1..d1021cc4 100644 --- a/src/main/java/org/italiangrid/storm/webdav/milton/StoRMMiltonRequest.java +++ b/src/main/java/org/italiangrid/storm/webdav/milton/StoRMMiltonRequest.java @@ -28,8 +28,8 @@ public class StoRMMiltonRequest extends ServletRequest { - private static final String regex = "(http.*:\\d*)/webdav/(.*)$"; - private static final Pattern p = Pattern.compile(regex); + private static final String REGEX = "(http.*:\\d*)/webdav/(.*)$"; + private static final Pattern p = Pattern.compile(REGEX); public StoRMMiltonRequest(HttpServletRequest r, ServletContext servletContext) { @@ -60,5 +60,5 @@ public Auth getAuthorization() { // Always return null as milton is confused by the OAuth2 Bearer scheme return null; } - + } diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/StormJwtAuthoritiesConverter.java b/src/main/java/org/italiangrid/storm/webdav/oauth/StormJwtAuthoritiesConverter.java index a1df6ac8..a9f9160d 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/StormJwtAuthoritiesConverter.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/StormJwtAuthoritiesConverter.java @@ -85,7 +85,7 @@ protected Set extractOauthGroupAuthorities(Jwt jwt) { String tokenIssuer = jwt.getClaimAsString(JwtClaimNames.ISS); for (String groupClaim : OAUTH_GROUP_CLAIM_NAMES) { - if (Boolean.TRUE.equals(jwt.containsClaim(groupClaim))) { + if (jwt.hasClaim(groupClaim)) { jwt.getClaimAsStringList(groupClaim) .forEach(gc -> groupAuthorities.add(new JwtGroupAuthority(tokenIssuer, gc))); break; diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ErrorResponseDTO.java b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ErrorResponseDTO.java index 23d7e6ce..2521dc6f 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ErrorResponseDTO.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ErrorResponseDTO.java @@ -18,13 +18,13 @@ import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; @JsonInclude(NON_EMPTY) -@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class ErrorResponseDTO { - + public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type"; public static final String INVALID_REQUEST = "invalid_request"; public static final String INVALID_SCOPE = "invalid_scope"; diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ResourceAccessTokenRequest.java b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ResourceAccessTokenRequest.java index e3bce43f..26a3645c 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ResourceAccessTokenRequest.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/ResourceAccessTokenRequest.java @@ -21,7 +21,7 @@ public enum Permission { r, w, rw - }; + } final String path; final Permission permission; diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/TokenResponseDTO.java b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/TokenResponseDTO.java index 06f9967a..48ef1316 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/TokenResponseDTO.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/TokenResponseDTO.java @@ -18,11 +18,11 @@ import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; @JsonInclude(NON_EMPTY) -@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class TokenResponseDTO { String accessToken; diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/web/AuthzServerMetadata.java b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/web/AuthzServerMetadata.java index dba834b0..efb85698 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/web/AuthzServerMetadata.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/authzserver/web/AuthzServerMetadata.java @@ -21,11 +21,11 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; @JsonInclude(NON_EMPTY) -@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) public class AuthzServerMetadata { private String issuer; diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/utils/TrustedJwtDecoderCacheLoader.java b/src/main/java/org/italiangrid/storm/webdav/oauth/utils/TrustedJwtDecoderCacheLoader.java index f9e19765..161e1625 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/utils/TrustedJwtDecoderCacheLoader.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/utils/TrustedJwtDecoderCacheLoader.java @@ -96,7 +96,7 @@ public JwtDecoder load(String issuer) throws Exception { validators.add(new AudienceValidator(as)); } - decoder.setJwtValidator(new DelegatingOAuth2TokenValidator(validators)); + decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(validators)); return decoder; } diff --git a/src/main/java/org/italiangrid/storm/webdav/oauth/validator/WlcgProfileValidator.java b/src/main/java/org/italiangrid/storm/webdav/oauth/validator/WlcgProfileValidator.java index 2c59c7a0..5b11a118 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oauth/validator/WlcgProfileValidator.java +++ b/src/main/java/org/italiangrid/storm/webdav/oauth/validator/WlcgProfileValidator.java @@ -31,8 +31,9 @@ public class WlcgProfileValidator implements OAuth2TokenValidator { - public static final Logger LOG = LoggerFactory.getLogger(AudienceValidator.class); + public static final Logger LOG = LoggerFactory.getLogger(WlcgProfileValidator.class); + public static final String INVALID_TOKEN_ERROR_CODE = "invalid_token"; public static final String WLCG_VER_CLAIM = "wlcg.ver"; public static final String SCOPE_CLAIM = "scope"; @@ -40,25 +41,25 @@ public class WlcgProfileValidator implements OAuth2TokenValidator { Collections.unmodifiableSet(Sets.newHashSet("1.0")); private static final OAuth2Error INVALID_PROFILE_VERSION = - new OAuth2Error("invalid_token", "Unsupported WLCG token profile version", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "Unsupported WLCG token profile version", null); private static final OAuth2Error MISSING_SCOPE = - new OAuth2Error("invalid_token", "scope claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "scope claim not found in token", null); private static final OAuth2Error MISSING_NBF = - new OAuth2Error("invalid_token", "nbf claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "nbf claim not found in token", null); private static final OAuth2Error MISSING_EXP = - new OAuth2Error("invalid_token", "exp claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "exp claim not found in token", null); private static final OAuth2Error MISSING_SUB = - new OAuth2Error("invalid_token", "sub claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "sub claim not found in token", null); private static final OAuth2Error MISSING_AUD = - new OAuth2Error("invalid_token", "aud claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "aud claim not found in token", null); private static final OAuth2Error MISSING_JTI = - new OAuth2Error("invalid_token", "jti claim not found in token", null); + new OAuth2Error(INVALID_TOKEN_ERROR_CODE, "jti claim not found in token", null); private static final OAuth2TokenValidatorResult SUCCESS = OAuth2TokenValidatorResult.success(); @@ -76,7 +77,7 @@ public OAuth2TokenValidatorResult validate(Jwt token) { return OAuth2TokenValidatorResult.failure(INVALID_PROFILE_VERSION); } - if (Boolean.FALSE.equals(token.containsClaim(SCOPE_CLAIM))) { + if (!token.hasClaim(SCOPE_CLAIM)) { return OAuth2TokenValidatorResult.failure(MISSING_SCOPE); } diff --git a/src/main/java/org/italiangrid/storm/webdav/oidc/ClientRegistrationCacheLoader.java b/src/main/java/org/italiangrid/storm/webdav/oidc/ClientRegistrationCacheLoader.java index 46bf17ac..805ed969 100644 --- a/src/main/java/org/italiangrid/storm/webdav/oidc/ClientRegistrationCacheLoader.java +++ b/src/main/java/org/italiangrid/storm/webdav/oidc/ClientRegistrationCacheLoader.java @@ -70,10 +70,8 @@ private ClientRegistration getClientRegistration(String registrationId, map.from(properties::getAuthorizationGrantType) .as(AuthorizationGrantType::new) .to(builder::authorizationGrantType); - map.from(properties::getRedirectUri).to(builder::redirectUriTemplate); - map.from(properties::getScope) - .as((scope) -> StringUtils.toStringArray(scope)) - .to(builder::scope); + map.from(properties::getRedirectUri).to(builder::redirectUri); + map.from(properties::getScope).as(StringUtils::toStringArray).to(builder::scope); map.from(properties::getClientName).to(builder::clientName); return builder.build(); } diff --git a/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectConstants.java b/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectConstants.java index fa1d9fa6..90a24b21 100644 --- a/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectConstants.java +++ b/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectConstants.java @@ -15,8 +15,10 @@ */ package org.italiangrid.storm.webdav.redirector; -public interface RedirectConstants { +public final class RedirectConstants { - String ACCESS_TOKEN_PARAMETER = "access_token"; + public static final String ACCESS_TOKEN_PARAMETER = "access_token"; + + private RedirectConstants() {} } diff --git a/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectFilter.java b/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectFilter.java index 5b7d2ab8..7150b8e4 100644 --- a/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectFilter.java +++ b/src/main/java/org/italiangrid/storm/webdav/redirector/RedirectFilter.java @@ -35,7 +35,7 @@ import com.google.common.base.Strings; -public class RedirectFilter implements Filter, TpcUtils, RedirectConstants { +public class RedirectFilter implements Filter, TpcUtils { public static final String LOCATION = "Location"; public static final String NO_REDIRECT_QUERY_PARAM = "no_redirect"; @@ -93,7 +93,7 @@ private boolean isGetOrPutRequest(HttpServletRequest req) { private boolean requestDoesNotHaveAccessToken(HttpServletRequest req) { - String accessToken = req.getParameter(ACCESS_TOKEN_PARAMETER); + String accessToken = req.getParameter(RedirectConstants.ACCESS_TOKEN_PARAMETER); return Strings.isNullOrEmpty(accessToken); } diff --git a/src/main/java/org/italiangrid/storm/webdav/server/servlet/MiltonFilter.java b/src/main/java/org/italiangrid/storm/webdav/server/servlet/MiltonFilter.java index 54cd7762..813c805a 100644 --- a/src/main/java/org/italiangrid/storm/webdav/server/servlet/MiltonFilter.java +++ b/src/main/java/org/italiangrid/storm/webdav/server/servlet/MiltonFilter.java @@ -126,7 +126,7 @@ public void doMilton(HttpServletRequest request, HttpServletResponse response) { try { // Is this really needed? - MiltonServlet.setThreadlocals((HttpServletRequest) request, (HttpServletResponse) response); + MiltonServlet.setThreadlocals(request, response); Request miltonReq = new StoRMMiltonRequest(request, servletContext); diff --git a/src/main/java/org/italiangrid/storm/webdav/server/util/CANLListener.java b/src/main/java/org/italiangrid/storm/webdav/server/util/CANLListener.java index 59b5f57e..872eb24e 100644 --- a/src/main/java/org/italiangrid/storm/webdav/server/util/CANLListener.java +++ b/src/main/java/org/italiangrid/storm/webdav/server/util/CANLListener.java @@ -35,13 +35,13 @@ public void loadingNotification(String location, String type, Severity level, Ex location = location.substring(5, location.length()); if (level.equals(Severity.ERROR)) { - LOG.error("Error for {} {}: {}.", new Object[] {type, location, cause.getMessage()}); + LOG.error("Error for {} {}: {}.", type, location, cause.getMessage()); } else if (level.equals(Severity.WARNING)) { - LOG.debug("Warning for {} {}: {}.", new Object[] {type, location, cause.getMessage()}); + LOG.debug("Warning for {} {}: {}.", type, location, cause.getMessage()); } else if (level.equals(Severity.NOTIFICATION)) { - LOG.debug("Loading {} {}.", new Object[] {type, location}); + LOG.debug("Loading {} {}.", type, location); } } diff --git a/src/main/java/org/italiangrid/storm/webdav/spring/AppConfig.java b/src/main/java/org/italiangrid/storm/webdav/spring/AppConfig.java index 46dccccb..08b344a8 100644 --- a/src/main/java/org/italiangrid/storm/webdav/spring/AppConfig.java +++ b/src/main/java/org/italiangrid/storm/webdav/spring/AppConfig.java @@ -125,7 +125,7 @@ import eu.emi.security.authn.x509.impl.PEMCredential; @Configuration -public class AppConfig implements TransferConstants { +public class AppConfig { public static final Logger LOG = LoggerFactory.getLogger(AppConfig.class); @@ -266,10 +266,10 @@ HttpClientConnectionManager tpcClientConnectionManager(ThirdPartyCopyProperties LayeredConnectionSocketFactory tlsSf = new TpcSSLConnectionSocketFactory(ctx); Registry r = RegistryBuilder.create() - .register(HTTP, sf) - .register(HTTPS, tlsSf) - .register(DAV, sf) - .register(DAVS, tlsSf) + .register(TransferConstants.HTTP, sf) + .register(TransferConstants.HTTPS, tlsSf) + .register(TransferConstants.DAV, sf) + .register(TransferConstants.DAVS, tlsSf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r); @@ -331,7 +331,7 @@ ClientRegistrationRepository clientRegistrationRepository( LOG.info("OpenID providers configuration will be refreshed every {} minutes", props.getRefreshPeriodMinutes()); - return (k) -> { + return k -> { try { return clients.get(k); } catch (ExecutionException e) { @@ -428,7 +428,7 @@ PathAuthorizationPdp fineGrainedAuthzPdpd(PathAuthorizationPolicyRepository repo @Bean @ConditionalOnProperty(name = "oauth.enable-oidc", havingValue = "false") ClientRegistrationRepository emptyClientRegistrationRepository() { - return (id) -> null; + return id -> null; } diff --git a/src/main/java/org/italiangrid/storm/webdav/spring/web/SecurityConfig.java b/src/main/java/org/italiangrid/storm/webdav/spring/web/SecurityConfig.java index 8a7f093a..0e85dbf0 100644 --- a/src/main/java/org/italiangrid/storm/webdav/spring/web/SecurityConfig.java +++ b/src/main/java/org/italiangrid/storm/webdav/spring/web/SecurityConfig.java @@ -87,7 +87,7 @@ public class SecurityConfig { private static final Logger LOG = LoggerFactory.getLogger(SecurityConfig.class); - private final static List ALLOWED_METHODS; + private static final List ALLOWED_METHODS; static { ALLOWED_METHODS = Lists.newArrayList(); diff --git a/src/main/java/org/italiangrid/storm/webdav/spring/web/ServletConfiguration.java b/src/main/java/org/italiangrid/storm/webdav/spring/web/ServletConfiguration.java index 261fac93..23ce8b49 100644 --- a/src/main/java/org/italiangrid/storm/webdav/spring/web/ServletConfiguration.java +++ b/src/main/java/org/italiangrid/storm/webdav/spring/web/ServletConfiguration.java @@ -121,8 +121,8 @@ FilterRegistrationBean redirectFilter(PathResolver pathResolver, RedirectionService redirectionService) { LOG.info("Redirector filter enabled"); - FilterRegistrationBean filter = new FilterRegistrationBean( - new RedirectFilter(pathResolver, redirectionService)); + FilterRegistrationBean filter = + new FilterRegistrationBean<>(new RedirectFilter(pathResolver, redirectionService)); filter.addUrlPatterns("/*"); filter.setOrder(REDIRECT_REQ_FILTER_ORDER); @@ -200,9 +200,9 @@ FilterRegistrationBean tpcFilter(Clock clock, FilesystemAccess f TransferClient metricsClient = new HttpTransferClientMetricsWrapper(registry, client); - FilterRegistrationBean tpcFilter = new FilterRegistrationBean<>( - new TransferFilter(clock, metricsClient, resolver, lus, props.isVerifyChecksum(), - props.getEnableExpectContinueThreshold())); + FilterRegistrationBean tpcFilter = + new FilterRegistrationBean<>(new TransferFilter(clock, metricsClient, resolver, lus, + props.isVerifyChecksum(), props.getEnableExpectContinueThreshold())); tpcFilter.addUrlPatterns("/*"); tpcFilter.setOrder(TPC_FILTER_ORDER); return tpcFilter; @@ -213,8 +213,7 @@ FilterRegistrationBean statsFilter(MetricRegistry regist PathResolver resolver) { FilterRegistrationBean filter = - new FilterRegistrationBean( - new StorageAreaStatsFilter(registry, resolver)); + new FilterRegistrationBean<>(new StorageAreaStatsFilter(registry, resolver)); filter.addUrlPatterns("/*"); filter.setOrder(STATS_FILTER_ORDER); return filter; diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/TpcUtils.java b/src/main/java/org/italiangrid/storm/webdav/tpc/TpcUtils.java index 57ae36bc..5e7a1ec0 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/TpcUtils.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/TpcUtils.java @@ -30,7 +30,7 @@ import org.italiangrid.storm.webdav.error.ResourceNotFound; import org.italiangrid.storm.webdav.server.PathResolver; -public interface TpcUtils extends TransferConstants { +public interface TpcUtils { default Supplier resourceNotFoundError(String path) { return () -> new ResourceNotFound(format("No storage area found matching path: %s", path)); @@ -47,27 +47,29 @@ default String getSerlvetRequestPath(HttpServletRequest request) { } default String destinationHeader(HttpServletRequest request) { - return request.getHeader(DESTINATION_HEADER); + return request.getHeader(TransferConstants.DESTINATION_HEADER); } default boolean requestHasSourceHeader(HttpServletRequest request) { - return Optional.ofNullable(request.getHeader(SOURCE_HEADER)).isPresent(); + return Optional.ofNullable(request.getHeader(TransferConstants.SOURCE_HEADER)).isPresent(); } default boolean requestHasDestinationHeader(HttpServletRequest request) { - return Optional.ofNullable(request.getHeader(DESTINATION_HEADER)).isPresent(); + return Optional.ofNullable(request.getHeader(TransferConstants.DESTINATION_HEADER)).isPresent(); } default boolean requestHasLocalDestinationHeader(HttpServletRequest request, LocalURLService localURLService) { - Optional destination = Optional.ofNullable(request.getHeader(DESTINATION_HEADER)); + Optional destination = + Optional.ofNullable(request.getHeader(TransferConstants.DESTINATION_HEADER)); return (destination.isPresent() && localURLService.isLocalURL(destination.get())); } default boolean requestHasRemoteDestinationHeader(HttpServletRequest request, LocalURLService localURLService) { - Optional destination = Optional.ofNullable(request.getHeader(DESTINATION_HEADER)); + Optional destination = + Optional.ofNullable(request.getHeader(TransferConstants.DESTINATION_HEADER)); return (destination.isPresent() && !localURLService.isLocalURL(destination.get())); } @@ -112,7 +114,7 @@ default boolean requestHasTranferHeader(HttpServletRequest request) { Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - if (headerName.toLowerCase().startsWith(TRANSFER_HEADER_LC)) { + if (headerName.toLowerCase().startsWith(TransferConstants.TRANSFER_HEADER_LC)) { return true; } } @@ -130,7 +132,7 @@ default boolean isCopyOrMoveRequest(HttpServletRequest request) { } default String dropSlashWebdavFromPath(String path) { - Matcher m = WEBDAV_PATH_PATTERN.matcher(path); + Matcher m = TransferConstants.WEBDAV_PATH_PATTERN.matcher(path); if (m.matches()) { return String.format("/%s", m.group(1)); diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferConstants.java b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferConstants.java index fa6a55fb..64f0c25a 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferConstants.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferConstants.java @@ -20,32 +20,34 @@ import com.google.common.collect.ImmutableSet; -public interface TransferConstants { +public final class TransferConstants { - String AUTHORIZATION_HEADER = "Authorization"; - String CLIENT_INFO_HEADER = "ClientInfo"; - String SOURCE_HEADER = "Source"; - String DESTINATION_HEADER = "Destination"; - String OVERWRITE_HEADER = "Overwrite"; - String REQUIRE_CHECKSUM_HEADER = "RequireChecksumVerification"; - String CREDENTIAL_HEADER = "Credential"; + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String CLIENT_INFO_HEADER = "ClientInfo"; + public static final String SOURCE_HEADER = "Source"; + public static final String DESTINATION_HEADER = "Destination"; + public static final String OVERWRITE_HEADER = "Overwrite"; + public static final String REQUIRE_CHECKSUM_HEADER = "RequireChecksumVerification"; + public static final String CREDENTIAL_HEADER = "Credential"; - String CREDENTIAL_HEADER_NONE_VALUE = "none"; + public static final String CREDENTIAL_HEADER_NONE_VALUE = "none"; - String TRANSFER_HEADER = "TransferHeader"; - String TRANSFER_HEADER_LC = TRANSFER_HEADER.toLowerCase(); - int TRANFER_HEADER_LENGTH = TRANSFER_HEADER.length(); + public static final String TRANSFER_HEADER = "TransferHeader"; + public static final String TRANSFER_HEADER_LC = TRANSFER_HEADER.toLowerCase(); + public static final int TRANFER_HEADER_LENGTH = TRANSFER_HEADER.length(); - String HTTP = "http"; - String HTTPS = "https"; + public static final String HTTP = "http"; + public static final String HTTPS = "https"; - String DAV = "dav"; - String DAVS = "davs"; + public static final String DAV = "dav"; + public static final String DAVS = "davs"; - Set SUPPORTED_PROTOCOLS = + public static final Set SUPPORTED_PROTOCOLS = ImmutableSet.builder().add(HTTP, HTTPS, DAV, DAVS).build(); - String WEBDAV_PATH_REGEX = "/webdav/(.*)$"; - Pattern WEBDAV_PATH_PATTERN = Pattern.compile(WEBDAV_PATH_REGEX); + public static final String WEBDAV_PATH_REGEX = "/webdav/(.*)$"; + public static final Pattern WEBDAV_PATH_PATTERN = Pattern.compile(WEBDAV_PATH_REGEX); + + private TransferConstants() {} } diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilter.java b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilter.java index 7788865a..c40d2a56 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilter.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilter.java @@ -108,7 +108,8 @@ protected void handleTpc(HttpServletRequest request, HttpServletResponse respons try { if (validRequest(request, response)) { - Optional source = Optional.ofNullable(request.getHeader(SOURCE_HEADER)); + Optional source = + Optional.ofNullable(request.getHeader(TransferConstants.SOURCE_HEADER)); SciTag scitag = (SciTag) request.getAttribute(SciTag.SCITAG_ATTRIBUTE); if (source.isPresent()) { handlePullCopy(request, response, scitag); @@ -123,7 +124,8 @@ protected void handleTpc(HttpServletRequest request, HttpServletResponse respons } private void setupLoggingContext(HttpServletRequest request) { - Optional clientInfoHeader = Optional.ofNullable(request.getHeader(CLIENT_INFO_HEADER)); + Optional clientInfoHeader = + Optional.ofNullable(request.getHeader(TransferConstants.CLIENT_INFO_HEADER)); if (clientInfoHeader.isPresent()) { try { @@ -147,8 +149,8 @@ protected void logTransferStart(GetTransferRequest req) { LOG.info( "Pull third-party transfer requested: Source: {}, Destination: {}, hasAuthorizationHeader: {}, id: {}", - req.remoteURI(), req.path(), req.transferHeaders().containsKey(AUTHORIZATION_HEADER), - req.uuid()); + req.remoteURI(), req.path(), + req.transferHeaders().containsKey(TransferConstants.AUTHORIZATION_HEADER), req.uuid()); if (LOG.isDebugEnabled()) { LOG.debug("{}", req); } @@ -157,8 +159,8 @@ protected void logTransferStart(GetTransferRequest req) { protected void logTransferStart(PutTransferRequest req) { LOG.info( "Push third-party transfer requested: Source: {}, Destination: {}, hasAuthorizationHeader: {}, id: {}", - req.path(), req.remoteURI(), req.transferHeaders().containsKey(AUTHORIZATION_HEADER), - req.uuid()); + req.path(), req.remoteURI(), + req.transferHeaders().containsKey(TransferConstants.AUTHORIZATION_HEADER), req.uuid()); if (LOG.isDebugEnabled()) { LOG.debug("{}", req); } @@ -215,7 +217,7 @@ protected void logTransferException(TransferRequest request, Exception e) { protected void handlePullCopy(HttpServletRequest request, HttpServletResponse response, SciTag scitag) throws IOException { - URI uri = URI.create(request.getHeader(SOURCE_HEADER)); + URI uri = URI.create(request.getHeader(TransferConstants.SOURCE_HEADER)); String path = getScopedPathInfo(request); GetTransferRequest xferRequest = GetTransferRequestBuilder.create() @@ -254,7 +256,7 @@ protected void handlePullCopy(HttpServletRequest request, HttpServletResponse re protected void handlePushCopy(HttpServletRequest request, HttpServletResponse response, SciTag scitag) throws IOException { - URI uri = URI.create(request.getHeader(DESTINATION_HEADER)); + URI uri = URI.create(request.getHeader(TransferConstants.DESTINATION_HEADER)); String path = getScopedPathInfo(request); PutTransferRequest xferRequest = PutTransferRequestBuilder.create() diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilterSupport.java b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilterSupport.java index 448f09d1..ad0b487d 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilterSupport.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/TransferFilterSupport.java @@ -46,7 +46,7 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; -public class TransferFilterSupport implements TransferConstants, TpcUtils { +public class TransferFilterSupport implements TpcUtils { public static final Logger LOG = LoggerFactory.getLogger(TransferFilterSupport.class); @@ -81,8 +81,8 @@ protected Multimap getTransferHeaders(HttpServletRequest request while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); - if (headerName.toLowerCase().startsWith(TRANSFER_HEADER_LC)) { - String xferHeaderName = headerName.substring(TRANFER_HEADER_LENGTH); + if (headerName.toLowerCase().startsWith(TransferConstants.TRANSFER_HEADER_LC)) { + String xferHeaderName = headerName.substring(TransferConstants.TRANFER_HEADER_LENGTH); if (xferHeaderName.trim().length() == 0) { LOG.warn("Ignoring invalid transfer header {}", headerName); continue; @@ -109,7 +109,7 @@ protected Multimap getTransferHeaders(HttpServletRequest request protected boolean verifyChecksumRequested(HttpServletRequest request) { Optional verifyChecksumFromHeader = - Optional.ofNullable(request.getHeader(REQUIRE_CHECKSUM_HEADER)); + Optional.ofNullable(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)); if (verifyChecksumFromHeader.isPresent()) { return "true".equals(verifyChecksumFromHeader.get()); @@ -119,7 +119,8 @@ protected boolean verifyChecksumRequested(HttpServletRequest request) { } protected boolean overwriteRequested(HttpServletRequest request) { - Optional overwrite = Optional.ofNullable(request.getHeader(OVERWRITE_HEADER)); + Optional overwrite = + Optional.ofNullable(request.getHeader(TransferConstants.OVERWRITE_HEADER)); if (overwrite.isPresent()) { return "T".equalsIgnoreCase(overwrite.get()); @@ -130,7 +131,7 @@ protected boolean overwriteRequested(HttpServletRequest request) { protected boolean isSupportedTransferURI(URI uri) { - return SUPPORTED_PROTOCOLS.contains(uri.getScheme()) && uri.getPath() != null; + return TransferConstants.SUPPORTED_PROTOCOLS.contains(uri.getScheme()) && uri.getPath() != null; } protected boolean validTransferURI(String xferUri) { @@ -242,26 +243,33 @@ protected boolean validLocalDestinationPath(HttpServletRequest request, protected boolean validRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { - Optional source = Optional.ofNullable(request.getHeader(SOURCE_HEADER)); - Optional dest = Optional.ofNullable(request.getHeader(DESTINATION_HEADER)); - Optional overwrite = Optional.ofNullable(request.getHeader(OVERWRITE_HEADER)); - Optional checksum = Optional.ofNullable(request.getHeader(REQUIRE_CHECKSUM_HEADER)); - Optional credential = Optional.ofNullable(request.getHeader(CREDENTIAL_HEADER)); + Optional source = + Optional.ofNullable(request.getHeader(TransferConstants.SOURCE_HEADER)); + Optional dest = + Optional.ofNullable(request.getHeader(TransferConstants.DESTINATION_HEADER)); + Optional overwrite = + Optional.ofNullable(request.getHeader(TransferConstants.OVERWRITE_HEADER)); + Optional checksum = + Optional.ofNullable(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)); + Optional credential = + Optional.ofNullable(request.getHeader(TransferConstants.CREDENTIAL_HEADER)); if (source.isPresent() && dest.isPresent()) { invalidRequest(response, "Source and Destination headers are both present!"); return false; } - if (source.isPresent() && !validTransferURI(request.getHeader(SOURCE_HEADER))) { - invalidRequest(response, - format("Invalid %s header: %s", SOURCE_HEADER, request.getHeader(SOURCE_HEADER))); + if (source.isPresent() + && !validTransferURI(request.getHeader(TransferConstants.SOURCE_HEADER))) { + invalidRequest(response, format("Invalid %s header: %s", TransferConstants.SOURCE_HEADER, + request.getHeader(TransferConstants.SOURCE_HEADER))); return false; } - if (dest.isPresent() && !validTransferURI(request.getHeader(DESTINATION_HEADER))) { - invalidRequest(response, format("Invalid %s header: %s", DESTINATION_HEADER, - request.getHeader(DESTINATION_HEADER))); + if (dest.isPresent() + && !validTransferURI(request.getHeader(TransferConstants.DESTINATION_HEADER))) { + invalidRequest(response, format("Invalid %s header: %s", TransferConstants.DESTINATION_HEADER, + request.getHeader(TransferConstants.DESTINATION_HEADER))); return false; } @@ -284,7 +292,8 @@ protected boolean validRequest(HttpServletRequest request, HttpServletResponse r } if (invalidOverwrite) { - invalidRequest(response, format("Invalid %s header value: %s", OVERWRITE_HEADER, val)); + invalidRequest(response, + format("Invalid %s header value: %s", TransferConstants.OVERWRITE_HEADER, val)); return false; } } @@ -301,12 +310,13 @@ protected boolean validRequest(HttpServletRequest request, HttpServletResponse r if (invalidChecksum) { invalidRequest(response, - format("Invalid %s header value: %s", REQUIRE_CHECKSUM_HEADER, val)); + format("Invalid %s header value: %s", TransferConstants.REQUIRE_CHECKSUM_HEADER, val)); return false; } } - if (credential.isPresent() && !CREDENTIAL_HEADER_NONE_VALUE.equals(credential.get())) { + if (credential.isPresent() + && !TransferConstants.CREDENTIAL_HEADER_NONE_VALUE.equals(credential.get())) { invalidRequest(response, "Unsupported Credential header value: " + credential.get()); return false; } diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/http/HttpTransferClient.java b/src/main/java/org/italiangrid/storm/webdav/tpc/http/HttpTransferClient.java index 87cad35d..a4f77887 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/http/HttpTransferClient.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/http/HttpTransferClient.java @@ -116,7 +116,7 @@ HttpGet prepareRequest(GetTransferRequest request) { return get; } - HttpPut prepareRequest(PutTransferRequest request, HttpEntity cfe) throws IOException { + HttpPut prepareRequest(PutTransferRequest request, HttpEntity cfe) { request.setTransferStatus(TransferStatus.builder(clock).inProgress(0)); @@ -170,9 +170,9 @@ public void handle(GetTransferRequest request, TransferStatusCallback cb) { HttpGet get = prepareRequest(request); HttpClientContext context = HttpClientContext.create(); - ScheduledFuture reportTask = executorService.scheduleAtFixedRate(() -> { - reportStatus(cb, request, statusBuilder.inProgress(os.getCount())); - }, reportDelaySec, reportDelaySec, TimeUnit.SECONDS); + ScheduledFuture reportTask = executorService.scheduleAtFixedRate( + () -> reportStatus(cb, request, statusBuilder.inProgress(os.getCount())), reportDelaySec, + reportDelaySec, TimeUnit.SECONDS); try { @@ -233,13 +233,7 @@ public void handle(PutTransferRequest request, TransferStatusCallback cb) { HttpPut put = null; HttpClientContext context = HttpClientContext.create(); - try { - put = prepareRequest(request, cfe); - } catch (IOException e) { - logException(e); - reportStatus(cb, request, statusBuilder - .error(format("Error pushing %s: %s", request.remoteURI().toString(), e.getMessage()))); - } + put = prepareRequest(request, cfe); ScheduledFuture reportTask = executorService.scheduleAtFixedRate( () -> reportStatus(cb, request, statusBuilder.inProgress(cfe.getCount())), reportDelaySec, diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/Adler32DigestHeaderHelper.java b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/Adler32DigestHeaderHelper.java index 6c6d8f32..c75c991f 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/Adler32DigestHeaderHelper.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/Adler32DigestHeaderHelper.java @@ -31,6 +31,8 @@ public class Adler32DigestHeaderHelper { public static final String DIGEST_HEADER_REGEX = "^\\s*adler32\\s*=\\s*([0-9a-zA-Z]{8})\\s*"; public static final Pattern DIGEST_HEADER_PATTERN = Pattern.compile(DIGEST_HEADER_REGEX); + private Adler32DigestHeaderHelper() {} + public static Optional extractAdler32DigestFromResponse(HttpResponse response) { checkNotNull(response); @@ -40,7 +42,7 @@ public static Optional extractAdler32DigestFromResponse(HttpResponse res if (digestHeader.isPresent()) { String digestHeaderValue = digestHeader.get().getValue(); - + if (!isNullOrEmpty(digestHeaderValue)) { Matcher m = DIGEST_HEADER_PATTERN.matcher(digestHeaderValue); diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/ClientInfo.java b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/ClientInfo.java index a3ceca4d..1e099704 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/ClientInfo.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/ClientInfo.java @@ -27,8 +27,10 @@ public class ClientInfo { + private static final String INVALID_CLIENTINFO_HEADER_MESSAGE = "Invalid ClientInfo header: %s"; + public static final String CLIENT_INFO_MDC_KEY = "tpc.clientInfo"; - + public static final String JOB_ID_KEY = "job-id"; public static final String FILE_ID_KEY = "file-id"; public static final String RETRY_COUNT_KEY = "retry"; @@ -59,13 +61,13 @@ public int getRetryCount() { } public static ClientInfo fromHeaderString(String headerString) { - checkArgument(!isNullOrEmpty(headerString), "Invalid ClientInfo header: %s", headerString); + checkArgument(!isNullOrEmpty(headerString), INVALID_CLIENTINFO_HEADER_MESSAGE, headerString); Map splitResult = SPLITTER.split(headerString); - checkArgument(splitResult.containsKey(JOB_ID_KEY), "Invalid ClientInfo header: %s", + checkArgument(splitResult.containsKey(JOB_ID_KEY), INVALID_CLIENTINFO_HEADER_MESSAGE, headerString); - checkArgument(splitResult.containsKey(FILE_ID_KEY), "Invalid ClientInfo header: %s", + checkArgument(splitResult.containsKey(FILE_ID_KEY), INVALID_CLIENTINFO_HEADER_MESSAGE, headerString); - checkArgument(splitResult.containsKey(RETRY_COUNT_KEY), "Invalid ClientInfo header: %s", + checkArgument(splitResult.containsKey(RETRY_COUNT_KEY), INVALID_CLIENTINFO_HEADER_MESSAGE, headerString); return new ClientInfo(splitResult.get(JOB_ID_KEY), splitResult.get(FILE_ID_KEY), Integer.parseInt(splitResult.get(RETRY_COUNT_KEY))); @@ -74,6 +76,6 @@ public static ClientInfo fromHeaderString(String headerString) { public void addToMDC() { final String ciStr = String.format("job-id:%s,file-id:%s,retry:%d", jobId, fileId, retryCount); MDC.put(CLIENT_INFO_MDC_KEY, ciStr); - + } } diff --git a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/UrlHelper.java b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/UrlHelper.java index 5462e239..6dc72458 100644 --- a/src/main/java/org/italiangrid/storm/webdav/tpc/utils/UrlHelper.java +++ b/src/main/java/org/italiangrid/storm/webdav/tpc/utils/UrlHelper.java @@ -15,8 +15,6 @@ */ package org.italiangrid.storm.webdav.tpc.utils; -import static java.util.Objects.isNull; - import java.net.URI; import java.net.URISyntaxException; @@ -31,11 +29,7 @@ public static boolean isRemoteUrl(String url) { URI uri = new URI(url); - if (isNull(uri.getScheme())) { - return false; - } - - return true; + return uri.getScheme() != null; } catch (URISyntaxException e) { return false; diff --git a/src/main/java/org/italiangrid/storm/webdav/utils/RangeCopyHelper.java b/src/main/java/org/italiangrid/storm/webdav/utils/RangeCopyHelper.java index c442df09..cef6fa60 100644 --- a/src/main/java/org/italiangrid/storm/webdav/utils/RangeCopyHelper.java +++ b/src/main/java/org/italiangrid/storm/webdav/utils/RangeCopyHelper.java @@ -28,6 +28,8 @@ public class RangeCopyHelper { + private RangeCopyHelper() {} + public static long rangeCopy(InputStream is, File f, long rangeStart, long rangeCount) throws IOException { checkNotNull(is); diff --git a/src/main/java/org/italiangrid/storm/webdav/web/ViewUtilsInterceptor.java b/src/main/java/org/italiangrid/storm/webdav/web/ViewUtilsInterceptor.java index f4df47dc..f1b54e2b 100644 --- a/src/main/java/org/italiangrid/storm/webdav/web/ViewUtilsInterceptor.java +++ b/src/main/java/org/italiangrid/storm/webdav/web/ViewUtilsInterceptor.java @@ -25,9 +25,9 @@ import org.italiangrid.storm.webdav.server.servlet.SAIndexServlet; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.servlet.HandlerInterceptor; -public class ViewUtilsInterceptor extends HandlerInterceptorAdapter { +public class ViewUtilsInterceptor implements HandlerInterceptor { final ServiceConfigurationProperties serviceConfig; final StorageAreaConfiguration saConfig; diff --git a/src/main/resources/templates/400.html b/src/main/resources/templates/400.html index 14d78a16..9bf8a90e 100644 --- a/src/main/resources/templates/400.html +++ b/src/main/resources/templates/400.html @@ -1,5 +1,5 @@ - Bad request! @@ -10,4 +10,4 @@

Bad request!

The request you submitted is malformed!

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/401.html b/src/main/resources/templates/401.html index dee6c977..b6cf5c92 100644 --- a/src/main/resources/templates/401.html +++ b/src/main/resources/templates/401.html @@ -1,5 +1,5 @@ - Access denied! @@ -10,4 +10,4 @@

Unauthorized!

You are not authenticated and are trying to access content that requires authenticated access!

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/403.html b/src/main/resources/templates/403.html index bdf4065d..3b7c6306 100644 --- a/src/main/resources/templates/403.html +++ b/src/main/resources/templates/403.html @@ -1,5 +1,5 @@ - Access denied! @@ -10,4 +10,4 @@

Forbidden!

You do not have the rights to access the requested resources!

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/404.html b/src/main/resources/templates/404.html index a895f025..18bc284a 100644 --- a/src/main/resources/templates/404.html +++ b/src/main/resources/templates/404.html @@ -1,5 +1,5 @@ - Not found! @@ -10,4 +10,4 @@

Not found!

We could not find the resource you're looking for...

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/405.html b/src/main/resources/templates/405.html index 4a228df8..6200622f 100644 --- a/src/main/resources/templates/405.html +++ b/src/main/resources/templates/405.html @@ -1,5 +1,5 @@ - Access denied! @@ -10,4 +10,4 @@

Request method not allowed!

The http method in your request is not allowed for the target resource!

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/authn-info.html b/src/main/resources/templates/authn-info.html index 8c9570cc..3980a10a 100644 --- a/src/main/resources/templates/authn-info.html +++ b/src/main/resources/templates/authn-info.html @@ -1,5 +1,5 @@ - Authentication info @@ -26,4 +26,4 @@ Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html index 3e127e9b..438b6d21 100644 --- a/src/main/resources/templates/error.html +++ b/src/main/resources/templates/error.html @@ -1,5 +1,5 @@ - Error! @@ -10,4 +10,4 @@

Ops!

Something went wrong, and this page is not very informative

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/jetty-dir.html b/src/main/resources/templates/jetty-dir.html index 6963c475..b06c5b35 100644 --- a/src/main/resources/templates/jetty-dir.html +++ b/src/main/resources/templates/jetty-dir.html @@ -1,5 +1,5 @@ - Directory @@ -31,4 +31,4 @@

Directory

- \ No newline at end of file + diff --git a/src/main/resources/templates/layout.html b/src/main/resources/templates/layout.html index 8f38e1f5..b5689f46 100644 --- a/src/main/resources/templates/layout.html +++ b/src/main/resources/templates/layout.html @@ -1,5 +1,5 @@ - + StoRM WebDAV @@ -39,4 +39,4 @@

- \ No newline at end of file + diff --git a/src/main/resources/templates/oidc-login.html b/src/main/resources/templates/oidc-login.html index 0cdb116e..4b4843bd 100644 --- a/src/main/resources/templates/oidc-login.html +++ b/src/main/resources/templates/oidc-login.html @@ -1,5 +1,5 @@ - StoRM WebDAV service - Login @@ -24,4 +24,4 @@

Login error

Go back to the storage area index page - \ No newline at end of file + diff --git a/src/main/resources/templates/sa-index.html b/src/main/resources/templates/sa-index.html index 560b8174..2f2820a9 100644 --- a/src/main/resources/templates/sa-index.html +++ b/src/main/resources/templates/sa-index.html @@ -1,5 +1,5 @@ - Storage areas index @@ -18,4 +18,4 @@

Storage areas:

- \ No newline at end of file + diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/integration/LocalAuthzIntegrationTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/integration/LocalAuthzIntegrationTests.java index 2935fa19..d59a1bbe 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/integration/LocalAuthzIntegrationTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/integration/LocalAuthzIntegrationTests.java @@ -77,12 +77,12 @@ public void setup() { } @Test - public void testLocalAuthz() throws Exception { + void testLocalAuthz() throws Exception { mvc.perform(put(SLASH_WLCG_SLASH_FILE)).andExpect(status().isUnauthorized()); } @Test - public void testInvalidTokenAuthz() throws Exception { + void testInvalidTokenAuthz() throws Exception { Jwt token = Jwt.withTokenValue("test") .header("kid", "rsa1") .issuer(UNKNOWN_ISSUER) @@ -104,7 +104,7 @@ public void testInvalidTokenAuthz() throws Exception { } @Test - public void testValidLocalTokenAuthz() throws Exception { + void testValidLocalTokenAuthz() throws Exception { Jwt token = Jwt.withTokenValue("test") .header("kid", "rsa1") .issuer(LOCAL_ISSUER) @@ -123,7 +123,7 @@ public void testValidLocalTokenAuthz() throws Exception { } @Test - public void testInvalidPathLocalTokenAuthz() throws Exception { + void testInvalidPathLocalTokenAuthz() throws Exception { Jwt token = Jwt.withTokenValue("test") .header("kid", "rsa1") .issuer(LOCAL_ISSUER) @@ -139,7 +139,7 @@ public void testInvalidPathLocalTokenAuthz() throws Exception { } @Test - public void testInvalidLocalToken() throws Exception { + void testInvalidLocalToken() throws Exception { Jwt token = Jwt.withTokenValue("test") .header("kid", "rsa1") .issuer(LOCAL_ISSUER) diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/AuthzPdpTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/AuthzPdpTests.java index 04347431..e7bdf69e 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/AuthzPdpTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/AuthzPdpTests.java @@ -83,7 +83,7 @@ public void setup() { @Test - public void notApplicableWithEmptyPolicies() { + void notApplicableWithEmptyPolicies() { PathAuthorizationResult result = pdp.authorizeRequest(newAuthorizationRequest(request, authentication)); @@ -92,7 +92,7 @@ public void notApplicableWithEmptyPolicies() { @Test - public void denyPolicyApplied() { + void denyPolicyApplied() { PathAuthorizationPolicy denyAllPolicy = PathAuthorizationPolicy.builder() .withDeny() @@ -112,7 +112,7 @@ public void denyPolicyApplied() { } @Test - public void firstApplicablePolicyApplied() { + void firstApplicablePolicyApplied() { PathAuthorizationPolicy denyAllPolicy = PathAuthorizationPolicy.builder() .withDeny() @@ -138,7 +138,7 @@ public void firstApplicablePolicyApplied() { } @Test - public void oauthGroupHolderPolicyNotAppliedAsItDoesNotMatchPath() { + void oauthGroupHolderPolicyNotAppliedAsItDoesNotMatchPath() { PathAuthorizationPolicy oauthTestPolicy = PathAuthorizationPolicy.builder() .withPermit() @@ -164,7 +164,7 @@ public void oauthGroupHolderPolicyNotAppliedAsItDoesNotMatchPath() { } @Test - public void oauthGroupHolderPolicyNotAppliedDueToWrongGroup() { + void oauthGroupHolderPolicyNotAppliedDueToWrongGroup() { when(authentication.getAuthorities()) .thenReturn(authorities(new JwtGroupAuthority(TEST_ISSUER, "/test/subgroup"))); @@ -197,7 +197,7 @@ public void oauthGroupHolderPolicyNotAppliedDueToWrongGroup() { } @Test - public void oauthGroupHolderPolicyNotAppliedDueToWrongIssuer() { + void oauthGroupHolderPolicyNotAppliedDueToWrongIssuer() { when(authentication.getAuthorities()) .thenReturn(authorities(new JwtGroupAuthority(TEST2_ISSUER, "/test"))); @@ -228,7 +228,7 @@ public void oauthGroupHolderPolicyNotAppliedDueToWrongIssuer() { } @Test - public void oauthGroupHolderPolicyApplied() { + void oauthGroupHolderPolicyApplied() { when(request.getServletPath()).thenReturn("/test/file0"); when(request.getMethod()).thenReturn("GET"); @@ -260,7 +260,7 @@ public void oauthGroupHolderPolicyApplied() { } @Test - public void multiplePrincipalMatchersWorkAsExpected() { + void multiplePrincipalMatchersWorkAsExpected() { when(request.getServletPath()).thenReturn("/test/file0"); when(request.getMethod()).thenReturn("GET"); @@ -310,7 +310,7 @@ public void multiplePrincipalMatchersWorkAsExpected() { } @Test - public void multiplePathsMatchersWorkAsExpected() { + void multiplePathsMatchersWorkAsExpected() { when(request.getServletPath()).thenReturn("/test/file0"); when(request.getMethod()).thenReturn("GET"); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/LocalAuthzPdpTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/LocalAuthzPdpTests.java index 128e5ee3..3f082100 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/LocalAuthzPdpTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/LocalAuthzPdpTests.java @@ -100,7 +100,7 @@ public void setup() throws MalformedURLException { } @Test - public void noPathRaisesException() throws Exception { + void noPathRaisesException() { when(jwt.getClaimAsString("path")).thenReturn(null); Exception e = assertThrows(IllegalArgumentException.class, () -> { @@ -110,7 +110,7 @@ public void noPathRaisesException() throws Exception { } @Test - public void noPermsRaisesException() throws Exception { + void noPermsRaisesException() { when(jwt.getClaimAsString("perms")).thenReturn(null); Exception e = assertThrows(IllegalArgumentException.class, () -> { @@ -120,7 +120,7 @@ public void noPermsRaisesException() throws Exception { } @Test - public void pathMismatchYeldsDeny() throws Exception { + void pathMismatchYeldsDeny() { when(jwt.getClaimAsString("path")).thenReturn("/test/another"); PathAuthorizationResult result = @@ -130,7 +130,7 @@ public void pathMismatchYeldsDeny() throws Exception { } @Test - public void permMismatchYeldsDeny() throws Exception { + void permMismatchYeldsDeny() throws Exception { when(request.getMethod()).thenReturn("PUT"); PathAuthorizationResult result = @@ -140,7 +140,7 @@ public void permMismatchYeldsDeny() throws Exception { } @Test - public void originMismatchYeldsDeny() throws Exception { + void originMismatchYeldsDeny() { when(request.getRemoteAddr()).thenReturn(REMOTE_ADDR); when(jwt.getClaimAsString(ORIGIN_CLAIM)).thenReturn(ANOTHER_REMOTE_ADDR); @@ -151,7 +151,7 @@ public void originMismatchYeldsDeny() throws Exception { } @Test - public void testPermit() throws Exception { + void testPermit() throws Exception { PathAuthorizationResult result = pdp.authorizeRequest(newAuthorizationRequest(request, jwtAuth)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyParserTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyParserTests.java index 1fdf6d43..e65eec29 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyParserTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyParserTests.java @@ -43,7 +43,7 @@ import com.google.common.collect.Lists; @ExtendWith(MockitoExtension.class) -public class PolicyParserTests { +class PolicyParserTests { ServiceConfigurationProperties properties = new ServiceConfigurationProperties(); @@ -65,13 +65,13 @@ public void setup() { } @Test - public void testNoPolicyParsing() throws Exception { + void testNoPolicyParsing() throws Exception { assertThat(parser.parsePolicies(), empty()); } @Test - public void testSimplePolicyParsing() throws Exception { + void testSimplePolicyParsing() throws Exception { FineGrainedAuthzPolicyProperties.PrincipalProperties anonymous = new FineGrainedAuthzPolicyProperties.PrincipalProperties(); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyPropertiesValidationTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyPropertiesValidationTests.java index e2912024..31cfea4f 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyPropertiesValidationTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/pdp/PolicyPropertiesValidationTests.java @@ -42,7 +42,7 @@ import com.google.common.collect.Lists; @ExtendWith(MockitoExtension.class) -public class PolicyPropertiesValidationTests { +class PolicyPropertiesValidationTests { private Validator validator; @@ -69,7 +69,7 @@ public FineGrainedAuthzPolicyProperties minimalValidPolicy() { } @Test - public void testValidAuthzPolicyPassesValidation() throws Exception { + void testValidAuthzPolicyPassesValidation() throws Exception { FineGrainedAuthzPolicyProperties props = minimalValidPolicy(); @@ -81,7 +81,7 @@ public void testValidAuthzPolicyPassesValidation() throws Exception { } @Test - public void testDescriptionRequired() throws Exception { + void testDescriptionRequired() throws Exception { FineGrainedAuthzPolicyProperties props = minimalValidPolicy(); props.setDescription(null); @@ -96,7 +96,7 @@ public void testDescriptionRequired() throws Exception { } @Test - public void testSaRequired() throws Exception { + void testSaRequired() throws Exception { FineGrainedAuthzPolicyProperties props = minimalValidPolicy(); props.setSa(null); @@ -111,7 +111,7 @@ public void testSaRequired() throws Exception { } @Test - public void testPrincipalsNotEmpty() throws Exception { + void testPrincipalsNotEmpty() throws Exception { FineGrainedAuthzPolicyProperties props = minimalValidPolicy(); props.setPrincipals(emptyList()); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/PathResolverTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/PathResolverTests.java index 5031c0f1..cb11dfad 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/PathResolverTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/PathResolverTests.java @@ -36,7 +36,7 @@ public class PathResolverTests { - private final String ROOTDIR = "/storage"; + private static final String ROOTDIR = "/storage"; /* * Map SA-name -> VO name @@ -93,29 +93,29 @@ private StorageAreaInfo getMockSAInfo(String name, String voname) { } @Test - public void checkResolvedRootPath() { + void checkResolvedRootPath() { for (String name : input.keySet()) { String pathToTest = "/".concat(name).concat("/testdir"); String expectedRootPath = ROOTDIR.concat("/").concat(input.get(name)) .concat("/testdir"); - + String rootPath = pathResolver.resolvePath(pathToTest); Assert.assertEquals(expectedRootPath, rootPath); } } - + @Test - public void checkResolvedStorageArea() { + void checkResolvedStorageArea() { for (String name : input.keySet()) { String pathToTest = "/".concat(name).concat("/testdir"); String expectedRootPath = ROOTDIR.concat("/").concat(input.get(name)) .concat("/testdir"); - + StorageAreaInfo sa = pathResolver.resolveStorageArea(pathToTest); Assert.assertEquals(expectedRootPath, sa.rootPath() + "/testdir"); } diff --git a/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/VOMSMapTests.java b/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/VOMSMapTests.java index 9f59ef0c..e52d3974 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/VOMSMapTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/authz/vomap/VOMSMapTests.java @@ -24,18 +24,18 @@ public class VOMSMapTests { - public static final String mySubject = "CN=Andrea Ceccanti,L=CNAF,OU=Personal Certificate,O=INFN,C=IT"; + public static final String MY_SUBJECT = "CN=Andrea Ceccanti,L=CNAF,OU=Personal Certificate,O=INFN,C=IT"; @Test - public void VOMapParserTest() { + void VOMapParserTest() { - MapfileVOMembershipSource m = new MapfileVOMembershipSource("testers", + MapfileVOMembershipSource m = new MapfileVOMembershipSource("testers", new File("src/test/resources/vomsmap/testers.map")); - + Assert.assertEquals("testers",m.getVOName()); - Assert.assertTrue(m.getVOMembers().contains(mySubject)); - + Assert.assertTrue(m.getVOMembers().contains(MY_SUBJECT)); + Assert.assertFalse(m.getVOMembers().contains("CN=I am not Real, L=CNAF")); - + } } diff --git a/src/test/java/org/italiangrid/storm/webdav/test/checksum/ChecksumHelperTest.java b/src/test/java/org/italiangrid/storm/webdav/test/checksum/ChecksumHelperTest.java index 09c7287c..97d40ee8 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/checksum/ChecksumHelperTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/checksum/ChecksumHelperTest.java @@ -32,7 +32,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class ChecksumHelperTest { +class ChecksumHelperTest { private File testFile; private Adler32ChecksumInputStream cis; @@ -60,12 +60,12 @@ public void setup() throws IOException { } @AfterEach - public void finalize() throws IOException { + public void cleanup() throws IOException { cis.close(); } @Test - public void testGetChecksumValueFromFile() throws IOException { + void testGetChecksumValueFromFile() { String newChecksum = cis.getChecksumValue(); String oldChecksum = Long.toHexString(cis.getChecksum().getValue()); @@ -76,7 +76,7 @@ public void testGetChecksumValueFromFile() throws IOException { } @Test - public void testChecksumHelperAddLeadingZero() { + void testChecksumHelperAddLeadingZero() { final String CHECKSUM_VALUE = "abcdefgh"; assertEquals(CHECKSUM_VALUE, ChecksumHelper.addLeadingZero(CHECKSUM_VALUE, 8)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/macaroon/MacaroonRequestIntegrationTests.java b/src/test/java/org/italiangrid/storm/webdav/test/macaroon/MacaroonRequestIntegrationTests.java index c2c87b7d..5c85f963 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/macaroon/MacaroonRequestIntegrationTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/macaroon/MacaroonRequestIntegrationTests.java @@ -95,19 +95,19 @@ public MacaroonRequestIntegrationTests() { } @Test - public void getNotSupported() throws Exception { + void getNotSupported() throws Exception { mvc.perform(get("/whatever").contentType(MacaroonRequestFilter.MACAROON_REQUEST_CONTENT_TYPE)) .andExpect(status().isMethodNotAllowed()); } @Test - public void emptyRequestFails() throws Exception { + void emptyRequestFails() throws Exception { mvc.perform(post("/whatever").contentType(MacaroonRequestFilter.MACAROON_REQUEST_CONTENT_TYPE)) .andExpect(status().isBadRequest()); } @Test - public void vomsRequired() throws Exception { + void vomsRequired() throws Exception { mvc .perform(post("/whatever").contentType(MacaroonRequestFilter.MACAROON_REQUEST_CONTENT_TYPE) .content(EMPTY_JSON_OBJECT)) @@ -116,7 +116,7 @@ public void vomsRequired() throws Exception { @Test @WithMockVOMSUser - public void macaroonIssued() throws Exception { + void macaroonIssued() throws Exception { mvc .perform(post("/whatever").contentType(MacaroonRequestFilter.MACAROON_REQUEST_CONTENT_TYPE) .content(EMPTY_JSON_OBJECT)) @@ -127,7 +127,7 @@ public void macaroonIssued() throws Exception { @Test @WithMockVOMSUser(acExpirationSecs = 43200) - public void validityEnforced() throws Exception { + void validityEnforced() throws Exception { MacaroonRequestDTO dto = new MacaroonRequestDTO(); dto.setValidity("PT2H"); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/oauth/integration/OAuthAuthzServerIntegrationTests.java b/src/test/java/org/italiangrid/storm/webdav/test/oauth/integration/OAuthAuthzServerIntegrationTests.java index c1e8e6b6..41eaaac3 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/oauth/integration/OAuthAuthzServerIntegrationTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/oauth/integration/OAuthAuthzServerIntegrationTests.java @@ -93,27 +93,27 @@ public void setup() { } @Test - public void getNotSupported() throws Exception { + void getNotSupported() throws Exception { mvc.perform(get("/oauth/token").contentType(APPLICATION_FORM_URLENCODED)) .andExpect(status().isMethodNotAllowed()); } @Test - public void postNotSupportedForAnonymous() throws Exception { + void postNotSupportedForAnonymous() throws Exception { mvc.perform(post("/oauth/token").contentType(APPLICATION_FORM_URLENCODED)) .andExpect(status().isUnauthorized()); } @Test @WithMockUser(username = "test") - public void postNotSupportedForAuthenticatedNonVomsUsers() throws Exception { + void postNotSupportedForAuthenticatedNonVomsUsers() throws Exception { mvc.perform(post("/oauth/token").content(CONTENT).contentType(APPLICATION_FORM_URLENCODED)) .andExpect(status().isForbidden()); } @Test @WithMockVOMSUser(acExpirationSecs = 200) - public void postSupportedForAuthenticatedVomsUsers() throws Exception { + void postSupportedForAuthenticatedVomsUsers() throws Exception { mvc.perform(post("/oauth/token").content(CONTENT).contentType(APPLICATION_FORM_URLENCODED)) .andExpect(status().isOk()) .andExpect(jsonPath("$.access_token").exists()) @@ -123,7 +123,7 @@ public void postSupportedForAuthenticatedVomsUsers() throws Exception { @Test @WithMockVOMSUser - public void invalidGrantTypeRejected() throws Exception { + void invalidGrantTypeRejected() throws Exception { mvc .perform( post("/oauth/token").content(CONTENT_CUSTOM).contentType(APPLICATION_FORM_URLENCODED)) @@ -135,7 +135,7 @@ public void invalidGrantTypeRejected() throws Exception { @Test @WithMockVOMSUser - public void requestedLifetimeHonoured() throws Exception { + void requestedLifetimeHonoured() throws Exception { mvc .perform(post("/oauth/token").content(format("%s&lifetime=50", CONTENT)) .contentType(APPLICATION_FORM_URLENCODED)) @@ -147,7 +147,7 @@ public void requestedLifetimeHonoured() throws Exception { @Test @WithMockVOMSUser(acExpirationSecs = 200) - public void requestedLifetimeLimited() throws Exception { + void requestedLifetimeLimited() throws Exception { mvc .perform(post("/oauth/token").content(format("%s&lifetime=200000", CONTENT)) .contentType(APPLICATION_FORM_URLENCODED)) @@ -159,7 +159,7 @@ public void requestedLifetimeLimited() throws Exception { @Test @WithMockVOMSUser - public void scopeLengthIsChecked() throws Exception { + void scopeLengthIsChecked() throws Exception { String randomAlphabetic = randomAlphabetic(AccessTokenRequest.MAX_SCOPE_LENGTH); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/JwtIssuerTest.java b/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/JwtIssuerTest.java index 73a15f41..3ecd3946 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/JwtIssuerTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/JwtIssuerTest.java @@ -143,7 +143,7 @@ public void setup() { } @Test - public void canCreateSignedJWT() throws ParseException, JOSEException { + void canCreateSignedJWT() throws ParseException, JOSEException { SignedJWT jwt = issuer.createAccessToken(req, authn); assertThat(jwt, notNullValue()); @@ -162,7 +162,7 @@ public void canCreateSignedJWT() throws ParseException, JOSEException { @Test - public void returnsAuthoritiesAsExpected() throws ParseException { + void returnsAuthoritiesAsExpected() throws ParseException { SAPermission canReadTest = SAPermission.canRead("test"); SAPermission canWriteTest = SAPermission.canWrite("test"); @@ -184,7 +184,7 @@ public void returnsAuthoritiesAsExpected() throws ParseException { } @Test - public void tokenIssuerLimitsTokenValidityToAcLifetime() throws ParseException { + void tokenIssuerLimitsTokenValidityToAcLifetime() throws ParseException { SAPermission canReadTest = SAPermission.canRead("test"); SAPermission canWriteTest = SAPermission.canWrite("test"); @@ -201,7 +201,7 @@ public void tokenIssuerLimitsTokenValidityToAcLifetime() throws ParseException { } @Test - public void tokenIssuerLimitsTokenValidtyWithRequestedLifetime() throws ParseException { + void tokenIssuerLimitsTokenValidtyWithRequestedLifetime() throws ParseException { SAPermission canReadTest = SAPermission.canRead("test"); SAPermission canWriteTest = SAPermission.canWrite("test"); when(ps.getSAPermissions(authn)).thenReturn(Sets.newHashSet(canReadTest, canWriteTest)); @@ -218,7 +218,7 @@ public void tokenIssuerLimitsTokenValidtyWithRequestedLifetime() throws ParseExc @Test - public void tokenIssuerIgnoresRequestedLifetimeWhenExceedsInternalLimit() throws ParseException { + void tokenIssuerIgnoresRequestedLifetimeWhenExceedsInternalLimit() throws ParseException { SAPermission canReadTest = SAPermission.canRead("test"); SAPermission canWriteTest = SAPermission.canWrite("test"); when(ps.getSAPermissions(authn)).thenReturn(Sets.newHashSet(canReadTest, canWriteTest)); @@ -234,7 +234,7 @@ public void tokenIssuerIgnoresRequestedLifetimeWhenExceedsInternalLimit() throws } @Test - public void tokenIssuerCreatesResourceAccessToken() throws ParseException { + void tokenIssuerCreatesResourceAccessToken() throws ParseException { when(resourceAtRequest.getPath()).thenReturn("/example/resource"); when(resourceAtRequest.getPermission()).thenReturn(Permission.r); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/TokenServiceTest.java b/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/TokenServiceTest.java index 89fbdd8c..9a70ae63 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/TokenServiceTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/oauth/jwt/TokenServiceTest.java @@ -82,7 +82,7 @@ public void setup() throws ParseException { } @Test - public void canGenerateTokenResponse() { + void canGenerateTokenResponse() { TokenResponseDTO response = issuerService.createAccessToken(request, auth); assertThat(response.getTokenType(), is(BEARER_TOKEN_TYPE)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/oauth/validator/AudienceValidatorTests.java b/src/test/java/org/italiangrid/storm/webdav/test/oauth/validator/AudienceValidatorTests.java index 39159bb5..c0e8419d 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/oauth/validator/AudienceValidatorTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/oauth/validator/AudienceValidatorTests.java @@ -35,7 +35,7 @@ import com.google.common.collect.Lists; @ExtendWith(MockitoExtension.class) -public class AudienceValidatorTests { +class AudienceValidatorTests { @Mock AuthorizationServer server; @@ -52,7 +52,7 @@ public void setup() { } @Test - public void testNullAudiences() { + void testNullAudiences() { when(server.getAudiences()).thenReturn(null); assertThrows(IllegalArgumentException.class, () -> { validator = new AudienceValidator(server); @@ -60,7 +60,7 @@ public void testNullAudiences() { } @Test - public void testEmptyAudiences() { + void testEmptyAudiences() { when(server.getAudiences()).thenReturn(emptyList()); assertThrows(IllegalArgumentException.class, () -> { validator = new AudienceValidator(server); @@ -68,28 +68,28 @@ public void testEmptyAudiences() { } @Test - public void testNoAudienceInTokenYeldsSuccess() { + void testNoAudienceInTokenYeldsSuccess() { when(jwt.getAudience()).thenReturn(null); validator = new AudienceValidator(server); assertThat(validator.validate(jwt).hasErrors(), is(false)); } @Test - public void testEmptyAudienceInTokenYeldsSuccess() { + void testEmptyAudienceInTokenYeldsSuccess() { when(jwt.getAudience()).thenReturn(emptyList()); validator = new AudienceValidator(server); assertThat(validator.validate(jwt).hasErrors(), is(false)); } @Test - public void testInvalidAudienceIsError() { + void testInvalidAudienceIsError() { when(jwt.getAudience()).thenReturn(Lists.newArrayList("testAudience")); validator = new AudienceValidator(server); assertThat(validator.validate(jwt).hasErrors(), is(true)); } @Test - public void testAudienceValidationSuccess() { + void testAudienceValidationSuccess() { when(jwt.getAudience()).thenReturn(Lists.newArrayList("any")); validator = new AudienceValidator(server); assertThat(validator.validate(jwt).hasErrors(), is(false)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RandomReplicaSelectorTests.java b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RandomReplicaSelectorTests.java index 1c0cb171..5407e143 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RandomReplicaSelectorTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RandomReplicaSelectorTests.java @@ -32,7 +32,7 @@ import com.google.common.collect.Sets; @RunWith(MockitoJUnitRunner.class) -public class RandomReplicaSelectorTests extends RedirectorTestSupport { +class RandomReplicaSelectorTests extends RedirectorTestSupport { ServiceConfigurationProperties config; RandomReplicaSelector selector; @@ -44,14 +44,14 @@ public void setup() { } @Test - public void testEmptyOptionalOnEmptyEndpointList() { + void testEmptyOptionalOnEmptyEndpointList() { assertThat(selector.selectReplica().isPresent(), is(false)); } @Test - public void testSingleEndpointList() { + void testSingleEndpointList() { ReplicaEndpointProperties replica = new ReplicaEndpointProperties(); replica.setEndpoint(ENDPOINT_URI_0); @@ -65,7 +65,7 @@ public void testSingleEndpointList() { @Test - public void testDoubleEndpointList() { + void testDoubleEndpointList() { ReplicaEndpointProperties replica0 = new ReplicaEndpointProperties(); replica0.setEndpoint(ENDPOINT_URI_0); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectFilterTests.java b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectFilterTests.java index 10110200..ec96bbc7 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectFilterTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectFilterTests.java @@ -94,7 +94,7 @@ public void setup() { } @Test - public void filterIgnoresPlainHttpRequests() throws IOException, ServletException { + void filterIgnoresPlainHttpRequests() throws IOException, ServletException { when(request.getScheme()).thenReturn("http"); filter.doFilter(request, response, filterChain); @@ -104,7 +104,7 @@ public void filterIgnoresPlainHttpRequests() throws IOException, ServletExceptio } @Test - public void filterIgnoresPlainDavRequests() throws IOException, ServletException { + void filterIgnoresPlainDavRequests() throws IOException, ServletException { when(request.getScheme()).thenReturn("dav"); filter.doFilter(request, response, filterChain); @@ -114,7 +114,7 @@ public void filterIgnoresPlainDavRequests() throws IOException, ServletException } @Test - public void filterIgnoresRequestWithAccessToken() throws IOException, ServletException { + void filterIgnoresRequestWithAccessToken() throws IOException, ServletException { when(request.getParameter("access_token")).thenReturn(RANDOM_TOKEN_STRING); filter.doFilter(request, response, filterChain); @@ -124,7 +124,7 @@ public void filterIgnoresRequestWithAccessToken() throws IOException, ServletExc } @Test - public void filterIgnoresRequestWithNoRedirect() throws IOException, ServletException { + void filterIgnoresRequestWithNoRedirect() throws IOException, ServletException { Map parameterMap = Maps.newHashMap(); parameterMap.put("no_redirect", new String[] {}); @@ -137,7 +137,7 @@ public void filterIgnoresRequestWithNoRedirect() throws IOException, ServletExce } @Test - public void filterIgnoresDirectoryRequest() throws IOException, ServletException { + void filterIgnoresDirectoryRequest() throws IOException, ServletException { when(file.isFile()).thenReturn(false); @@ -148,7 +148,7 @@ public void filterIgnoresDirectoryRequest() throws IOException, ServletException } @Test - public void filterIgnoresResourceNotFound() throws IOException, ServletException { + void filterIgnoresResourceNotFound() throws IOException, ServletException { when(pathResolver.getPath("/example/file")).thenReturn(null); @@ -159,13 +159,13 @@ public void filterIgnoresResourceNotFound() throws IOException, ServletException } @Test - public void filterSendsRedirect() throws IOException, ServletException { + void filterSendsRedirect() throws IOException, ServletException { filter.doFilter(request, response, filterChain); verify(redirectionService).buildRedirect(Mockito.any(), Mockito.eq(request), Mockito.eq(response)); - verify(response).setStatus(Mockito.eq(SC_TEMPORARY_REDIRECT)); + verify(response).setStatus(SC_TEMPORARY_REDIRECT); verify(response).setHeader(Mockito.eq("Location"), redirectUrl.capture()); assertThat(redirectUrl.getValue(), is(REDIRECTED_URL)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectionServiceTests.java b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectionServiceTests.java index 788f1781..6f7d4489 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectionServiceTests.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/redirector/RedirectionServiceTests.java @@ -49,7 +49,7 @@ import com.nimbusds.jwt.SignedJWT; @ExtendWith(MockitoExtension.class) -public class RedirectionServiceTests extends RedirectorTestSupport { +class RedirectionServiceTests extends RedirectorTestSupport { @Mock @@ -91,7 +91,7 @@ public void setup() { @Test - public void testRedirectFailureOnEmptyReplica() { + void testRedirectFailureOnEmptyReplica() { Exception e = assertThrows(RedirectError.class, () -> { service.buildRedirect(authentication, request, response); @@ -100,7 +100,7 @@ public void testRedirectFailureOnEmptyReplica() { } @Test - public void testRedirectUriConstruction() { + void testRedirectUriConstruction() { when(selector.selectReplica()).thenReturn(Optional.of(REPLICA_0)); String uriString = service.buildRedirect(authentication, request, response); @@ -121,7 +121,7 @@ public void testRedirectUriConstruction() { } @Test - public void testPutRedirectUriConstruction() { + void testPutRedirectUriConstruction() { when(selector.selectReplica()).thenReturn(Optional.of(REPLICA_0)); when(request.getMethod()).thenReturn("PUT"); @@ -143,7 +143,7 @@ public void testPutRedirectUriConstruction() { } @Test - public void testRedirectUriWithPrefixConstruction() { + void testRedirectUriWithPrefixConstruction() { when(selector.selectReplica()).thenReturn(Optional.of(REPLICA_WITH_PREFIX)); String uriString = service.buildRedirect(authentication, request, response); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/ClientInfoParserTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/ClientInfoParserTest.java index 35afedc9..85aac3e2 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/ClientInfoParserTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/ClientInfoParserTest.java @@ -24,10 +24,10 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class ClientInfoParserTest { +class ClientInfoParserTest { @Test - public void testClientInfoHeaderParsing() { + void testClientInfoHeaderParsing() { ClientInfo ci = ClientInfo .fromHeaderString("job-id=34f98a5e-1e49-11e9-ab17-fa163edecedf;file-id=8764139989;retry=0"); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/PullTransferTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/PullTransferTest.java index 1eaee85c..09527a6a 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/PullTransferTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/PullTransferTest.java @@ -35,25 +35,27 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import com.google.common.collect.Multimap; @ExtendWith(MockitoExtension.class) -public class PullTransferTest extends TransferFilterTestSupport { +class PullTransferTest extends TransferFilterTestSupport { + @Override @BeforeEach public void setup() throws IOException { super.setup(); lenient().when(request.getMethod()).thenReturn(COPY.name()); lenient().when(request.getServletPath()).thenReturn(SERVLET_PATH); lenient().when(request.getPathInfo()).thenReturn(LOCAL_PATH); - lenient().when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); - lenient().when(request.getHeader(OVERWRITE_HEADER)).thenReturn(null); - lenient().when(request.getHeader(DESTINATION_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CLIENT_INFO_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CREDENTIAL_HEADER)).thenReturn(null); - lenient().when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); + lenient().when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CLIENT_INFO_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CREDENTIAL_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn(null); lenient().when(request.getHeaderNames()).thenReturn(emptyEnumeration()); lenient().when(resolver.pathExists(FULL_LOCAL_PATH)).thenReturn(false); lenient().when(resolver.pathExists(FULL_LOCAL_PATH_PARENT)).thenReturn(true); @@ -73,7 +75,7 @@ void pullEmptyTransferHeaders() throws IOException, ServletException { @Test void overwriteHeaderRecognized() throws IOException, ServletException { - when(request.getHeader(OVERWRITE_HEADER)).thenReturn("F"); + when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn("F"); filter.doFilter(request, response, chain); verify(client).handle(getXferRequest.capture(), Mockito.any()); assertThat(getXferRequest.getValue().path(), is(FULL_LOCAL_PATH)); @@ -86,7 +88,7 @@ void overwriteHeaderRecognized() throws IOException, ServletException { @Test void checksumRecognized() throws IOException, ServletException { - when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn("false"); + when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn("false"); filter.doFilter(request, response, chain); verify(client).handle(getXferRequest.capture(), Mockito.any()); assertThat(getXferRequest.getValue().path(), is(FULL_LOCAL_PATH)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/PushTransferTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/PushTransferTest.java index 6569e33a..8806e50c 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/PushTransferTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/PushTransferTest.java @@ -37,27 +37,29 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import com.google.common.collect.Multimap; @ExtendWith(MockitoExtension.class) -public class PushTransferTest extends TransferFilterTestSupport { +class PushTransferTest extends TransferFilterTestSupport { + @Override @BeforeEach public void setup() throws IOException { super.setup(); lenient().when(request.getMethod()).thenReturn(COPY.name()); lenient().when(request.getServletPath()).thenReturn(SERVLET_PATH); lenient().when(request.getPathInfo()).thenReturn(LOCAL_PATH); - lenient().when(request.getHeader(DESTINATION_HEADER)).thenReturn(HTTPS_URL); + lenient().when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(HTTPS_URL); lenient().when(request.getHeaderNames()).thenReturn(emptyEnumeration()); lenient().when(resolver.pathExists(FULL_LOCAL_PATH)).thenReturn(true); - lenient().when(request.getHeader(SOURCE_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CLIENT_INFO_HEADER)).thenReturn(null); - lenient().when(request.getHeader(OVERWRITE_HEADER)).thenReturn(null); - lenient().when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CREDENTIAL_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CLIENT_INFO_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CREDENTIAL_HEADER)).thenReturn(null); } @@ -81,7 +83,7 @@ void pushEmptyTransferHeaders() throws IOException, ServletException { @Test void overwriteHeaderRecognized() throws IOException, ServletException { - when(request.getHeader(OVERWRITE_HEADER)).thenReturn("F"); + when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn("F"); filter.doFilter(request, response, chain); verify(client).handle(putXferRequest.capture(), Mockito.any()); assertThat(putXferRequest.getValue().path(), is(FULL_LOCAL_PATH)); @@ -94,7 +96,7 @@ void overwriteHeaderRecognized() throws IOException, ServletException { @Test void checksumRecognized() throws IOException, ServletException { - when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn("false"); + when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn("false"); filter.doFilter(request, response, chain); verify(client).handle(putXferRequest.capture(), Mockito.any()); assertThat(putXferRequest.getValue().path(), is(FULL_LOCAL_PATH)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/SciTagFilterActivationTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/SciTagFilterActivationTest.java index 4a87ae05..51e587c9 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/SciTagFilterActivationTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/SciTagFilterActivationTest.java @@ -39,6 +39,7 @@ import org.italiangrid.storm.webdav.server.servlet.SciTagFilter; import org.italiangrid.storm.webdav.scitag.SciTag; import org.italiangrid.storm.webdav.scitag.SciTagTransfer; +import org.italiangrid.storm.webdav.tpc.TransferConstants; @ExtendWith(MockitoExtension.class) class SciTagFilterActivationTest extends TransferFilterTestSupport { @@ -64,7 +65,7 @@ public void setup() throws IOException { lenient().when(resolver.resolveStorageArea(FULL_LOCAL_PATH)).thenReturn(testSa); lenient().when(resolver.resolveStorageArea("/test/otherfile")).thenReturn(testSa); lenient().when(resolver.resolveStorageArea("/other/file")).thenReturn(otherSa); - lenient().when(request.getHeader(SOURCE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(null); } @Test diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterActivationTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterActivationTest.java index 7fea4844..b7b9a3a0 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterActivationTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterActivationTest.java @@ -31,6 +31,7 @@ import org.italiangrid.storm.webdav.config.StorageAreaInfo; import org.italiangrid.storm.webdav.server.servlet.WebDAVMethod; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -39,7 +40,7 @@ import org.springframework.http.HttpMethod; @ExtendWith(MockitoExtension.class) -public class TransferFilterActivationTest extends TransferFilterTestSupport { +class TransferFilterActivationTest extends TransferFilterTestSupport { @Mock StorageAreaInfo testSa; @@ -47,6 +48,7 @@ public class TransferFilterActivationTest extends TransferFilterTestSupport { @Mock StorageAreaInfo otherSa; + @Override @BeforeEach public void setup() throws IOException { super.setup(); @@ -56,11 +58,11 @@ public void setup() throws IOException { lenient().when(resolver.resolveStorageArea(FULL_LOCAL_PATH)).thenReturn(testSa); lenient().when(resolver.resolveStorageArea("/test/otherfile")).thenReturn(testSa); lenient().when(resolver.resolveStorageArea("/other/file")).thenReturn(otherSa); - lenient().when(request.getHeader(SOURCE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(null); } @Test - public void filterIgnoresOtherHttpOrWebdavMethods() throws IOException, ServletException { + void filterIgnoresOtherHttpOrWebdavMethods() throws IOException, ServletException { // Ignore Http methods for (HttpMethod m : HttpMethod.values()) { when(request.getMethod()).thenReturn(m.toString()); @@ -80,12 +82,12 @@ public void filterIgnoresOtherHttpOrWebdavMethods() throws IOException, ServletE } @Test - public void filterSkippedIfSourceAndDestionationHeaderMissing() + void filterSkippedIfSourceAndDestionationHeaderMissing() throws IOException, ServletException { // No source or destination header - when(request.getHeader(SOURCE_HEADER)).thenReturn(null); - when(request.getHeader(DESTINATION_HEADER)).thenReturn(null); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(null); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(null); when(request.getMethod()).thenReturn(COPY.toString()); filter.doFilter(request, response, chain); @@ -93,9 +95,10 @@ public void filterSkippedIfSourceAndDestionationHeaderMissing() } @Test - public void filterBlocksLocalCopyAcrossStorageAreas() throws IOException, ServletException { + void filterBlocksLocalCopyAcrossStorageAreas() throws IOException, ServletException { when(request.getMethod()).thenReturn(COPY.toString()); - when(request.getHeader(DESTINATION_HEADER)).thenReturn("https://localhost/other/file"); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)) + .thenReturn("https://localhost/other/file"); filter.doFilter(request, response, chain); verify(responseWriter).print(error.capture()); assertThat(error.getValue(), is("Local copy across storage areas is not supported")); @@ -103,19 +106,21 @@ public void filterBlocksLocalCopyAcrossStorageAreas() throws IOException, Servle } @Test - public void filterIgnoresLocalCopyInSameStorageArea() throws IOException, ServletException { + void filterIgnoresLocalCopyInSameStorageArea() throws IOException, ServletException { when(request.getMethod()).thenReturn(COPY.toString()); - when(request.getHeader(DESTINATION_HEADER)).thenReturn("https://localhost/test/otherfile"); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)) + .thenReturn("https://localhost/test/otherfile"); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); } @Test - public void filterHandlesLocalCopyWithTransferHeader() throws IOException, ServletException { + void filterHandlesLocalCopyWithTransferHeader() throws IOException, ServletException { when(request.getMethod()).thenReturn(COPY.toString()); - when(request.getHeader(DESTINATION_HEADER)).thenReturn("https://localhost/test/otherfile"); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)) + .thenReturn("https://localhost/test/otherfile"); when(requestHeaderNames.hasMoreElements()).thenReturn(true, true, false); - when(requestHeaderNames.nextElement()).thenReturn(DESTINATION_HEADER, + when(requestHeaderNames.nextElement()).thenReturn(TransferConstants.DESTINATION_HEADER, TRANSFER_HEADER_AUTHORIZATION_KEY); filter.doFilter(request, response, chain); @@ -123,17 +128,17 @@ public void filterHandlesLocalCopyWithTransferHeader() throws IOException, Servl } @Test - public void filterHandlesRemoteSourceHeader() throws IOException, ServletException { + void filterHandlesRemoteSourceHeader() throws IOException, ServletException { when(request.getMethod()).thenReturn(COPY.toString()); - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); filter.doFilter(request, response, chain); verifyNoInteractions(chain); } @Test - public void filterHandlesRemoteDestinationHeader() throws IOException, ServletException { + void filterHandlesRemoteDestinationHeader() throws IOException, ServletException { when(request.getMethod()).thenReturn(COPY.toString()); - when(request.getHeader(DESTINATION_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(HTTP_URL); filter.doFilter(request, response, chain); verifyNoInteractions(chain); } diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterTestSupport.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterTestSupport.java index 6733e0e5..6f81b5c1 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterTestSupport.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferFilterTestSupport.java @@ -33,7 +33,6 @@ import org.italiangrid.storm.webdav.server.PathResolver; import org.italiangrid.storm.webdav.tpc.LocalURLService; import org.italiangrid.storm.webdav.tpc.StaticHostListLocalURLService; -import org.italiangrid.storm.webdav.tpc.TransferConstants; import org.italiangrid.storm.webdav.tpc.TransferFilter; import org.italiangrid.storm.webdav.tpc.transfer.GetTransferRequest; import org.italiangrid.storm.webdav.tpc.transfer.PutTransferRequest; @@ -42,7 +41,7 @@ import org.mockito.Captor; import org.mockito.Mock; -public class TransferFilterTestSupport implements TransferConstants { +public class TransferFilterTestSupport { public static final Instant NOW = Instant.parse("2021-01-01T00:00:00.00Z"); @@ -74,7 +73,7 @@ public class TransferFilterTestSupport implements TransferConstants { public static final URI HTTP_URL_URI = URI.create(HTTP_URL); public static final URI HTTPS_URL_URI = URI.create(HTTPS_URL); - public static String[] INVALID_URLs = + public static final String[] INVALID_URLs = {"http:whatever", "httpg://storm.example/test", "gsiftp://whatever/test"}; public static final String EXPECTED_HEADER = org.apache.http.protocol.HTTP.EXPECT_DIRECTIVE; diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferRequestValidationTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferRequestValidationTest.java index e4b8786a..619e7782 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferRequestValidationTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferRequestValidationTest.java @@ -36,10 +36,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; +import org.italiangrid.storm.webdav.tpc.TransferConstants; @ExtendWith(MockitoExtension.class) -public class TransferRequestValidationTest extends TransferFilterTestSupport { +class TransferRequestValidationTest extends TransferFilterTestSupport { + @Override @BeforeEach public void setup() throws IOException { super.setup(); @@ -49,18 +51,18 @@ public void setup() throws IOException { lenient().when(request.getHeaderNames()).thenReturn(emptyEnumeration()); lenient().when(resolver.pathExists(FULL_LOCAL_PATH)).thenReturn(false); lenient().when(resolver.pathExists(FULL_LOCAL_PATH_PARENT)).thenReturn(true); - lenient().when(request.getHeader(SOURCE_HEADER)).thenReturn(null); - lenient().when(request.getHeader(OVERWRITE_HEADER)).thenReturn(null); - lenient().when(request.getHeader(DESTINATION_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CLIENT_INFO_HEADER)).thenReturn(null); - lenient().when(request.getHeader(CREDENTIAL_HEADER)).thenReturn(null); - lenient().when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CLIENT_INFO_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.CREDENTIAL_HEADER)).thenReturn(null); + lenient().when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn(null); } @Test - public void sourceAndDestHeaderPresent() throws IOException, ServletException { - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); - when(request.getHeader(DESTINATION_HEADER)).thenReturn(HTTP_URL); + void sourceAndDestHeaderPresent() throws IOException, ServletException { + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(HTTP_URL); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); @@ -69,9 +71,9 @@ public void sourceAndDestHeaderPresent() throws IOException, ServletException { } @Test - public void invalidDestinationURIs() throws IOException, ServletException { + void invalidDestinationURIs() throws IOException, ServletException { for (String u : INVALID_URLs) { - when(request.getHeader(DESTINATION_HEADER)).thenReturn(u); + when(request.getHeader(TransferConstants.DESTINATION_HEADER)).thenReturn(u); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); assertThat(httpStatus.getValue(), is(BAD_REQUEST.value())); @@ -82,9 +84,9 @@ public void invalidDestinationURIs() throws IOException, ServletException { @Test - public void invalidSourceURIs() throws IOException, ServletException { + void invalidSourceURIs() throws IOException, ServletException { for (String u : INVALID_URLs) { - when(request.getHeader(SOURCE_HEADER)).thenReturn(u); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(u); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); assertThat(httpStatus.getValue(), is(BAD_REQUEST.value())); @@ -94,14 +96,14 @@ public void invalidSourceURIs() throws IOException, ServletException { } @Test - public void invalidOverwriteHeader() throws IOException, ServletException { + void invalidOverwriteHeader() throws IOException, ServletException { String[] invalidValues = {"", "cccc", "whatever", "true", "false"}; - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); for (String s : invalidValues) { - when(request.getHeader(OVERWRITE_HEADER)).thenReturn(s); + when(request.getHeader(TransferConstants.OVERWRITE_HEADER)).thenReturn(s); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); assertThat(httpStatus.getValue(), is(BAD_REQUEST.value())); @@ -111,12 +113,12 @@ public void invalidOverwriteHeader() throws IOException, ServletException { } @Test - public void invalidRequireChecksumHeader() throws IOException, ServletException { + void invalidRequireChecksumHeader() throws IOException, ServletException { String[] invalidValues = {"t", "F", ""}; - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); for (String s : invalidValues) { - when(request.getHeader(REQUIRE_CHECKSUM_HEADER)).thenReturn(s); + when(request.getHeader(TransferConstants.REQUIRE_CHECKSUM_HEADER)).thenReturn(s); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); assertThat(httpStatus.getValue(), is(BAD_REQUEST.value())); @@ -126,8 +128,8 @@ public void invalidRequireChecksumHeader() throws IOException, ServletException } @Test - public void emptyOrNullPathInfo() throws IOException, ServletException { - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); + void emptyOrNullPathInfo() throws IOException, ServletException { + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); String[] invalidPathInfos = {null, "", "does/not/start/with/slash"}; String[] expectedErrorMsgs = {"Null or empty", "Null or empty", "Invalid local path"}; @@ -145,9 +147,9 @@ public void emptyOrNullPathInfo() throws IOException, ServletException { } @Test - public void invalidCredentialHeader() throws IOException, ServletException { - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); - when(request.getHeader(CREDENTIAL_HEADER)).thenReturn("gridsite"); + void invalidCredentialHeader() throws IOException, ServletException { + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.CREDENTIAL_HEADER)).thenReturn("gridsite"); filter.doFilter(request, response, chain); verify(response).sendError(httpStatus.capture(), error.capture()); assertThat(httpStatus.getValue(), is(SC_BAD_REQUEST)); @@ -155,9 +157,9 @@ public void invalidCredentialHeader() throws IOException, ServletException { } @Test - public void noneCredentialHeaderAccepted() throws IOException, ServletException { - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); - when(request.getHeader(CREDENTIAL_HEADER)).thenReturn("none"); + void noneCredentialHeaderAccepted() throws IOException, ServletException { + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.CREDENTIAL_HEADER)).thenReturn("none"); filter.doFilter(request, response, chain); verify(response).setStatus(httpStatus.capture()); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferReturnStatusTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferReturnStatusTest.java index 22bd4478..b54b1bac 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferReturnStatusTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferReturnStatusTest.java @@ -31,6 +31,7 @@ import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpResponseException; +import org.italiangrid.storm.webdav.tpc.TransferConstants; import org.italiangrid.storm.webdav.tpc.transfer.GetTransferRequest; import org.italiangrid.storm.webdav.tpc.transfer.error.ChecksumVerificationError; import org.italiangrid.storm.webdav.tpc.transfer.error.TransferError; @@ -42,28 +43,29 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class TransferReturnStatusTest extends TransferFilterTestSupport { +class TransferReturnStatusTest extends TransferFilterTestSupport { + @Override @BeforeEach public void setup() throws IOException { super.setup(); when(request.getMethod()).thenReturn(COPY.name()); when(request.getServletPath()).thenReturn(SERVLET_PATH); when(request.getPathInfo()).thenReturn(LOCAL_PATH); - when(request.getHeader(SOURCE_HEADER)).thenReturn(HTTP_URL); + when(request.getHeader(TransferConstants.SOURCE_HEADER)).thenReturn(HTTP_URL); when(request.getHeaderNames()).thenReturn(emptyEnumeration()); when(resolver.pathExists(FULL_LOCAL_PATH_PARENT)).thenReturn(true); } @Test - public void filterAnswers202() throws IOException, ServletException { + void filterAnswers202() throws IOException, ServletException { filter.doFilter(request, response, chain); verify(response).setStatus(httpStatus.capture()); assertThat(httpStatus.getValue(), is(SC_ACCEPTED)); } @Test - public void filterAnswers412ForClientProtocolException() throws IOException, ServletException { + void filterAnswers412ForClientProtocolException() throws IOException, ServletException { Mockito.doThrow(new ClientProtocolException("Connection error")) .when(client) .handle(ArgumentMatchers.any(), ArgumentMatchers.any()); @@ -75,7 +77,7 @@ public void filterAnswers412ForClientProtocolException() throws IOException, Ser } @Test - public void filterAnswers412ForHttpExceptionError() throws IOException, ServletException { + void filterAnswers412ForHttpExceptionError() throws IOException, ServletException { Mockito.doThrow(new HttpResponseException(HttpServletResponse.SC_FORBIDDEN, "Access denied")) .when(client) .handle(ArgumentMatchers.any(), ArgumentMatchers.any()); @@ -88,7 +90,7 @@ public void filterAnswers412ForHttpExceptionError() throws IOException, ServletE } @Test - public void filterAnswers412ForChecksumVerificationError() throws IOException, ServletException { + void filterAnswers412ForChecksumVerificationError() throws IOException, ServletException { Mockito.doThrow(new ChecksumVerificationError("Checksum verification error")) .when(client) .handle(ArgumentMatchers.any(), ArgumentMatchers.any()); @@ -100,7 +102,7 @@ public void filterAnswers412ForChecksumVerificationError() throws IOException, S } @Test - public void filterAnswers412ForGenericTransferError() throws IOException, ServletException { + void filterAnswers412ForGenericTransferError() throws IOException, ServletException { Mockito.doThrow(new TransferError("Error")) .when(client) .handle(ArgumentMatchers.any(), ArgumentMatchers.any()); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferStatsTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferStatsTest.java index c0e3a6d0..f602a5e7 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferStatsTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/TransferStatsTest.java @@ -40,7 +40,7 @@ public class TransferStatsTest { TransferStatus.Builder status = TransferStatus.builder(clock); @Test - public void testByteCountPull() { + void testByteCountPull() { GetTransferRequest req = GetTransferRequestBuilder.create().build(); @@ -57,7 +57,7 @@ public void testByteCountPull() { } @Test - public void testOneMsecByteCountPull() { + void testOneMsecByteCountPull() { GetTransferRequest req = GetTransferRequestBuilder.create().build(); req.setTransferStatus(status.inProgress(0)); @@ -72,7 +72,7 @@ public void testOneMsecByteCountPull() { } @Test - public void testHalfMsecByteCountPull() { + void testHalfMsecByteCountPull() { GetTransferRequest req = GetTransferRequestBuilder.create().build(); req.setTransferStatus(status.inProgress(0)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/ClientTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/ClientTest.java index 353df6ba..efd8b40b 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/ClientTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/ClientTest.java @@ -42,12 +42,13 @@ import com.google.common.collect.ArrayListMultimap; @ExtendWith(MockitoExtension.class) -public class ClientTest extends ClientTestSupport { +class ClientTest extends ClientTestSupport { @TempDir public File storage; @SuppressWarnings("unchecked") + @Override @BeforeEach public void setup() throws IOException { @@ -69,7 +70,7 @@ public void setup() throws IOException { } @Test - public void testClientCorrectlyBuildsHttpRequestNoHeaders() throws IOException { + void testClientCorrectlyBuildsHttpRequestNoHeaders() throws IOException { client.handle(req, (r, s) -> { }); @@ -86,7 +87,7 @@ public void testClientCorrectlyBuildsHttpRequestNoHeaders() throws IOException { } @Test - public void testClientCorrectlyBuildsHttpRequestWithHeaders() throws IOException { + void testClientCorrectlyBuildsHttpRequestWithHeaders() throws IOException { when(req.transferHeaders()).thenReturn(HEADER_MAP); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/DigestTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/DigestTest.java index 5007bf71..5ace7612 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/DigestTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/DigestTest.java @@ -37,7 +37,7 @@ public class DigestTest { @Mock Header header; - public static String[] INVALID_HEADERS = + public static final String[] INVALID_HEADERS = {"", "adler54=1233456", "adler32=8a23d4f889", "sha256:437648", null}; public static final String[] VALID_HEADERS = @@ -51,7 +51,7 @@ protected void instrumentResponse(String headerValue) { } @Test - public void testInvalidHeader() { + void testInvalidHeader() { for (String s : INVALID_HEADERS) { instrumentResponse(s); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/GetResponseHandlerTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/GetResponseHandlerTest.java index 257b060c..498be64d 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/GetResponseHandlerTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/GetResponseHandlerTest.java @@ -36,36 +36,37 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class GetResponseHandlerTest extends ClientTestSupport { +class GetResponseHandlerTest extends ClientTestSupport { @Mock StatusLine status; - + @Mock HttpEntity entity; - + @Mock HttpResponse response; - + @Mock StormCountingOutputStream os; - + GetResponseHandler handler; + @Override @BeforeEach public void setup() { - + handler = new GetResponseHandler(null, os, eah); lenient().when(response.getStatusLine()).thenReturn(status); lenient().when(response.getEntity()).thenReturn(entity); } - + @Test - public void handlerWritesToStream() throws IOException { + void handlerWritesToStream() throws IOException { when(status.getStatusCode()).thenReturn(200); - + handler.handleResponse(response); - + verify(entity).getContent(); verify(eah).setChecksumAttribute(ArgumentMatchers.any(), any()); } diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcClientRedirectionTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcClientRedirectionTest.java index 498084a4..33e51df0 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcClientRedirectionTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcClientRedirectionTest.java @@ -21,13 +21,7 @@ import static org.mockserver.model.NottableString.not; import static org.mockserver.verify.VerificationTimes.exactly; -import java.io.IOException; import java.net.URI; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.cert.CertificateException; import java.util.UUID; import javax.net.ssl.SSLContext; @@ -93,8 +87,7 @@ public static class TestConfig { @Bean("tpcConnectionManager") @Primary public HttpClientConnectionManager tpcClientConnectionManager(ThirdPartyCopyProperties props, - ServiceConfiguration conf) throws KeyStoreException, CertificateException, IOException, - NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { + ServiceConfiguration conf) { SSLContext ctx = KeyStoreFactory.keyStoreFactory().sslContext(); ConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory(); @@ -144,7 +137,7 @@ private String mockHttpUrl(String path) { } @Test - public void handleCrossProtocolRedirectionCorrectly() { + void handleCrossProtocolRedirectionCorrectly() { Multimap headers = ArrayListMultimap.create(); headers.put("Authorization", "Bearer this-is-a-fake-token"); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcIntegrationTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcIntegrationTest.java index ca1fba9f..9c8d8e86 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcIntegrationTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/http/integration/TpcIntegrationTest.java @@ -23,7 +23,7 @@ import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.NottableString.not; import static org.mockserver.verify.VerificationTimes.exactly; -import static org.springframework.util.SocketUtils.findAvailableTcpPort; +import static org.springframework.test.util.TestSocketUtils.findAvailableTcpPort; import java.net.URI; import java.util.UUID; @@ -70,7 +70,7 @@ public class TpcIntegrationTest { @BeforeAll public static void startMockServer() { - port = findAvailableTcpPort(15000); + port = findAvailableTcpPort(); mockServer = startClientAndServer(port); } @@ -89,7 +89,7 @@ private String mockUrl(String path) { } @Test - public void testPutRedirectHandled() { + void testPutRedirectHandled() { Multimap emptyHeaders = ArrayListMultimap.create(); PutTransferRequest putRequest = new PutTransferRequestImpl(UUID.randomUUID().toString(), @@ -118,7 +118,7 @@ public void testPutRedirectHandled() { } @Test - public void testAuthorizationHeaderIsDroppedOnRedirectForPut() { + void testAuthorizationHeaderIsDroppedOnRedirectForPut() { Multimap headers = ArrayListMultimap.create(); headers.put("Authorization", "Bearer this-is-a-fake-token"); @@ -149,7 +149,7 @@ public void testAuthorizationHeaderIsDroppedOnRedirectForPut() { } @Test - public void testAuthorizationHeaderIsDroppedOnRedirectForGet() { + void testAuthorizationHeaderIsDroppedOnRedirectForGet() { Multimap headers = ArrayListMultimap.create(); headers.put("Authorization", "Bearer this-is-a-fake-token"); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/tpc/urlservice/URLServiceTest.java b/src/test/java/org/italiangrid/storm/webdav/test/tpc/urlservice/URLServiceTest.java index 1e370480..5b73f499 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/tpc/urlservice/URLServiceTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/tpc/urlservice/URLServiceTest.java @@ -29,13 +29,13 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class URLServiceTest { +class URLServiceTest { public static final String[] SERVICE_ALIASES = {"storm.example", "alias.storm.example", "localhost"}; @Test - public void testEmptyList() { + void testEmptyList() { assertThrows(IllegalArgumentException.class, () -> { new StaticHostListLocalURLService(Collections.emptyList()); @@ -43,7 +43,7 @@ public void testEmptyList() { } @Test - public void testNullList() { + void testNullList() { assertThrows(NullPointerException.class, () -> { new StaticHostListLocalURLService(null); @@ -51,7 +51,7 @@ public void testNullList() { } @Test - public void testResolution() { + void testResolution() { StaticHostListLocalURLService service = new StaticHostListLocalURLService(Arrays.asList(SERVICE_ALIASES)); @@ -66,7 +66,7 @@ public void testResolution() { } @Test - public void testInvalidUrlResolution() { + void testInvalidUrlResolution() { StaticHostListLocalURLService service = new StaticHostListLocalURLService(Arrays.asList(SERVICE_ALIASES)); diff --git a/src/test/java/org/italiangrid/storm/webdav/test/utils/IOUtilsTest.java b/src/test/java/org/italiangrid/storm/webdav/test/utils/IOUtilsTest.java index 6c10477b..ec27df7e 100644 --- a/src/test/java/org/italiangrid/storm/webdav/test/utils/IOUtilsTest.java +++ b/src/test/java/org/italiangrid/storm/webdav/test/utils/IOUtilsTest.java @@ -30,7 +30,7 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class IOUtilsTest { +class IOUtilsTest { @TempDir public File testFolder; @@ -48,7 +48,7 @@ public File tempFileOfChar(String name, int b, int size) throws IOException { } @Test - public void testAllFileCopy() throws IOException { + void testAllFileCopy() throws IOException { File source = tempFileOfChar("source", 0, 128); File dest = tempFileOfChar("dest", 1, 128); @@ -66,7 +66,7 @@ public void testAllFileCopy() throws IOException { } @Test - public void testLongerSourceFileCopy() throws IOException { + void testLongerSourceFileCopy() throws IOException { File source = tempFileOfChar("source", 0, 200); File dest = tempFileOfChar("dest", 1, 64); @@ -84,7 +84,7 @@ public void testLongerSourceFileCopy() throws IOException { } @Test - public void testShorterSourceFileCopy() throws IOException { + void testShorterSourceFileCopy() throws IOException { File source = tempFileOfChar("source", 0, 16); File dest = tempFileOfChar("dest", 1, 512); @@ -102,7 +102,7 @@ public void testShorterSourceFileCopy() throws IOException { } @Test - public void testPartialWriteCopy() throws IOException { + void testPartialWriteCopy() throws IOException { File source = tempFileOfChar("source", 0, 128); File dest = tempFileOfChar("dest", 1, 512); @@ -120,7 +120,7 @@ public void testPartialWriteCopy() throws IOException { } @Test - public void testMiddleWrite() throws IOException { + void testMiddleWrite() throws IOException { File source = tempFileOfChar("source", 0, 640); File dest = tempFileOfChar("dest", 1, 256);