From 151f9a6f39d4338d387e759e48135f05dda8ca6a Mon Sep 17 00:00:00 2001 From: Luca Bassi Date: Fri, 8 May 2026 19:13:53 +0200 Subject: [PATCH 1/3] Add Spotless to format code and CI workflow to check formatting --- .github/workflows/check-formatting.yaml | 27 +++++++++++++++++++++++++ pom.xml | 12 +++++++++++ 2 files changed, 39 insertions(+) create mode 100644 .github/workflows/check-formatting.yaml diff --git a/.github/workflows/check-formatting.yaml b/.github/workflows/check-formatting.yaml new file mode 100644 index 0000000..4c26fa1 --- /dev/null +++ b/.github/workflows/check-formatting.yaml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare +# +# SPDX-License-Identifier: Apache-2.0 + +name: Check formatting + +on: [push, pull_request] + +jobs: + check-formatting: + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: 21 + - name: Cache Maven packages + uses: actions/cache@v5 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + - name: Check formatting + run: mvn -B spotless:check diff --git a/pom.xml b/pom.xml index 2d1f184..e6c1724 100644 --- a/pom.xml +++ b/pom.xml @@ -46,6 +46,7 @@ SPDX-License-Identifier: Apache-2.0 0.10.0 3.2.8 3.12.0 + 3.4.0 4.13.2 3.0 @@ -231,6 +232,17 @@ SPDX-License-Identifier: Apache-2.0 + + + com.diffplug.spotless + spotless-maven-plugin + ${plugin.spotless.version} + + + + + + From 97145e5e6cf3138e451975815a1bdb596f671e43 Mon Sep 17 00:00:00 2001 From: Luca Bassi Date: Fri, 8 May 2026 19:14:17 +0200 Subject: [PATCH 2/3] Format code --- .../org/italiangrid/voms/VOMSAttribute.java | 100 ++-- .../java/org/italiangrid/voms/VOMSError.java | 7 +- .../voms/VOMSGenericAttribute.java | 14 +- .../org/italiangrid/voms/VOMSValidators.java | 57 +- .../italiangrid/voms/ac/ACLookupListener.java | 30 +- .../italiangrid/voms/ac/ACParsingContext.java | 37 +- .../voms/ac/VOMSACLookupStrategy.java | 25 +- .../org/italiangrid/voms/ac/VOMSACParser.java | 19 +- .../voms/ac/VOMSACValidationStrategy.java | 33 +- .../italiangrid/voms/ac/VOMSACValidator.java | 91 ++- .../VOMSAttributesNormalizationStrategy.java | 24 +- .../voms/ac/VOMSValidationResult.java | 56 +- .../voms/ac/ValidationResultListener.java | 13 +- .../ac/impl/DefaultLocalHostnameResolver.java | 16 +- .../voms/ac/impl/DefaultVOMSACParser.java | 35 +- .../impl/DefaultVOMSValidationStrategy.java | 149 +++-- .../voms/ac/impl/DefaultVOMSValidator.java | 41 +- .../voms/ac/impl/LeafACLookupStrategy.java | 26 +- ...eafVOMSExtensionNormalizationStrategy.java | 18 +- .../voms/ac/impl/LocalHostnameResolver.java | 11 +- .../voms/ac/impl/VOMSAttributesImpl.java | 42 +- .../ac/impl/VOMSGenericAttributeImpl.java | 37 +- .../voms/ac/impl/package-info.java | 5 +- .../org/italiangrid/voms/ac/package-info.java | 6 +- .../voms/asn1/VOMSACGenerator.java | 152 ++--- .../italiangrid/voms/asn1/VOMSACUtils.java | 230 +++---- .../italiangrid/voms/asn1/VOMSConstants.java | 58 +- .../italiangrid/voms/asn1/package-info.java | 5 +- .../voms/credential/FilePermissionError.java | 10 +- .../LoadCredentialsEventListener.java | 36 +- .../credential/LoadCredentialsStrategy.java | 17 +- .../voms/credential/ProxyNamingPolicy.java | 12 +- .../voms/credential/UserCredentials.java | 23 +- .../credential/VOMSEnvironmentVariables.java | 3 +- .../impl/AbstractLoadCredentialsStrategy.java | 116 ++-- .../impl/DefaultLoadCredentialsStrategy.java | 80 ++- .../impl/DefaultProxyPathBuilder.java | 1 - .../voms/credential/impl/package-info.java | 5 +- .../voms/credential/package-info.java | 5 +- .../voms/error/VOMSValidationErrorCode.java | 13 +- .../error/VOMSValidationErrorMessage.java | 39 +- .../italiangrid/voms/error/package-info.java | 5 +- .../voms/examples/ValidationExample.java | 22 +- .../voms/examples/package-info.java | 5 +- .../org/italiangrid/voms/package-info.java | 12 +- .../voms/request/ACDecodingStrategy.java | 9 +- .../request/SSLSocketFactoryProvider.java | 34 +- .../voms/request/VOMSACRequest.java | 13 +- .../voms/request/VOMSACService.java | 24 +- .../voms/request/VOMSESLookupStrategy.java | 14 +- .../voms/request/VOMSESParser.java | 35 +- .../voms/request/VOMSESParserFactory.java | 3 +- .../voms/request/VOMSErrorMessage.java | 8 +- .../italiangrid/voms/request/VOMSMessage.java | 7 +- .../voms/request/VOMSProtocol.java | 24 +- .../voms/request/VOMSProtocolError.java | 32 +- .../voms/request/VOMSProtocolListener.java | 21 +- .../voms/request/VOMSRequestListener.java | 74 +-- .../voms/request/VOMSResponse.java | 23 +- .../request/VOMSResponseParsingStrategy.java | 12 +- .../voms/request/VOMSServerInfo.java | 26 +- .../voms/request/VOMSServerInfoStore.java | 32 +- .../request/VOMSServerInfoStoreListener.java | 29 +- .../voms/request/VOMSWarningMessage.java | 8 +- .../voms/request/impl/ACGenerationParams.java | 88 ++- .../request/impl/AbstractVOMSProtocol.java | 51 +- .../impl/BaseVOMSESLookupStrategy.java | 10 +- .../request/impl/DefaultVOMSACRequest.java | 12 +- .../request/impl/DefaultVOMSACService.java | 215 +++---- .../impl/DefaultVOMSESLookupStrategy.java | 21 +- .../request/impl/DefaultVOMSServerInfo.java | 69 +-- .../impl/DefaultVOMSServerInfoStore.java | 119 ++-- .../voms/request/impl/FakeVOMSACService.java | 55 +- .../impl/FakeVOMSACServiceProperties.java | 16 +- .../request/impl/GoodACDecodingStrategy.java | 1 - .../voms/request/impl/LegacyProtocol.java | 59 +- .../request/impl/LegacyRequestSender.java | 28 +- .../request/impl/LegacyVOMSESParserImpl.java | 52 +- .../voms/request/impl/LegacyVOMSResponse.java | 72 +-- .../LegacyVOMSResponseParsingStrategy.java | 10 +- .../voms/request/impl/RESTProtocol.java | 52 +- .../request/impl/RESTServiceURLBuilder.java | 19 +- .../voms/request/impl/RESTVOMSResponse.java | 5 +- .../impl/RESTVOMSResponseParsingStrategy.java | 25 +- .../voms/request/impl/VOMSESLineParser.java | 109 ++-- .../voms/request/impl/VOMSRequestFactory.java | 40 +- .../voms/request/impl/package-info.java | 5 +- .../voms/request/package-info.java | 5 +- .../italiangrid/voms/store/LSCFileParser.java | 34 +- .../org/italiangrid/voms/store/LSCInfo.java | 47 +- .../italiangrid/voms/store/Updateable.java | 18 +- .../voms/store/UpdatingVOMSTrustStore.java | 7 +- .../voms/store/VOMSTrustStore.java | 73 +-- .../store/VOMSTrustStoreStatusListener.java | 40 +- .../voms/store/VOMSTrustStores.java | 47 +- .../voms/store/impl/DefaultLSCFileParser.java | 24 +- .../impl/DefaultUpdatingVOMSTrustStore.java | 115 ++-- .../store/impl/DefaultVOMSTrustStore.java | 134 ++--- .../italiangrid/voms/store/impl/LSCFile.java | 58 +- .../store/impl/VOMSNamedThreadFactory.java | 10 +- .../voms/store/impl/VOMSThread.java | 23 +- .../voms/store/impl/package-info.java | 5 +- .../italiangrid/voms/store/package-info.java | 5 +- .../util/CachingCertificateValidator.java | 189 +++--- .../util/CertificateValidatorBuilder.java | 561 ++++++++---------- .../voms/util/CredentialsUtils.java | 181 +++--- .../voms/util/FilePermissionHelper.java | 48 +- .../voms/util/FingerprintHelper.java | 16 +- .../org/italiangrid/voms/util/GaParser.java | 31 +- .../italiangrid/voms/util/NullListener.java | 116 +--- .../org/italiangrid/voms/util/TimeUtils.java | 27 +- .../voms/util/VOMSBase64Decoder.java | 187 +++--- .../voms/util/VOMSFQANNamingScheme.java | 173 +++--- .../org/italiangrid/voms/util/XMLUtils.java | 6 +- .../italiangrid/voms/util/package-info.java | 5 +- .../voms/test/TestDefaultVOMSTrustStore.java | 25 +- .../voms/test/TestFilePermissionHelper.java | 13 +- .../voms/test/TestFingerprint.java | 23 +- .../italiangrid/voms/test/TestLSCParser.java | 58 +- .../voms/test/TestOpensslHashFunction.java | 57 +- .../italiangrid/voms/test/TestTimeUtils.java | 23 +- .../voms/test/TestVOMSESLineParser.java | 7 +- .../voms/test/TestVOMSESLookupStrategy.java | 11 +- .../voms/test/TestVOMSESParser.java | 44 +- .../voms/test/TestVOMSServerInfoStore.java | 27 +- .../voms/test/ac/TestACGeneration.java | 338 ++++++----- .../voms/test/ac/TestACGenerationParams.java | 26 +- .../voms/test/ac/TestACParser.java | 16 +- .../voms/test/ac/TestACParsingContext.java | 3 - .../voms/test/ac/TestACSupport.java | 23 +- .../voms/test/ac/TestACValidator.java | 138 +++-- .../voms/test/ac/TestFakeVOMSACService.java | 32 +- .../voms/test/ac/TestGaParser.java | 35 +- .../test/ac/TestNoExtensionValidation.java | 62 +- .../test/ac/TestVOMSValidationResult.java | 5 +- .../voms/test/cred/TestLoadCredential.java | 32 +- .../voms/test/cred/package-info.java | 7 +- .../test/mt/TestConcurrentValidation.java | 115 ++-- .../italiangrid/voms/test/package-info.java | 5 +- .../voms/test/req/TestRequests.java | 88 +-- .../voms/test/utils/EchoVOMSProtocol.java | 25 +- .../italiangrid/voms/test/utils/Fixture.java | 1 - .../voms/test/utils/LogListener.java | 36 +- .../italiangrid/voms/test/utils/Utils.java | 91 ++- .../italiangrid/voms/test/utils/VOMSAA.java | 129 ++-- 145 files changed, 3029 insertions(+), 3953 deletions(-) diff --git a/src/main/java/org/italiangrid/voms/VOMSAttribute.java b/src/main/java/org/italiangrid/voms/VOMSAttribute.java index 21ac3fb..726e374 100644 --- a/src/main/java/org/italiangrid/voms/VOMSAttribute.java +++ b/src/main/java/org/italiangrid/voms/VOMSAttribute.java @@ -8,154 +8,142 @@ import java.security.cert.X509Certificate; import java.util.Date; import java.util.List; - import javax.security.auth.x500.X500Principal; - import org.bouncycastle.cert.X509AttributeCertificateHolder; /** - * The VOMS attributes information. This interface provides access to all the - * information available in a VOMS attribute certificate. - * - * @author Andrea Ceccanti + * The VOMS attributes information. This interface provides access to all the information available + * in a VOMS attribute certificate. * + * @author Andrea Ceccanti */ public interface VOMSAttribute { /** * This method returns the name of the VO this VOMS attributes are about - * + * * @return The name of the VO this VOMS attributes are about */ public String getVO(); /** - * This method returns the host where the VOMS Attribute Authority (AA) that - * signed these attribute lives - * - * @return The name of the host where the VOMS AA that signed these attributes - * lives + * This method returns the host where the VOMS Attribute Authority (AA) that signed these + * attribute lives + * + * @return The name of the host where the VOMS AA that signed these attributes lives */ public String getHost(); /** - * This method returns the port on which the VOMS Attribute Authority (AA) - * that signed these attributes listens for requests. - * - * @return The port on which the VOMS AA that signed these attributes listens - * for requests + * This method returns the port on which the VOMS Attribute Authority (AA) that signed these + * attributes listens for requests. + * + * @return The port on which the VOMS AA that signed these attributes listens for requests */ public int getPort(); /** - * This method returns the subject (as an {@link X500Principal}) of the holder - * of these VOMS attributes - * + * This method returns the subject (as an {@link X500Principal}) of the holder of these VOMS + * attributes + * * @return The subject of the holder of these VOMS attributes */ public X500Principal getHolder(); /** * This method returns the holder certificate serial number - * + * * @return The serial number of the holder certificate */ public BigInteger getHolderSerialNumber(); /** - * This method returns the subject of the VOMS Attribute Authority that signed - * these attributes. - * + * This method returns the subject of the VOMS Attribute Authority that signed these attributes. + * * @return The subject of the VOMS AA that signed these attributes */ public X500Principal getIssuer(); /** * This method returns the attributes' validity start time - * + * * @return The attributes' validity start time */ public Date getNotBefore(); /** * This method returns the attributes' validity end time - * + * * @return The attributes' validity end time */ public Date getNotAfter(); /** - * This method returns the list of signed Fully Qualified Attribute Names - * (FQANs) in this {@link VOMSAttribute}. - * + * This method returns the list of signed Fully Qualified Attribute Names (FQANs) in this {@link + * VOMSAttribute}. + * * @return The {@link List} of VOMS fully qualified attribute names */ public List getFQANs(); /** - * This method returns the primary FQAN (the first in the list returned by - * {@link #getFQANs()}) in this {@link VOMSAttribute}. - * + * This method returns the primary FQAN (the first in the list returned by {@link #getFQANs()}) in + * this {@link VOMSAttribute}. + * * @return The primary VOMS fully qualified attribute name */ public String getPrimaryFQAN(); /** - * This method returns the signature on the VOMS attribute certificate as a - * byte array. - * + * This method returns the signature on the VOMS attribute certificate as a byte array. + * * @return The signature of this VOMS attributes */ public byte[] getSignature(); /** - * This method returns the list of VOMS Generic attributes in this - * {@link VOMSAttribute}. - * + * This method returns the list of VOMS Generic attributes in this {@link VOMSAttribute}. + * * @return The VOMS generic attributes */ public List getGenericAttributes(); /** - * This method returns the list of targets defined for this - * {@link VOMSAttribute}. - * + * This method returns the list of targets defined for this {@link VOMSAttribute}. + * * @return The targets for this VOMS attributes */ public List getTargets(); /** - * This method returns the certificate chain of the VOMS Attribute Authority - * (AA) that signed this {@link VOMSAttribute}. - * + * This method returns the certificate chain of the VOMS Attribute Authority (AA) that signed this + * {@link VOMSAttribute}. + * * @return The VOMS AA certificate chain */ public X509Certificate[] getAACertificates(); /** - * This method checks whether the attributes are valid in the current instant - * of time. No validation is performed on the attributes. - * + * This method checks whether the attributes are valid in the current instant of time. No + * validation is performed on the attributes. + * * @return true if valid, false otherwise */ public boolean isValid(); /** - * This method checks whether the attributes are valid in a given time passed - * as argument. No validation is performed on the attributes. - * - * @param time - * the time used for the validity check + * This method checks whether the attributes are valid in a given time passed as argument. No + * validation is performed on the attributes. + * + * @param time the time used for the validity check * @return true if valid, false otherwise */ public boolean validAt(Date time); /** * This method returns the underlying VOMS Attribute certificate object. - * - * @return the underlying bouncycastle object for the VOMS attribute - * certificate. + * + * @return the underlying bouncycastle object for the VOMS attribute certificate. */ public X509AttributeCertificateHolder getVOMSAC(); - } diff --git a/src/main/java/org/italiangrid/voms/VOMSError.java b/src/main/java/org/italiangrid/voms/VOMSError.java index 501a8c1..e9b060d 100644 --- a/src/main/java/org/italiangrid/voms/VOMSError.java +++ b/src/main/java/org/italiangrid/voms/VOMSError.java @@ -6,15 +6,12 @@ /** * The base VOMS exception class. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSError extends RuntimeException { - /** - * - */ + /** */ private static final long serialVersionUID = 1L; public VOMSError(String message) { diff --git a/src/main/java/org/italiangrid/voms/VOMSGenericAttribute.java b/src/main/java/org/italiangrid/voms/VOMSGenericAttribute.java index a4bd820..891737c 100644 --- a/src/main/java/org/italiangrid/voms/VOMSGenericAttribute.java +++ b/src/main/java/org/italiangrid/voms/VOMSGenericAttribute.java @@ -5,34 +5,30 @@ package org.italiangrid.voms; /** - * A VOMS generic attribute is a name=value pair attribute augmented with a - * context. - * - * - * @author Andrea Ceccanti + * A VOMS generic attribute is a name=value pair attribute augmented with a context. * + * @author Andrea Ceccanti */ public interface VOMSGenericAttribute { /** * This method returns the name of this generic attribute - * + * * @return the name of this generic attribute */ public String getName(); /** * This method returns the value of this generic attribute - * + * * @return the value of this generic attribute */ public String getValue(); /** * This method returns the context for this generic attribute - * + * * @return the context of this generic attribute */ public String getContext(); - } diff --git a/src/main/java/org/italiangrid/voms/VOMSValidators.java b/src/main/java/org/italiangrid/voms/VOMSValidators.java index 33b5517..faac3f4 100644 --- a/src/main/java/org/italiangrid/voms/VOMSValidators.java +++ b/src/main/java/org/italiangrid/voms/VOMSValidators.java @@ -4,6 +4,7 @@ package org.italiangrid.voms; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; import org.italiangrid.voms.ac.VOMSACLookupStrategy; import org.italiangrid.voms.ac.VOMSACParser; import org.italiangrid.voms.ac.VOMSACValidator; @@ -12,48 +13,53 @@ import org.italiangrid.voms.ac.impl.DefaultVOMSValidator; import org.italiangrid.voms.store.VOMSTrustStore; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; - /** * A factory for VOMS attributes validators and parsers. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSValidators { - private VOMSValidators() { - - } + private VOMSValidators() {} public static VOMSACValidator newValidator(ValidationResultListener listener) { - return new DefaultVOMSValidator.Builder().validationListener(listener) - .build(); + return new DefaultVOMSValidator.Builder().validationListener(listener).build(); } - public static VOMSACValidator newValidator(VOMSTrustStore trustStore, - X509CertChainValidatorExt validator, ValidationResultListener vrListener) { - - return new DefaultVOMSValidator.Builder().trustStore(trustStore) - .certChainValidator(validator).validationListener(vrListener).build(); + public static VOMSACValidator newValidator( + VOMSTrustStore trustStore, + X509CertChainValidatorExt validator, + ValidationResultListener vrListener) { + return new DefaultVOMSValidator.Builder() + .trustStore(trustStore) + .certChainValidator(validator) + .validationListener(vrListener) + .build(); } - public static VOMSACValidator newValidator(VOMSTrustStore store, - X509CertChainValidatorExt validator, ValidationResultListener vrListener, - VOMSACLookupStrategy strategy) { - - return new DefaultVOMSValidator.Builder().trustStore(store) - .certChainValidator(validator).validationListener(vrListener) - .acLookupStrategy(strategy).build(); + public static VOMSACValidator newValidator( + VOMSTrustStore store, + X509CertChainValidatorExt validator, + ValidationResultListener vrListener, + VOMSACLookupStrategy strategy) { + + return new DefaultVOMSValidator.Builder() + .trustStore(store) + .certChainValidator(validator) + .validationListener(vrListener) + .acLookupStrategy(strategy) + .build(); } - public static VOMSACValidator newValidator(VOMSTrustStore trustStore, - X509CertChainValidatorExt validator) { + public static VOMSACValidator newValidator( + VOMSTrustStore trustStore, X509CertChainValidatorExt validator) { - return new DefaultVOMSValidator.Builder().trustStore(trustStore) - .certChainValidator(validator).build(); + return new DefaultVOMSValidator.Builder() + .trustStore(trustStore) + .certChainValidator(validator) + .build(); } public static VOMSACValidator newValidator() { @@ -65,5 +71,4 @@ public static VOMSACParser newParser() { return new DefaultVOMSACParser(); } - } diff --git a/src/main/java/org/italiangrid/voms/ac/ACLookupListener.java b/src/main/java/org/italiangrid/voms/ac/ACLookupListener.java index f2ffa89..8551734 100644 --- a/src/main/java/org/italiangrid/voms/ac/ACLookupListener.java +++ b/src/main/java/org/italiangrid/voms/ac/ACLookupListener.java @@ -7,34 +7,26 @@ import java.security.cert.X509Certificate; /** - * This interface is used to notify of events related to the lookup and - * succesfull parsing of VOMS attribute certificates from a certificate chain. - * - * @author andreaceccanti + * This interface is used to notify of events related to the lookup and succesfull parsing of VOMS + * attribute certificates from a certificate chain. * + * @author andreaceccanti */ public interface ACLookupListener { /** - * Informs that an AC is being looked for in the cert chain passed as - * argument. - * - * @param chain - * the chain where the AC is looked for - * @param chainLevel - * the level in the chain where the AC is being looked for + * Informs that an AC is being looked for in the cert chain passed as argument. + * + * @param chain the chain where the AC is looked for + * @param chainLevel the level in the chain where the AC is being looked for */ public void notifyACLookupEvent(X509Certificate[] chain, int chainLevel); /** - * Informs that an AC has been succesfully parsed from the cert chain passed - * as argument - * - * @param chain - * the chain from which the AC has been parsed - * @param chainLevel - * the level in the chain where the AC has been parsed + * Informs that an AC has been succesfully parsed from the cert chain passed as argument + * + * @param chain the chain from which the AC has been parsed + * @param chainLevel the level in the chain where the AC has been parsed */ public void notifyACParseEvent(X509Certificate[] chain, int chainLevel); - } diff --git a/src/main/java/org/italiangrid/voms/ac/ACParsingContext.java b/src/main/java/org/italiangrid/voms/ac/ACParsingContext.java index 783c528..2e70da9 100644 --- a/src/main/java/org/italiangrid/voms/ac/ACParsingContext.java +++ b/src/main/java/org/italiangrid/voms/ac/ACParsingContext.java @@ -6,25 +6,23 @@ import java.security.cert.X509Certificate; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; /** - * This class describes the context in which a VOMS {@link AttributeCertificate} - * has been parsed in a certificate chain. - * - * @author Andrea Ceccanti + * This class describes the context in which a VOMS {@link AttributeCertificate} has been parsed in + * a certificate chain. * + * @author Andrea Ceccanti */ public class ACParsingContext { - /** The parsed VOMS attribute certificates **/ + /** The parsed VOMS attribute certificates * */ private List ACs; - /** The position in the cert chain where the VOMS attributes have been parsed **/ + /** The position in the cert chain where the VOMS attributes have been parsed */ private int certChainPostion; - /** The certificate chain form which the VOMS attributes have been parsed. **/ + /** The certificate chain form which the VOMS attributes have been parsed. * */ private X509Certificate[] certChain; /** @@ -36,8 +34,7 @@ public List getACs() { } /** - * @param aCs - * the aCs to set + * @param aCs the aCs to set */ public void setACs(List aCs) { @@ -53,8 +50,7 @@ public int getCertChainPostion() { } /** - * @param certChainPostion - * the certChainPostion to set + * @param certChainPostion the certChainPostion to set */ public void setCertChainPostion(int certChainPostion) { @@ -70,8 +66,7 @@ public X509Certificate[] getCertChain() { } /** - * @param certChain - * the certChain to set + * @param certChain the certChain to set */ public void setCertChain(X509Certificate[] certChain) { @@ -79,19 +74,15 @@ public void setCertChain(X509Certificate[] certChain) { } /** - * @param aCs - * a set of parsed VOMS Attribute Certificates - * @param certChainPostion - * the position in the chain where the ACs have been parsed - * @param certChain - * the chain from where the ACs have been parsed + * @param aCs a set of parsed VOMS Attribute Certificates + * @param certChainPostion the position in the chain where the ACs have been parsed + * @param certChain the chain from where the ACs have been parsed */ - public ACParsingContext(List aCs, int certChainPostion, - X509Certificate[] certChain) { + public ACParsingContext( + List aCs, int certChainPostion, X509Certificate[] certChain) { ACs = aCs; this.certChainPostion = certChainPostion; this.certChain = certChain; } - } diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSACLookupStrategy.java b/src/main/java/org/italiangrid/voms/ac/VOMSACLookupStrategy.java index 2c863a3..faf9b30 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSACLookupStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSACLookupStrategy.java @@ -8,27 +8,18 @@ import java.util.List; /** - * - * A strategy for looking up a set of VOMS Attribute Certificates from a - * certificate chain. - * - * @author Andrea Ceccanti + * A strategy for looking up a set of VOMS Attribute Certificates from a certificate chain. * + * @author Andrea Ceccanti */ public interface VOMSACLookupStrategy { /** - * This method defines how a set of VOMS Attribute Certificates is looked for - * in a certificate chain. - * - * @param certChain - * the certificate chain that will be searched for VOMS attribute - * certificates - * - * @return a {@link List} of {@link ACParsingContext} that describes the - * lookup outcome + * This method defines how a set of VOMS Attribute Certificates is looked for in a certificate + * chain. + * + * @param certChain the certificate chain that will be searched for VOMS attribute certificates + * @return a {@link List} of {@link ACParsingContext} that describes the lookup outcome */ - public List lookupVOMSAttributeCertificates( - X509Certificate[] certChain); - + public List lookupVOMSAttributeCertificates(X509Certificate[] certChain); } diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSACParser.java b/src/main/java/org/italiangrid/voms/ac/VOMSACParser.java index 966208f..5875857 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSACParser.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSACParser.java @@ -6,27 +6,22 @@ import java.security.cert.X509Certificate; import java.util.List; - import org.italiangrid.voms.VOMSAttribute; /** * This interface defines the behavior of a VOMS Attribute Certificate parser. - * - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface VOMSACParser { /** - * Looks for and parses VOMS attributes in the certificate chain passed as - * argument (which is assumed to be already validated). - * - * @param validatedChain - * a validated X.509 certificate chain - * @return a possibly empty list of {@link VOMSAttribute} objects providing - * access to the parsed VOMS attributes + * Looks for and parses VOMS attributes in the certificate chain passed as argument (which is + * assumed to be already validated). + * + * @param validatedChain a validated X.509 certificate chain + * @return a possibly empty list of {@link VOMSAttribute} objects providing access to the parsed + * VOMS attributes */ public List parse(X509Certificate[] validatedChain); - } diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSACValidationStrategy.java b/src/main/java/org/italiangrid/voms/ac/VOMSACValidationStrategy.java index 2288d5f..0b0fce8 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSACValidationStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSACValidationStrategy.java @@ -5,39 +5,30 @@ package org.italiangrid.voms.ac; import java.security.cert.X509Certificate; - import org.italiangrid.voms.VOMSAttribute; /** - * The strategy implemented to perform the validation of a VOMS attribute - * certificate. - * - * @author Andrea Ceccanti + * The strategy implemented to perform the validation of a VOMS attribute certificate. * + * @author Andrea Ceccanti */ public interface VOMSACValidationStrategy { /** * Validates a VOMS Attribute Certificate - * - * @param attributes - * the parsed VOMS attributes - * @param theChain - * the certificate chain from which the attributes were parsed - * @return a {@link VOMSValidationResult} object describing the outcome of the - * validation + * + * @param attributes the parsed VOMS attributes + * @param theChain the certificate chain from which the attributes were parsed + * @return a {@link VOMSValidationResult} object describing the outcome of the validation */ - public VOMSValidationResult validateAC(VOMSAttribute attributes, - X509Certificate[] theChain); + public VOMSValidationResult validateAC(VOMSAttribute attributes, X509Certificate[] theChain); /** - * Validates VOMS attributes not extracted from a certificate chain (e.g., as - * returned from the VOMS server) - * - * @param attributes - * the VOMS attributes - * @return a {@link VOMSValidationResult} object describing the outcome of the - * validation + * Validates VOMS attributes not extracted from a certificate chain (e.g., as returned from the + * VOMS server) + * + * @param attributes the VOMS attributes + * @return a {@link VOMSValidationResult} object describing the outcome of the validation */ public VOMSValidationResult validateAC(VOMSAttribute attributes); } diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSACValidator.java b/src/main/java/org/italiangrid/voms/ac/VOMSACValidator.java index cdb77c9..6406581 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSACValidator.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSACValidator.java @@ -6,83 +6,68 @@ import java.security.cert.X509Certificate; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSAttribute; /** - * This interface extends the {@link VOMSACParser} interface and provides - * methods to perform validation on the VOMS Attribute Certificates parsed from - * a given certificate chain. - * - * @author Andrea Ceccanti + * This interface extends the {@link VOMSACParser} interface and provides methods to perform + * validation on the VOMS Attribute Certificates parsed from a given certificate chain. * + * @author Andrea Ceccanti */ public interface VOMSACValidator extends VOMSACParser { /** - * Parses and validates the VOMS attributes found in the certificate chain - * passed as argument (which is assumed to be validated already). - * - * This method returns the possibly empty list of the validated attributes. - * - * This method should be used in conjunction with the registration of a - * {@link ValidationResultListener} to get details about validation error and - * warning messages. - * - * Use the {@link #validateWithResult(X509Certificate[])} method in case you - * don't want to rely on a {@link ValidationResultListener}. - * - * @param validatedChain - * a validated X.509 certificate chain - * @return a possibly empty list of {@link VOMSAttribute} object providing - * access to the validated VOMS attributes + * Parses and validates the VOMS attributes found in the certificate chain passed as argument + * (which is assumed to be validated already). + * + *

This method returns the possibly empty list of the validated attributes. + * + *

This method should be used in conjunction with the registration of a {@link + * ValidationResultListener} to get details about validation error and warning messages. + * + *

Use the {@link #validateWithResult(X509Certificate[])} method in case you don't want to rely + * on a {@link ValidationResultListener}. + * + * @param validatedChain a validated X.509 certificate chain + * @return a possibly empty list of {@link VOMSAttribute} object providing access to the validated + * VOMS attributes */ public List validate(X509Certificate[] validatedChain); /** - * Parses and validates the VOMS attributes found in the certificate chain - * passed as argument (which is assumed to be validated already). - * - * This method returns a possibly empty list of {@link VOMSValidationResult} - * objects which describe the outcome of the validation for each VOMS AC found - * in the certificate chain. - * - * This method is useful when you want to use a single call to get all details - * about validation without relying on the registration of a - * {@link ValidationResultListener}. - * - * @param validatedChain - * a chain of X.509 certificates - * @return a possibly empty list of {@link VOMSValidationResult} object - * providing access to validation results and related attributes + * Parses and validates the VOMS attributes found in the certificate chain passed as argument + * (which is assumed to be validated already). + * + *

This method returns a possibly empty list of {@link VOMSValidationResult} objects which + * describe the outcome of the validation for each VOMS AC found in the certificate chain. + * + *

This method is useful when you want to use a single call to get all details about validation + * without relying on the registration of a {@link ValidationResultListener}. + * + * @param validatedChain a chain of X.509 certificates + * @return a possibly empty list of {@link VOMSValidationResult} object providing access to + * validation results and related attributes */ - public List validateWithResult( - X509Certificate[] validatedChain); + public List validateWithResult(X509Certificate[] validatedChain); /** - * Validates the VOMS attributes found in the attribute certificate list - * passed as argument. - * - * @param acs - * a list of {@link AttributeCertificate} - * @return the validated and possibly empty list of - * {@link AttributeCertificate} object + * Validates the VOMS attributes found in the attribute certificate list passed as argument. + * + * @param acs a list of {@link AttributeCertificate} + * @return the validated and possibly empty list of {@link AttributeCertificate} object */ public List validateACs(List acs); /** - * Sets a listener that will received validation-related events for this - * {@link VOMSACValidator}. - * - * @param listener - * the listener that will receive validation-related events. + * Sets a listener that will received validation-related events for this {@link VOMSACValidator}. + * + * @param listener the listener that will receive validation-related events. */ public void setValidationResultListener(ValidationResultListener listener); /** - * Shutdown the VOMS validator. This method should be called to perform final - * cleanup operations. + * Shutdown the VOMS validator. This method should be called to perform final cleanup operations. */ public void shutdown(); } diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSAttributesNormalizationStrategy.java b/src/main/java/org/italiangrid/voms/ac/VOMSAttributesNormalizationStrategy.java index bea81a0..cb6b391 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSAttributesNormalizationStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSAttributesNormalizationStrategy.java @@ -5,28 +5,24 @@ package org.italiangrid.voms.ac; import java.util.List; - import org.italiangrid.voms.VOMSAttribute; /** - * A strategy to select the set of relevant and appliable VOMS attributes from a - * set of parsed VOMS attribute certificates. - * - * This strategy is responsible of creating the {@link VOMSAttribute} objects - * which represents the authorizative VOMS authorization information. - * - * @author Andrea Ceccanti + * A strategy to select the set of relevant and appliable VOMS attributes from a set of parsed VOMS + * attribute certificates. * + *

This strategy is responsible of creating the {@link VOMSAttribute} objects which represents + * the authorizative VOMS authorization information. + * + * @author Andrea Ceccanti */ public interface VOMSAttributesNormalizationStrategy { /** - * Returns the normalized view of VOMS Authorization information starting from - * a list of VOMS Attribute certificates. - * - * @param acs - * a list of {@link ACParsingContext} objects - * + * Returns the normalized view of VOMS Authorization information starting from a list of VOMS + * Attribute certificates. + * + * @param acs a list of {@link ACParsingContext} objects * @return a possibly empty list {@link VOMSAttribute} object */ public List normalizeAttributes(List acs); diff --git a/src/main/java/org/italiangrid/voms/ac/VOMSValidationResult.java b/src/main/java/org/italiangrid/voms/ac/VOMSValidationResult.java index fff875a..5c32e51 100644 --- a/src/main/java/org/italiangrid/voms/ac/VOMSValidationResult.java +++ b/src/main/java/org/italiangrid/voms/ac/VOMSValidationResult.java @@ -7,35 +7,30 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.error.VOMSValidationErrorMessage; /** * This class represents the outcome of a VOMS validation. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSValidationResult { - /** The flag that tells whether the validation was successfull or not **/ + /** The flag that tells whether the validation was successfull or not * */ private final boolean valid; - /** A list of {@link VOMSValidationErrorMessage} **/ + /** A list of {@link VOMSValidationErrorMessage} * */ private final List validationErrors; - /** The attributes this validation result refer to **/ + /** The attributes this validation result refer to * */ private final VOMSAttribute attributes; /** * Default constructor. - * - * @param attributes - * the attributes this validation result refer to - * @param valid - * true in case of validation success, - * false otherwise + * + * @param attributes the attributes this validation result refer to + * @param valid true in case of validation success, false otherwise */ public VOMSValidationResult(VOMSAttribute attributes, boolean valid) { @@ -44,17 +39,13 @@ public VOMSValidationResult(VOMSAttribute attributes, boolean valid) { /** * This constructor is used to pass in a list of validation errors as well. - * - * @param attributes - * the {@link VOMSAttribute} that will be validated - * @param valid - * true in case of validation success, - * false otherwise - * @param validationErrors - * a list of validation errors + * + * @param attributes the {@link VOMSAttribute} that will be validated + * @param valid true in case of validation success, false otherwise + * @param validationErrors a list of validation errors */ - public VOMSValidationResult(VOMSAttribute attributes, boolean valid, - List validationErrors) { + public VOMSValidationResult( + VOMSAttribute attributes, boolean valid, List validationErrors) { this.attributes = attributes; this.valid = valid; @@ -63,9 +54,8 @@ public VOMSValidationResult(VOMSAttribute attributes, boolean valid, /** * Tells if validation was successful or not. - * - * @return valid true in case of validation success, - * false otherwise + * + * @return valid true in case of validation success, false otherwise */ public boolean isValid() { @@ -73,9 +63,9 @@ public boolean isValid() { } /** - * The attributes are to be considered valid only if the {@link #isValid()} - * method for this {@link VOMSValidationResult} is true. - * + * The attributes are to be considered valid only if the {@link #isValid()} method for this {@link + * VOMSValidationResult} is true. + * * @return the attributes this validation result refer to */ public VOMSAttribute getAttributes() { @@ -94,8 +84,12 @@ public List getValidationErrors() { @Override public String toString() { - return "VOMSValidationResult [valid=" + valid + ", validationErrors=" - + validationErrors + ", attributes=" + attributes + "]"; + return "VOMSValidationResult [valid=" + + valid + + ", validationErrors=" + + validationErrors + + ", attributes=" + + attributes + + "]"; } - } diff --git a/src/main/java/org/italiangrid/voms/ac/ValidationResultListener.java b/src/main/java/org/italiangrid/voms/ac/ValidationResultListener.java index 2ec1d1c..50545fc 100644 --- a/src/main/java/org/italiangrid/voms/ac/ValidationResultListener.java +++ b/src/main/java/org/italiangrid/voms/ac/ValidationResultListener.java @@ -7,20 +7,17 @@ import org.italiangrid.voms.VOMSAttribute; /** - * This interface is used to notify interested listeners of VOMS attribute - * certificate validation outcome. - * - * @author andreaceccanti + * This interface is used to notify interested listeners of VOMS attribute certificate validation + * outcome. * + * @author andreaceccanti */ public interface ValidationResultListener { /** * Informs of the result of the validation of a set of {@link VOMSAttribute} - * - * @param result - * the validation result - * + * + * @param result the validation result */ public void notifyValidationResult(VOMSValidationResult result); } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/DefaultLocalHostnameResolver.java b/src/main/java/org/italiangrid/voms/ac/impl/DefaultLocalHostnameResolver.java index 22fdd1d..a26f665 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/DefaultLocalHostnameResolver.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/DefaultLocalHostnameResolver.java @@ -8,14 +8,13 @@ import java.net.UnknownHostException; /** - * The default implementation for localhost name resolver. The localhost name is - * resolved using the following code: - * - *

- * {@code
- * 		InetAddress.getLocalHost().getCanonicalHostName();
- * }
- * 
+ * The default implementation for localhost name resolver. The localhost name is resolved using the + * following code: + * + *
{@code
+ * InetAddress.getLocalHost()
+ *   .getCanonicalHostName();
+ * }
*/ public class DefaultLocalHostnameResolver implements LocalHostnameResolver { @@ -23,5 +22,4 @@ public String resolveLocalHostname() throws UnknownHostException { return InetAddress.getLocalHost().getCanonicalHostName(); } - } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSACParser.java b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSACParser.java index 6dbbe42..cac5344 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSACParser.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSACParser.java @@ -6,7 +6,6 @@ import java.security.cert.X509Certificate; import java.util.List; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.ac.ACParsingContext; import org.italiangrid.voms.ac.VOMSACLookupStrategy; @@ -15,26 +14,25 @@ import org.italiangrid.voms.util.NullListener; /** - * Default implementation of the VOMS attribute certificate parsing logic. - * This class is responsible for extracting and normalizing VOMS attributes - * from a given X.509 certificate chain. - * - *

It utilizes a {@link VOMSACLookupStrategy} to locate attribute certificates - * within the provided chain and applies a {@link VOMSAttributesNormalizationStrategy} - * to normalize the extracted attributes.

+ * Default implementation of the VOMS attribute certificate parsing logic. This class is responsible + * for extracting and normalizing VOMS attributes from a given X.509 certificate chain. * - *

By default, it uses {@link LeafACLookupStrategy} for lookup and - * {@link LeafVOMSExtensionNormalizationStrategy} for normalization.

+ *

It utilizes a {@link VOMSACLookupStrategy} to locate attribute certificates within the + * provided chain and applies a {@link VOMSAttributesNormalizationStrategy} to normalize the + * extracted attributes. * + *

By default, it uses {@link LeafACLookupStrategy} for lookup and {@link + * LeafVOMSExtensionNormalizationStrategy} for normalization. */ public class DefaultVOMSACParser implements VOMSACParser { private final VOMSACLookupStrategy acLookupStrategy; - private final VOMSAttributesNormalizationStrategy acNormalizationStrategy = new LeafVOMSExtensionNormalizationStrategy(); + private final VOMSAttributesNormalizationStrategy acNormalizationStrategy = + new LeafVOMSExtensionNormalizationStrategy(); /** - * Creates a new {@code DefaultVOMSACParser} with the default lookup strategy. - * Uses {@link LeafACLookupStrategy} with a {@link NullListener} instance. + * Creates a new {@code DefaultVOMSACParser} with the default lookup strategy. Uses {@link + * LeafACLookupStrategy} with a {@link NullListener} instance. */ public DefaultVOMSACParser() { @@ -42,8 +40,8 @@ public DefaultVOMSACParser() { } /** - * Creates a new {@code DefaultVOMSACParser} with a specified lookup strategy. - * Uses {@link LeafVOMSExtensionNormalizationStrategy} for attribute normalization. + * Creates a new {@code DefaultVOMSACParser} with a specified lookup strategy. Uses {@link + * LeafVOMSExtensionNormalizationStrategy} for attribute normalization. * * @param strategy the lookup strategy to use for locating attribute certificates * @throws NullPointerException if the provided strategy is {@code null} @@ -63,10 +61,9 @@ public DefaultVOMSACParser(VOMSACLookupStrategy strategy) { @Override public List parse(X509Certificate[] validatedChain) { - if (validatedChain == null) - throw new NullPointerException("Cannot parse a null certchain!"); - List parsedACs = acLookupStrategy - .lookupVOMSAttributeCertificates(validatedChain); + if (validatedChain == null) throw new NullPointerException("Cannot parse a null certchain!"); + List parsedACs = + acLookupStrategy.lookupVOMSAttributeCertificates(validatedChain); return acNormalizationStrategy.normalizeAttributes(parsedACs); } } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidationStrategy.java b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidationStrategy.java index 03570a6..1aa5a00 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidationStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidationStrategy.java @@ -19,6 +19,11 @@ import static org.italiangrid.voms.error.VOMSValidationErrorCode.other; import static org.italiangrid.voms.error.VOMSValidationErrorMessage.newErrorMessage; +import eu.emi.security.authn.x509.ValidationError; +import eu.emi.security.authn.x509.ValidationResult; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.impl.X500NameUtils; +import eu.emi.security.authn.x509.proxy.ProxyUtils; import java.net.UnknownHostException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; @@ -26,9 +31,7 @@ import java.util.Arrays; import java.util.Date; import java.util.List; - import javax.security.auth.x500.X500Principal; - import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.Extension; @@ -47,17 +50,10 @@ import org.italiangrid.voms.store.LSCInfo; import org.italiangrid.voms.store.VOMSTrustStore; -import eu.emi.security.authn.x509.ValidationError; -import eu.emi.security.authn.x509.ValidationResult; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.impl.X500NameUtils; -import eu.emi.security.authn.x509.proxy.ProxyUtils; - /** * The Default VOMS validation strategy. * * @author andreaceccanti - * */ public class DefaultVOMSValidationStrategy implements VOMSACValidationStrategy { @@ -65,13 +61,12 @@ public class DefaultVOMSValidationStrategy implements VOMSACValidationStrategy { private final X509CertChainValidatorExt certChainValidator; private final LocalHostnameResolver hostnameResolver; - public DefaultVOMSValidationStrategy(VOMSTrustStore store, X509CertChainValidatorExt validator, - LocalHostnameResolver resolver) { + public DefaultVOMSValidationStrategy( + VOMSTrustStore store, X509CertChainValidatorExt validator, LocalHostnameResolver resolver) { this.store = store; this.certChainValidator = validator; this.hostnameResolver = resolver; - } public DefaultVOMSValidationStrategy(VOMSTrustStore store, X509CertChainValidatorExt validator) { @@ -79,7 +74,9 @@ public DefaultVOMSValidationStrategy(VOMSTrustStore store, X509CertChainValidato this(store, validator, new DefaultLocalHostnameResolver()); } - private boolean checkACHolder(VOMSAttribute attributes, X509Certificate[] chain, + private boolean checkACHolder( + VOMSAttribute attributes, + X509Certificate[] chain, List validationErrors) { X500Principal chainHolder = ProxyUtils.getOriginalUserDN(chain); @@ -91,23 +88,25 @@ private boolean checkACHolder(VOMSAttribute attributes, X509Certificate[] chain, String acHolderSubject = X500NameUtils.getReadableForm(attributes.getHolder()); String certChainSubject = X500NameUtils.getReadableForm(chainHolder); - validationErrors.add(VOMSValidationErrorMessage.newErrorMessage(acHolderDoesntMatchCertChain, - acHolderSubject, certChainSubject)); + validationErrors.add( + VOMSValidationErrorMessage.newErrorMessage( + acHolderDoesntMatchCertChain, acHolderSubject, certChainSubject)); } return holderDoesMatch; } - private boolean checkACValidity(VOMSAttribute attributes, - List validationErrors) { + private boolean checkACValidity( + VOMSAttribute attributes, List validationErrors) { Date now = new Date(); boolean valid = attributes.validAt(now); if (!valid) { - VOMSValidationErrorMessage m = VOMSValidationErrorMessage.newErrorMessage( - acNotValidAtCurrentTime, attributes.getNotBefore(), attributes.getNotAfter(), now); + VOMSValidationErrorMessage m = + VOMSValidationErrorMessage.newErrorMessage( + acNotValidAtCurrentTime, attributes.getNotBefore(), attributes.getNotAfter(), now); validationErrors.add(m); } @@ -115,8 +114,8 @@ private boolean checkACValidity(VOMSAttribute attributes, return valid; } - private boolean checkLocalAACertSignature(VOMSAttribute attributes, - List validationErrors) { + private boolean checkLocalAACertSignature( + VOMSAttribute attributes, List validationErrors) { X509Certificate localAACert = store.getAACertificateBySubject(attributes.getIssuer()); if (localAACert == null) { @@ -137,16 +136,16 @@ private boolean checkLocalAACertSignature(VOMSAttribute attributes, if (!signatureValid) { String readableSubject = X500NameUtils.getReadableForm(localAACert.getSubjectX500Principal()); - validationErrors.add(VOMSValidationErrorMessage - .newErrorMessage(aaCertFailsSignatureVerification, readableSubject)); + validationErrors.add( + VOMSValidationErrorMessage.newErrorMessage( + aaCertFailsSignatureVerification, readableSubject)); } return signatureValid; - } - private boolean checkLSCSignature(VOMSAttribute attributes, - List validationErrors) { + private boolean checkLSCSignature( + VOMSAttribute attributes, List validationErrors) { LSCInfo lsc = store.getLSC(attributes.getVO(), attributes.getHost()); X509Certificate[] aaCerts = attributes.getAACertificates(); @@ -162,8 +161,8 @@ private boolean checkLSCSignature(VOMSAttribute attributes, } if (!lsc.matches(aaCerts)) { - validationErrors - .add(VOMSValidationErrorMessage.newErrorMessage(lscDescriptionDoesntMatchAcCert)); + validationErrors.add( + VOMSValidationErrorMessage.newErrorMessage(lscDescriptionDoesntMatchAcCert)); return false; } @@ -181,30 +180,28 @@ private boolean checkLSCSignature(VOMSAttribute attributes, if (!signatureValid) { String readableSubject = X500NameUtils.getReadableForm(aaCerts[0].getSubjectX500Principal()); - validationErrors.add(VOMSValidationErrorMessage - .newErrorMessage(acCertFailsSignatureVerification, readableSubject)); + validationErrors.add( + VOMSValidationErrorMessage.newErrorMessage( + acCertFailsSignatureVerification, readableSubject)); } return signatureValid; } - private boolean checkSignature(VOMSAttribute attributes, - List validationErrors) { + private boolean checkSignature( + VOMSAttribute attributes, List validationErrors) { boolean valid = checkLSCSignature(attributes, validationErrors); - if (!valid) - valid = checkLocalAACertSignature(attributes, validationErrors); + if (!valid) valid = checkLocalAACertSignature(attributes, validationErrors); return valid; - } - private boolean checkTargets(VOMSAttribute attributes, - List validationErrors) { + private boolean checkTargets( + VOMSAttribute attributes, List validationErrors) { - if (attributes.getTargets() == null || attributes.getTargets().size() == 0) - return true; + if (attributes.getTargets() == null || attributes.getTargets().size() == 0) return true; String localhostName; @@ -212,22 +209,23 @@ private boolean checkTargets(VOMSAttribute attributes, localhostName = hostnameResolver.resolveLocalHostname(); } catch (UnknownHostException e) { - validationErrors - .add(newErrorMessage(other, "Error resolving localhost name: " + e.getMessage())); + validationErrors.add( + newErrorMessage(other, "Error resolving localhost name: " + e.getMessage())); return false; } if (!attributes.getTargets().contains(localhostName)) { - validationErrors.add(newErrorMessage(localhostDoesntMatchAcTarget, localhostName, - attributes.getTargets().toString())); + validationErrors.add( + newErrorMessage( + localhostDoesntMatchAcTarget, localhostName, attributes.getTargets().toString())); return false; } return true; } - private boolean checkNoRevAvailExtension(VOMSAttribute attributes, - List validationErrors) { + private boolean checkNoRevAvailExtension( + VOMSAttribute attributes, List validationErrors) { Extension noRevAvail = attributes.getVOMSAC().getExtension(Extension.noRevAvail); @@ -238,7 +236,9 @@ private boolean checkNoRevAvailExtension(VOMSAttribute attributes, return true; } - private boolean checkAuthorityKeyIdentifier(X509Certificate aaCert, VOMSAttribute attributes, + private boolean checkAuthorityKeyIdentifier( + X509Certificate aaCert, + VOMSAttribute attributes, List validationErrors) { AuthorityKeyIdentifier akid = @@ -252,29 +252,31 @@ private boolean checkAuthorityKeyIdentifier(X509Certificate aaCert, VOMSAttribut boolean authKeyIdMatches = Arrays.equals(skid.getKeyIdentifier(), akid.getKeyIdentifier()); if (!authKeyIdMatches) { - validationErrors.add(newErrorMessage(other, - "AuthorityKeyIdentifier in the AC does not match AA certificate subject key identifier!")); + validationErrors.add( + newErrorMessage( + other, + "AuthorityKeyIdentifier in the AC does not match AA certificate subject key identifier!")); return false; } return true; } catch (CertificateEncodingException e) { - validationErrors.add(newErrorMessage(other, - String.format("VOMS AA certificate parse error: %s", e.getMessage()))); + validationErrors.add( + newErrorMessage( + other, String.format("VOMS AA certificate parse error: %s", e.getMessage()))); return false; } - } - private boolean checkAuthorityKeyIdentifierExtension(VOMSAttribute attributes, - List validationErrors) { + private boolean checkAuthorityKeyIdentifierExtension( + VOMSAttribute attributes, List validationErrors) { Extension authKeyId = attributes.getVOMSAC().getExtension(Extension.authorityKeyIdentifier); if (authKeyId != null && authKeyId.isCritical()) { - validationErrors - .add(newErrorMessage(other, "AuthorityKeyIdentifier AC extension cannot be critical!")); + validationErrors.add( + newErrorMessage(other, "AuthorityKeyIdentifier AC extension cannot be critical!")); return false; } @@ -282,8 +284,8 @@ private boolean checkAuthorityKeyIdentifierExtension(VOMSAttribute attributes, return true; } - private boolean checkUnhandledCriticalExtensions(VOMSAttribute attributes, - List validationErrors) { + private boolean checkUnhandledCriticalExtensions( + VOMSAttribute attributes, List validationErrors) { @SuppressWarnings("unchecked") List acExtensions = attributes.getVOMSAC().getExtensionOIDs(); @@ -291,8 +293,9 @@ private boolean checkUnhandledCriticalExtensions(VOMSAttribute attributes, for (ASN1ObjectIdentifier extId : acExtensions) { if (!VOMSConstants.VOMS_HANDLED_EXTENSIONS.contains(extId) && attributes.getVOMSAC().getExtension(extId).isCritical()) { - validationErrors.add(newErrorMessage(other, - "unknown critical extension found in VOMS AC: " + extId.getId())); + validationErrors.add( + newErrorMessage( + other, "unknown critical extension found in VOMS AC: " + extId.getId())); return false; } } @@ -316,14 +319,11 @@ public VOMSValidationResult validateAC(VOMSAttribute attributes) { valid = checkTargets(attributes, validationErrors); // AC extension checking to be compliant with rfc 3281 - if (valid) - valid = checkAuthorityKeyIdentifierExtension(attributes, validationErrors); + if (valid) valid = checkAuthorityKeyIdentifierExtension(attributes, validationErrors); - if (valid) - valid = checkNoRevAvailExtension(attributes, validationErrors); + if (valid) valid = checkNoRevAvailExtension(attributes, validationErrors); - if (valid) - valid = checkUnhandledCriticalExtensions(attributes, validationErrors); + if (valid) valid = checkUnhandledCriticalExtensions(attributes, validationErrors); return new VOMSValidationResult(attributes, valid, validationErrors); } @@ -349,26 +349,23 @@ public VOMSValidationResult validateAC(VOMSAttribute attributes, X509Certificate valid = checkTargets(attributes, validationErrors); // AC extension checking to be compliant with rfc 3281 - if (valid) - valid = checkAuthorityKeyIdentifierExtension(attributes, validationErrors); + if (valid) valid = checkAuthorityKeyIdentifierExtension(attributes, validationErrors); - if (valid) - valid = checkNoRevAvailExtension(attributes, validationErrors); + if (valid) valid = checkNoRevAvailExtension(attributes, validationErrors); - if (valid) - valid = checkUnhandledCriticalExtensions(attributes, validationErrors); + if (valid) valid = checkUnhandledCriticalExtensions(attributes, validationErrors); return new VOMSValidationResult(attributes, valid, validationErrors); } - private boolean validateCertificate(X509Certificate c, - List validationErrors) { + private boolean validateCertificate( + X509Certificate c, List validationErrors) { return validateCertificateChain(new X509Certificate[] {c}, validationErrors); } - private boolean validateCertificateChain(X509Certificate[] chain, - List validationErrors) { + private boolean validateCertificateChain( + X509Certificate[] chain, List validationErrors) { ValidationResult result = certChainValidator.validate(chain); @@ -385,7 +382,7 @@ private boolean verifyACSignature(VOMSAttribute attributes, X509Certificate cert X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); ContentVerifierProvider cvp = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()) - .build(certHolder); + .build(certHolder); return attributes.getVOMSAC().isSignatureValid(cvp); } catch (Exception e) { diff --git a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidator.java b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidator.java index 9de35c1..9379e77 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidator.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/DefaultVOMSValidator.java @@ -4,10 +4,10 @@ package org.italiangrid.voms.ac.impl; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.ac.VOMSACLookupStrategy; @@ -22,16 +22,12 @@ import org.italiangrid.voms.util.CertificateValidatorBuilder; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; - /** * The default implementation of the VOMS validator. - * - * @author andreaceccanti * + * @author andreaceccanti */ -public class DefaultVOMSValidator extends DefaultVOMSACParser implements - VOMSACValidator { +public class DefaultVOMSValidator extends DefaultVOMSACParser implements VOMSACValidator { public static final String DEFAULT_TRUST_ANCHORS_DIR = "/etc/grid-security/certificates"; @@ -49,9 +45,7 @@ public static class Builder { private X509CertChainValidatorExt certChainValidator; private VOMSACLookupStrategy acLookupStrategy; - public Builder() { - - } + public Builder() {} public Builder validationStrategy(VOMSACValidationStrategy s) { @@ -86,29 +80,24 @@ public Builder acLookupStrategy(VOMSACLookupStrategy ls) { private void sanityChecks() { if (validationStrategy == null) { - if (trustStore == null) - trustStore = VOMSTrustStores.newTrustStore(); + if (trustStore == null) trustStore = VOMSTrustStores.newTrustStore(); if (certChainValidator == null) - certChainValidator = new CertificateValidatorBuilder() - .trustAnchorsDir(DEFAULT_TRUST_ANCHORS_DIR).build(); + certChainValidator = + new CertificateValidatorBuilder().trustAnchorsDir(DEFAULT_TRUST_ANCHORS_DIR).build(); - validationStrategy = new DefaultVOMSValidationStrategy(trustStore, - certChainValidator); + validationStrategy = new DefaultVOMSValidationStrategy(trustStore, certChainValidator); } if (validationResultListener == null) { validationResultListener = NullListener.INSTANCE; - } - if (acLookupStrategy == null){ - + if (acLookupStrategy == null) { + acLookupStrategy = new LeafACLookupStrategy(); - } - } public DefaultVOMSValidator build() { @@ -127,29 +116,25 @@ private DefaultVOMSValidator(Builder b) { this.validationResultListener = b.validationResultListener; } - public List validateWithResult( - X509Certificate[] validatedChain) { + public List validateWithResult(X509Certificate[] validatedChain) { return internalValidate(validatedChain); } - protected List internalValidate( - X509Certificate[] validatedChain) { + protected List internalValidate(X509Certificate[] validatedChain) { List parsedAttrs = parse(validatedChain); List results = new ArrayList(); for (VOMSAttribute a : parsedAttrs) { - VOMSValidationResult result = validationStrategy.validateAC(a, - validatedChain); + VOMSValidationResult result = validationStrategy.validateAC(a, validatedChain); synchronized (listenerLock) { validationResultListener.notifyValidationResult(result); } results.add(result); - } return results; diff --git a/src/main/java/org/italiangrid/voms/ac/impl/LeafACLookupStrategy.java b/src/main/java/org/italiangrid/voms/ac/impl/LeafACLookupStrategy.java index 38be02c..a48431b 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/LeafACLookupStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/LeafACLookupStrategy.java @@ -4,11 +4,11 @@ package org.italiangrid.voms.ac.impl; +import eu.emi.security.authn.x509.proxy.ProxyUtils; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.ac.ACLookupListener; @@ -18,18 +18,13 @@ import org.italiangrid.voms.asn1.VOMSConstants; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.proxy.ProxyUtils; - /** - * This strategy returns the leaf VOMS Attribute Certificate in a certificate - * chain, i.e. the Attribute Certificate found in the latest delegation in the - * chain. - * - * @author Andrea Ceccanti + * This strategy returns the leaf VOMS Attribute Certificate in a certificate chain, i.e. the + * Attribute Certificate found in the latest delegation in the chain. * + * @author Andrea Ceccanti */ -public class LeafACLookupStrategy implements VOMSACLookupStrategy, - VOMSConstants { +public class LeafACLookupStrategy implements VOMSACLookupStrategy, VOMSConstants { private ACLookupListener listener; @@ -43,14 +38,13 @@ public LeafACLookupStrategy() { this(NullListener.INSTANCE); } - public List lookupVOMSAttributeCertificates( - X509Certificate[] certChain) { + public List lookupVOMSAttributeCertificates(X509Certificate[] certChain) { List parsedACs = new ArrayList(); if (certChain == null || certChain.length == 0) throw new VOMSError( - "Cannot extract VOMS Attribute Certificates from a null or empty certificate chain!"); + "Cannot extract VOMS Attribute Certificates from a null or empty certificate chain!"); for (int index = 0; index < certChain.length; index++) { @@ -62,16 +56,14 @@ public List lookupVOMSAttributeCertificates( if (ProxyUtils.isProxy(cert)) { - List vomsACs = VOMSACUtils - .getACsFromCertificate(cert); + List vomsACs = VOMSACUtils.getACsFromCertificate(cert); // Break at the first AC found from the top of the chain if (!vomsACs.isEmpty()) { listener.notifyACParseEvent(certChain, index); - ACParsingContext ctx = new ACParsingContext(vomsACs, index, - certChain); + ACParsingContext ctx = new ACParsingContext(vomsACs, index, certChain); parsedACs.add(ctx); break; } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/LeafVOMSExtensionNormalizationStrategy.java b/src/main/java/org/italiangrid/voms/ac/impl/LeafVOMSExtensionNormalizationStrategy.java index fc2a575..cd72405 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/LeafVOMSExtensionNormalizationStrategy.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/LeafVOMSExtensionNormalizationStrategy.java @@ -6,7 +6,6 @@ import java.util.Collections; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.ac.ACParsingContext; @@ -15,25 +14,20 @@ import org.italiangrid.voms.asn1.VOMSConstants; /** - * - * This strategy extracts the VOMS attributes from the top VOMS extension found - * in the parsing context passed as argument. - * - * @author Andrea Ceccanti + * This strategy extracts the VOMS attributes from the top VOMS extension found in the parsing + * context passed as argument. * + * @author Andrea Ceccanti */ -public class LeafVOMSExtensionNormalizationStrategy implements - VOMSAttributesNormalizationStrategy, VOMSConstants { +public class LeafVOMSExtensionNormalizationStrategy + implements VOMSAttributesNormalizationStrategy, VOMSConstants { public List normalizeAttributes(List acs) { - if (acs == null || acs.isEmpty()) - return Collections.emptyList(); + if (acs == null || acs.isEmpty()) return Collections.emptyList(); List attrs = acs.get(0).getACs(); return VOMSACUtils.deserializeVOMSAttributes(attrs); - } - } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/LocalHostnameResolver.java b/src/main/java/org/italiangrid/voms/ac/impl/LocalHostnameResolver.java index 68dbc55..5b96bd9 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/LocalHostnameResolver.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/LocalHostnameResolver.java @@ -6,19 +6,14 @@ import java.net.UnknownHostException; -/** - * A {@link LocalHostnameResolver} resolves the localhost host name. - * - */ +/** A {@link LocalHostnameResolver} resolves the localhost host name. */ public interface LocalHostnameResolver { /** * Resolves the hostname for localhost - * + * * @return a String containing the localhost hostname - * @throws UnknownHostException - * when there is an error resolving the hostname + * @throws UnknownHostException when there is an error resolving the hostname */ public String resolveLocalHostname() throws UnknownHostException; - } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/VOMSAttributesImpl.java b/src/main/java/org/italiangrid/voms/ac/impl/VOMSAttributesImpl.java index a162f34..96c635c 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/VOMSAttributesImpl.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/VOMSAttributesImpl.java @@ -4,25 +4,21 @@ package org.italiangrid.voms.ac.impl; +import eu.emi.security.authn.x509.impl.X500NameUtils; import java.math.BigInteger; import java.security.cert.X509Certificate; import java.util.Date; import java.util.List; - import javax.security.auth.x500.X500Principal; - import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.VOMSGenericAttribute; import org.italiangrid.voms.util.TimeUtils; -import eu.emi.security.authn.x509.impl.X500NameUtils; - /** * The default implementation for voms attributes - * - * @author andreaceccanti * + * @author andreaceccanti */ public class VOMSAttributesImpl implements VOMSAttribute { @@ -43,9 +39,7 @@ public class VOMSAttributesImpl implements VOMSAttribute { private X509Certificate[] aaCerts; private X509AttributeCertificateHolder VOMSAC; - public VOMSAttributesImpl() { - - } + public VOMSAttributesImpl() {} public X500Principal getIssuer() { @@ -145,11 +139,27 @@ public void setSignature(byte[] signature) { @Override public String toString() { - return "VOMSAttributesImpl [VO=" + VO + ", host=" + host + ", port=" + port - + ", FQANs=" + FQANs + ", gas=" + genericAttributes + ", issuer='" - + X500NameUtils.getReadableForm(issuer) + "', holder='" - + X500NameUtils.getReadableForm(holder) + "', notAfter=" + notAfter - + ", notBefore=" + notBefore + ", targets=" + acTargets + " ]"; + return "VOMSAttributesImpl [VO=" + + VO + + ", host=" + + host + + ", port=" + + port + + ", FQANs=" + + FQANs + + ", gas=" + + genericAttributes + + ", issuer='" + + X500NameUtils.getReadableForm(issuer) + + "', holder='" + + X500NameUtils.getReadableForm(holder) + + "', notAfter=" + + notAfter + + ", notBefore=" + + notBefore + + ", targets=" + + acTargets + + " ]"; } public List getGenericAttributes() { @@ -189,8 +199,8 @@ public boolean isValid() { public boolean validAt(Date date) { - return TimeUtils.checkTimeInRangeWithSkew(date, getNotBefore(), - getNotAfter(), DEFAULT_CLOCK_SKEW_IN_MINUTES); + return TimeUtils.checkTimeInRangeWithSkew( + date, getNotBefore(), getNotAfter(), DEFAULT_CLOCK_SKEW_IN_MINUTES); } public X509AttributeCertificateHolder getVOMSAC() { diff --git a/src/main/java/org/italiangrid/voms/ac/impl/VOMSGenericAttributeImpl.java b/src/main/java/org/italiangrid/voms/ac/impl/VOMSGenericAttributeImpl.java index 793edbd..382e274 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/VOMSGenericAttributeImpl.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/VOMSGenericAttributeImpl.java @@ -8,9 +8,8 @@ /** * The default implementation for VOMS Generic Attributes. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSGenericAttributeImpl implements VOMSGenericAttribute { @@ -18,9 +17,7 @@ public class VOMSGenericAttributeImpl implements VOMSGenericAttribute { private String value; private String context; - public VOMSGenericAttributeImpl() { - - } + public VOMSGenericAttributeImpl() {} public String getName() { @@ -55,8 +52,7 @@ public void setContext(String context) { @Override public String toString() { - return "VOMSGenericAttribute [name=" + name + ", value=" + value - + ", context=" + context + "]"; + return "VOMSGenericAttribute [name=" + name + ", value=" + value + ", context=" + context + "]"; } @Override @@ -73,28 +69,19 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; VOMSGenericAttributeImpl other = (VOMSGenericAttributeImpl) obj; if (context == null) { - if (other.context != null) - return false; - } else if (!context.equals(other.context)) - return false; + if (other.context != null) return false; + } else if (!context.equals(other.context)) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; + if (other.value != null) return false; + } else if (!value.equals(other.value)) return false; return true; } } diff --git a/src/main/java/org/italiangrid/voms/ac/impl/package-info.java b/src/main/java/org/italiangrid/voms/ac/impl/package-info.java index e1c57c7..3daa495 100644 --- a/src/main/java/org/italiangrid/voms/ac/impl/package-info.java +++ b/src/main/java/org/italiangrid/voms/ac/impl/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * Implementation classes for VOMS attributes validation and parsing. - */ +/** Implementation classes for VOMS attributes validation and parsing. */ package org.italiangrid.voms.ac.impl; - diff --git a/src/main/java/org/italiangrid/voms/ac/package-info.java b/src/main/java/org/italiangrid/voms/ac/package-info.java index c9dc5f9..c51441a 100644 --- a/src/main/java/org/italiangrid/voms/ac/package-info.java +++ b/src/main/java/org/italiangrid/voms/ac/package-info.java @@ -2,9 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the APIs to perform validation and parsing - * of VOMS attributes. - */ +/** This package provides the APIs to perform validation and parsing of VOMS attributes. */ package org.italiangrid.voms.ac; - diff --git a/src/main/java/org/italiangrid/voms/asn1/VOMSACGenerator.java b/src/main/java/org/italiangrid/voms/asn1/VOMSACGenerator.java index eaccf6a..ace3625 100644 --- a/src/main/java/org/italiangrid/voms/asn1/VOMSACGenerator.java +++ b/src/main/java/org/italiangrid/voms/asn1/VOMSACGenerator.java @@ -4,6 +4,8 @@ package org.italiangrid.voms.asn1; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.proxy.CertificateExtension; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -16,7 +18,6 @@ import java.util.EnumSet; import java.util.List; import java.util.Random; - import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; @@ -47,21 +48,14 @@ import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.VOMSGenericAttribute; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.proxy.CertificateExtension; - /** * A generator for VOMS Attribute Certificates (ACs). - *

- * This class provides methods for creating VOMS ACs with customizable properties, including + * + *

This class provides methods for creating VOMS ACs with customizable properties, including * optional extensions and fake signature bits for testing purposes. - *

- * - *

- * It uses BouncyCastle for cryptographic operations and supports various extensions required for + * + *

It uses BouncyCastle for cryptographic operations and supports various extensions required for * VOMS attribute certificates. - *

- * */ public class VOMSACGenerator implements VOMSConstants { @@ -75,53 +69,47 @@ public enum ACGenerationProperties { /** * Skips the inclusion of the AC Certs extension in the generated Attribute Certificate. - *

- * This extension normally contains the issuer's certificate chain, which may be omitted - * if the relying party already possesses it. - *

+ * + *

This extension normally contains the issuer's certificate chain, which may be omitted if + * the relying party already possesses it. */ SKIP_AC_CERTS_EXTENSION, /** * Generates fake signature bits instead of signing the certificate with a real key. - *

- * This is primarily used for testing purposes, as the resulting AC will not be verifiable. - *

+ * + *

This is primarily used for testing purposes, as the resulting AC will not be verifiable. */ FAKE_SIGNATURE_BITS, /** * Includes a fake critical extension in the generated Attribute Certificate. - *

- * This extension is added for testing scenarios where certificate parsers need to handle + * + *

This extension is added for testing scenarios where certificate parsers need to handle * unknown critical extensions. - *

*/ INCLUDE_FAKE_CRITICAL_EXTENSION, /** * Includes the "No Revocation Available" extension as a critical extension. - *

- * This extension indicates that no revocation information is available for the AC. - *

+ * + *

This extension indicates that no revocation information is available for the AC. */ INCLUDE_CRITICAL_NO_REV_AVAIL_EXTENSION, /** * Includes the Authority Key Identifier (AKID) extension as a critical extension. - *

- * The AKID extension helps in linking the AC to its issuer, making it easier for + * + *

The AKID extension helps in linking the AC to its issuer, making it easier for * verification systems to locate the issuing certificate. - *

*/ INCLUDE_CRITICAL_AKID_EXTENSION, /** * Includes an empty AC Certs extension in the generated Attribute Certificate. - *

- * This is useful for testing scenarios where the extension is expected but contains no + * + *

This is useful for testing scenarios where the extension is expected but contains no * actual certificate information. - *

*/ INCLUDE_EMPTY_AC_CERTS_EXTENSION; // @formatting on @@ -133,9 +121,8 @@ public enum ACGenerationProperties { /** * A ContentSigner implementation that generates random signature bits. - *

- * This is used for testing purposes to create attribute certificates with fake signatures. - *

+ * + *

This is used for testing purposes to create attribute certificates with fake signatures. */ static class RandomContentSigner implements ContentSigner { @@ -184,7 +171,6 @@ public byte[] getSignature() { return sigBytes; } - } /** Fake extension OID used in testing. */ @@ -254,8 +240,8 @@ private ASN1Encodable buildACCertsExtensionContent(EnumSet fqans, - GeneralName policyAuthorityInfo) { + private ASN1Encodable buildFQANsAttributeContent( + List fqans, GeneralName policyAuthorityInfo) { ASN1EncodableVector generalNames = new ASN1EncodableVector(); generalNames.add(policyAuthorityInfo); @@ -288,8 +273,10 @@ private ASN1Encodable buildFQANsAttributeContent(List fqans, return new DERSequence(container); } - private ASN1Encodable buildGAExtensionContent(EnumSet properties, - List gas, GeneralName policyAuthorityInfo) { + private ASN1Encodable buildGAExtensionContent( + EnumSet properties, + List gas, + GeneralName policyAuthorityInfo) { ASN1EncodableVector tagContainer = new ASN1EncodableVector(); ASN1EncodableVector tagSequences = new ASN1EncodableVector(); @@ -315,8 +302,8 @@ private AttributeCertificateHolder buildHolder(X509Certificate holderCert) JcaX509CertificateHolder holderWrappedCert = new JcaX509CertificateHolder(holderCert); - return new AttributeCertificateHolder(holderWrappedCert.getSubject(), - holderCert.getSerialNumber()); + return new AttributeCertificateHolder( + holderWrappedCert.getSubject(), holderCert.getSerialNumber()); } private AttributeCertificateIssuer buildIssuer() throws CertificateEncodingException { @@ -339,11 +326,10 @@ private DERSequence buildTagSequence(VOMSGenericAttribute ga) { tagSequence.add(getDEROctetString(ga.getContext())); return new DERSequence(tagSequence); - } - private ASN1Encodable buildTargetsExtensionContent(EnumSet properties, - List targets) { + private ASN1Encodable buildTargetsExtensionContent( + EnumSet properties, List targets) { ASN1EncodableVector targetSeq = new ASN1EncodableVector(); @@ -376,13 +362,31 @@ private ASN1Encodable buildTargetsExtensionContent(EnumSet fqans, - List gas, List targets, X509Certificate holderCert, - BigInteger serialNumber, Date notBefore, Date notAfter, String voName, String host, - int port) throws VOMSError { - - return generateVOMSAttributeCertificate(defaultGenerationProperties, fqans, gas, targets, - holderCert, serialNumber, notBefore, notAfter, voName, host, port); + public X509AttributeCertificateHolder generateVOMSAttributeCertificate( + List fqans, + List gas, + List targets, + X509Certificate holderCert, + BigInteger serialNumber, + Date notBefore, + Date notAfter, + String voName, + String host, + int port) + throws VOMSError { + + return generateVOMSAttributeCertificate( + defaultGenerationProperties, + fqans, + gas, + targets, + holderCert, + serialNumber, + notBefore, + notAfter, + voName, + host, + port); } /** @@ -403,10 +407,18 @@ public X509AttributeCertificateHolder generateVOMSAttributeCertificate(List generationProperties, List fqans, - List gas, List targets, X509Certificate holderCert, - BigInteger serialNumber, Date notBefore, Date notAfter, String voName, String host, - int port) throws VOMSError { + EnumSet generationProperties, + List fqans, + List gas, + List targets, + X509Certificate holderCert, + BigInteger serialNumber, + Date notBefore, + Date notAfter, + String voName, + String host, + int port) + throws VOMSError { AttributeCertificateHolder holder = null; AttributeCertificateIssuer issuer = null; @@ -424,18 +436,22 @@ public X509AttributeCertificateHolder generateVOMSAttributeCertificate( builder.addAttribute(VOMS_FQANS_OID, buildFQANsAttributeContent(fqans, policyAuthorityInfo)); if (gas != null && !gas.isEmpty()) { - builder.addExtension(VOMS_GENERIC_ATTRS_OID, false, + builder.addExtension( + VOMS_GENERIC_ATTRS_OID, + false, buildGAExtensionContent(generationProperties, gas, policyAuthorityInfo)); } if (targets != null && !targets.isEmpty()) { - builder.addExtension(Extension.targetInformation, true, + builder.addExtension( + Extension.targetInformation, + true, buildTargetsExtensionContent(generationProperties, targets)); } if (!generationProperties.contains(ACGenerationProperties.SKIP_AC_CERTS_EXTENSION)) { - builder.addExtension(VOMS_CERTS_OID, false, - buildACCertsExtensionContent(generationProperties)); + builder.addExtension( + VOMS_CERTS_OID, false, buildACCertsExtensionContent(generationProperties)); } if (generationProperties.contains(ACGenerationProperties.INCLUDE_FAKE_CRITICAL_EXTENSION)) { @@ -445,8 +461,8 @@ public X509AttributeCertificateHolder generateVOMSAttributeCertificate( boolean noRevAvailIsCritical = false; boolean akidIsCritical = false; - if (generationProperties - .contains(ACGenerationProperties.INCLUDE_CRITICAL_NO_REV_AVAIL_EXTENSION)) { + if (generationProperties.contains( + ACGenerationProperties.INCLUDE_CRITICAL_NO_REV_AVAIL_EXTENSION)) { noRevAvailIsCritical = true; } @@ -458,14 +474,13 @@ public X509AttributeCertificateHolder generateVOMSAttributeCertificate( AuthorityKeyIdentifier akid = buildAuthorityKeyIdentifier(); - builder.addExtension(Extension.authorityKeyIdentifier, akidIsCritical, - akid != null ? akid : DERNull.INSTANCE); + builder.addExtension( + Extension.authorityKeyIdentifier, akidIsCritical, akid != null ? akid : DERNull.INSTANCE); return builder.build(getSigner(generationProperties)); } catch (CertificateEncodingException | CertIOException | NoSuchAlgorithmException e) { throw new VOMSError(e.getMessage(), e); } - } /** @@ -485,7 +500,6 @@ public CertificateExtension generateVOMSExtension(List getACsFromVOMSExtension( - byte[] vomsExtension) throws IOException { + public static List getACsFromVOMSExtension(byte[] vomsExtension) + throws IOException { List acs = null; - if (vomsExtension == null) - return Collections.emptyList(); + if (vomsExtension == null) return Collections.emptyList(); acs = new ArrayList(); // Convert extension to a DEROctetString - ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream( - vomsExtension)); + ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream(vomsExtension)); byte[] payload = ((DEROctetString) asn1Stream.readObject()).getOctets(); asn1Stream.close(); @@ -112,8 +102,7 @@ public static List getACsFromVOMSExtension( while (theACs.hasMoreElements()) { - AttributeCertificate parsedAC = - AttributeCertificate.getInstance(theACs.nextElement()); + AttributeCertificate parsedAC = AttributeCertificate.getInstance(theACs.nextElement()); acs.add(parsedAC); } } @@ -122,28 +111,24 @@ public static List getACsFromVOMSExtension( } /** - * Deserializes the VOMS Attribute certificates, if present, in a given - * certificate passed as argument - * - * @param cert - * the {@link X509Certificate} where the ACs will be searched - * @return the possibly empty {@link List} of {@link AttributeCertificate} - * objects extracted from the VOMS extension - * @throws IOException - * in case of deserialization errors + * Deserializes the VOMS Attribute certificates, if present, in a given certificate passed as + * argument + * + * @param cert the {@link X509Certificate} where the ACs will be searched + * @return the possibly empty {@link List} of {@link AttributeCertificate} objects extracted from + * the VOMS extension + * @throws IOException in case of deserialization errors */ - public static List getACsFromCertificate( - X509Certificate cert) throws IOException { + public static List getACsFromCertificate(X509Certificate cert) + throws IOException { return getACsFromVOMSExtension(getVOMSExtensionFromCertificate(cert)); } /** * Deserializes the FQANs contained in a {@link IetfAttrSyntax} object - * - * @param attr - * the {@link IetfAttrSyntax} attribute syntax object containing the - * VOMS extension + * + * @param attr the {@link IetfAttrSyntax} attribute syntax object containing the VOMS extension * @return a {@link List} of FQANs */ private static List deserializeFQANs(IetfAttrSyntax attr) { @@ -155,39 +140,35 @@ private static List deserializeFQANs(IetfAttrSyntax attr) { ASN1OctetString[] values = (ASN1OctetString[]) attr.getValues(); - for (ASN1OctetString s : values) - fqans.add(new String(s.getOctets())); + for (ASN1OctetString s : values) fqans.add(new String(s.getOctets())); return fqans; } @SuppressWarnings("rawtypes") - private static List deserializeACTargets( - X509AttributeCertificateHolder ac) { + private static List deserializeACTargets(X509AttributeCertificateHolder ac) { List targets = new ArrayList(); Extension targetExtension = ac.getExtension(Extension.targetInformation); - if (targetExtension == null) - return targets; + if (targetExtension == null) return targets; - TargetInformation ti = TargetInformation - .getInstance((ASN1Sequence) targetExtension.getParsedValue()); + TargetInformation ti = + TargetInformation.getInstance((ASN1Sequence) targetExtension.getParsedValue()); // Only one Targets according to RFC 3281 Targets asn1TargetContainer = ti.getTargetsObjects()[0]; // The deserialization has to be done by hand since it seems VOMS // does not correctly encode the ACTargets extension... - ASN1Sequence targetSequence = (ASN1Sequence) asn1TargetContainer - .toASN1Primitive(); + ASN1Sequence targetSequence = (ASN1Sequence) asn1TargetContainer.toASN1Primitive(); Target[] asn1Targets = new Target[targetSequence.size()]; int count = 0; - for (Enumeration e = targetSequence.getObjects(); e.hasMoreElements();) { + for (Enumeration e = targetSequence.getObjects(); e.hasMoreElements(); ) { // There's one sequence more than expected here that makes // the bc constructor fail... @@ -202,7 +183,8 @@ private static List deserializeACTargets( GeneralName targetURI = t.getTargetName(); if (targetURI.getTagNo() != GeneralName.uniformResourceIdentifier) - raiseACNonConformantError("wrong AC target extension encoding. Only URI targets are supported."); + raiseACNonConformantError( + "wrong AC target extension encoding. Only URI targets are supported."); String targetString = ((DERIA5String) targetURI.getName()).getString(); targets.add(targetString); @@ -212,48 +194,40 @@ private static List deserializeACTargets( private static void raiseACNonConformantError(String errorString) { - throw new VOMSError("Non conformant VOMS Attribute certificate: " - + errorString); + throw new VOMSError("Non conformant VOMS Attribute certificate: " + errorString); } /** - * Peforms some sanity checks on the format of the policy authority field - * found in a VOMS extension. The enforced format is: vo://host:port - * - * @param attr - * the {@link IetfAttrSyntax} attribute syntax object containing the - * VOMS extension + * Peforms some sanity checks on the format of the policy authority field found in a VOMS + * extension. The enforced format is: vo://host:port + * + * @param attr the {@link IetfAttrSyntax} attribute syntax object containing the VOMS extension * @return the validated policy authority as a {@link String} */ private static String policyAuthoritySanityChecks(IetfAttrSyntax attr) { // The policy authority value is encoded as a DERIA5String - String policyAuthority = ((DERIA5String) attr.getPolicyAuthority() - .getNames()[0].getName()).getString(); + String policyAuthority = + ((DERIA5String) attr.getPolicyAuthority().getNames()[0].getName()).getString(); // PolicyAuthority scheme: ://: int index = policyAuthority.indexOf(POLICY_AUTHORITY_SEP); if ((index < 0) || (index == policyAuthority.length() - 1)) - raiseACNonConformantError("unsupported policy authority encoding '" - + policyAuthority + "'"); + raiseACNonConformantError("unsupported policy authority encoding '" + policyAuthority + "'"); return policyAuthority; - } /** * Deserializes the information in a list of VOMS attribute certificates. - * - * @param acs - * a {@link List} of VOMS acs + * + * @param acs a {@link List} of VOMS acs * @return a possibly empty list of {@link VOMSAttribute} */ - public static List deserializeVOMSAttributes( - List acs) { + public static List deserializeVOMSAttributes(List acs) { - if (acs == null || acs.size() == 0) - return Collections.emptyList(); + if (acs == null || acs.size() == 0) return Collections.emptyList(); List attributes = new ArrayList(); for (AttributeCertificate a : acs) { @@ -265,39 +239,35 @@ public static List deserializeVOMSAttributes( /** * Deserializes the information in a VOMS attribute certificate. - * - * @param ac - * a VOMS {@link AttributeCertificate} - * @return a {@link VOMSAttribute} object which provides more convenient - * access to the VOMS authorization information + * + * @param ac a VOMS {@link AttributeCertificate} + * @return a {@link VOMSAttribute} object which provides more convenient access to the VOMS + * authorization information */ public static VOMSAttribute deserializeVOMSAttributes(AttributeCertificate ac) { VOMSAttributesImpl attrs = new VOMSAttributesImpl(); - X509AttributeCertificateHolder acHolder = new X509AttributeCertificateHolder( - ac); + X509AttributeCertificateHolder acHolder = new X509AttributeCertificateHolder(ac); Attribute[] asn1Attrs = acHolder.getAttributes(VOMS_FQANS_OID); for (Attribute a : asn1Attrs) { - ASN1Primitive theVOMSDerObject = a.getAttributeValues()[0] - .toASN1Primitive(); + ASN1Primitive theVOMSDerObject = a.getAttributeValues()[0].toASN1Primitive(); - IetfAttrSyntax attrSyntax = IetfAttrSyntax.getInstance(ASN1Sequence - .getInstance(theVOMSDerObject)); + IetfAttrSyntax attrSyntax = + IetfAttrSyntax.getInstance(ASN1Sequence.getInstance(theVOMSDerObject)); String policyAuthority = policyAuthoritySanityChecks(attrSyntax); // The policy authority string has the following format: // ://: - attrs.setVO(policyAuthority.substring(0, - policyAuthority.indexOf(POLICY_AUTHORITY_SEP))); - attrs.setHost(policyAuthority.substring( - policyAuthority.indexOf(POLICY_AUTHORITY_SEP) + 3, - policyAuthority.lastIndexOf(":"))); - attrs.setPort(Integer.parseInt(policyAuthority.substring(policyAuthority - .lastIndexOf(":") + 1))); + attrs.setVO(policyAuthority.substring(0, policyAuthority.indexOf(POLICY_AUTHORITY_SEP))); + attrs.setHost( + policyAuthority.substring( + policyAuthority.indexOf(POLICY_AUTHORITY_SEP) + 3, policyAuthority.lastIndexOf(":"))); + attrs.setPort( + Integer.parseInt(policyAuthority.substring(policyAuthority.lastIndexOf(":") + 1))); attrs.setFQANs(deserializeFQANs(attrSyntax)); @@ -312,16 +282,13 @@ public static VOMSAttribute deserializeVOMSAttributes(AttributeCertificate ac) { try { - attrs.setIssuer(new X500Principal(acHolder.getIssuer().getNames()[0] - .getEncoded())); - attrs.setHolder(new X500Principal(acHolder.getHolder().getIssuer()[0] - .getEncoded())); + attrs.setIssuer(new X500Principal(acHolder.getIssuer().getNames()[0].getEncoded())); + attrs.setHolder(new X500Principal(acHolder.getHolder().getIssuer()[0].getEncoded())); attrs.setHolderSerialNumber(acHolder.getHolder().getSerialNumber()); } catch (IOException e) { throw new VOMSError( - "Error parsing attribute certificate issuer or holder name: " - + e.getMessage(), e); + "Error parsing attribute certificate issuer or holder name: " + e.getMessage(), e); } } @@ -330,21 +297,17 @@ public static VOMSAttribute deserializeVOMSAttributes(AttributeCertificate ac) { /** * Deserializes the VOMS generic attributes - * - * @param ac - * the VOMS {@link X509AttributeCertificateHolder} - * @return the {@link List} of {@link VOMSGenericAttribute} contained in the - * ac + * + * @param ac the VOMS {@link X509AttributeCertificateHolder} + * @return the {@link List} of {@link VOMSGenericAttribute} contained in the ac */ - private static List deserializeGAs( - X509AttributeCertificateHolder ac) { + private static List deserializeGAs(X509AttributeCertificateHolder ac) { List gas = new ArrayList(); Extension gasExtension = ac.getExtension(VOMS_GENERIC_ATTRS_OID); - if (gasExtension == null) - return gas; + if (gasExtension == null) return gas; // SEQUENCE of TagList - contains just one taglist element ASN1Sequence tagContainerSeq = (ASN1Sequence) gasExtension.getParsedValue(); @@ -353,13 +316,11 @@ private static List deserializeGAs( // TagList - this also should be a sigle element sequence ASN1Sequence tagListSeq = (ASN1Sequence) tagContainerSeq.getObjectAt(0); - if (tagListSeq.size() > 1) - raiseACNonConformantError("unsupported taglist format."); + if (tagListSeq.size() > 1) raiseACNonConformantError("unsupported taglist format."); // This TagList sequence is empty, gLite 3.2 VOMS versions had a bug // that added the extension even there were no attributes encoded... - if (tagListSeq.size() == 0) - return gas; + if (tagListSeq.size() == 0) return gas; // Down one level tagListSeq = (ASN1Sequence) tagListSeq.getObjectAt(0); @@ -377,17 +338,16 @@ private static List deserializeGAs( ASN1Sequence theActualTag = e.nextElement(); - if (theActualTag.size() != 3) - raiseACNonConformantError("unsupported tag format."); + if (theActualTag.size() != 3) raiseACNonConformantError("unsupported tag format."); VOMSGenericAttributeImpl attribute = new VOMSGenericAttributeImpl(); - attribute.setName(new String(DEROctetString.getInstance( - theActualTag.getObjectAt(0)).getOctets())); - attribute.setValue(new String(DEROctetString.getInstance( - theActualTag.getObjectAt(1)).getOctets())); - attribute.setContext(new String(DEROctetString.getInstance( - theActualTag.getObjectAt(2)).getOctets())); + attribute.setName( + new String(DEROctetString.getInstance(theActualTag.getObjectAt(0)).getOctets())); + attribute.setValue( + new String(DEROctetString.getInstance(theActualTag.getObjectAt(1)).getOctets())); + attribute.setContext( + new String(DEROctetString.getInstance(theActualTag.getObjectAt(2)).getOctets())); gas.add(attribute); } @@ -397,24 +357,22 @@ private static List deserializeGAs( /** * Deserializes the VOMS ACCerts extension - * - * @param ac - * the VOMS {@link X509AttributeCertificateHolder} + * + * @param ac the VOMS {@link X509AttributeCertificateHolder} * @return the parsed array of {@link X509Certificate} */ - private static X509Certificate[] deserializeACCerts( - X509AttributeCertificateHolder ac) { + private static X509Certificate[] deserializeACCerts(X509AttributeCertificateHolder ac) { List certs = new ArrayList(); - + Extension e = ac.getExtension(VOMS_CERTS_OID); if (e == null) { return null; } - + ASN1Sequence certSeq = (ASN1Sequence) e.getParsedValue(); - + if (certSeq.size() != 1) { raiseACNonConformantError("unsupported accerts format."); } @@ -423,15 +381,15 @@ private static X509Certificate[] deserializeACCerts( @SuppressWarnings("unchecked") Enumeration encodedCerts = certSeq.getObjects(); - + CertificateFactory cf = new CertificateFactory(); while (encodedCerts.hasMoreElements()) { DLSequence s = encodedCerts.nextElement(); - + X509Certificate theCert; - + try { ASN1InputStream stream = new ASN1InputStream(s.getEncoded()); theCert = (X509Certificate) cf.engineGenerateCertificate(stream); @@ -439,14 +397,12 @@ private static X509Certificate[] deserializeACCerts( } catch (CertificateParsingException ex) { throw new VOMSError("Certificate parsing error: " + ex.getMessage(), ex); } catch (CertificateEncodingException ex) { - throw new VOMSError("Certificate encoding error: " + ex.getMessage(), - ex); + throw new VOMSError("Certificate encoding error: " + ex.getMessage(), ex); } catch (CertificateException ex) { - throw new VOMSError("Error generating certificate from parsed data: " - + ex.getMessage(), ex); + throw new VOMSError( + "Error generating certificate from parsed data: " + ex.getMessage(), ex); } catch (IOException ex) { - throw new VOMSError("Certficate parsing error : "+ex.getMessage(), - ex); + throw new VOMSError("Certficate parsing error : " + ex.getMessage(), ex); } certs.add(theCert); @@ -455,7 +411,5 @@ private static X509Certificate[] deserializeACCerts( return certs.toArray(new X509Certificate[certs.size()]); } - private VOMSACUtils() { - - } + private VOMSACUtils() {} } diff --git a/src/main/java/org/italiangrid/voms/asn1/VOMSConstants.java b/src/main/java/org/italiangrid/voms/asn1/VOMSConstants.java index 8fd3238..cd9e5b2 100644 --- a/src/main/java/org/italiangrid/voms/asn1/VOMSConstants.java +++ b/src/main/java/org/italiangrid/voms/asn1/VOMSConstants.java @@ -7,45 +7,39 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; - import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x509.Extension; /** * A set of useful constants for ASN.1 parsing of VOMS attributes. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface VOMSConstants { - /** - * The VOMS attribute certificate extension OID. - */ - public final ASN1ObjectIdentifier VOMS_EXTENSION_OID = new ASN1ObjectIdentifier( - "1.3.6.1.4.1.8005.100.100.5"); - - /** - * The VOMS attributes OID. - */ - public final ASN1ObjectIdentifier VOMS_FQANS_OID = new ASN1ObjectIdentifier( - "1.3.6.1.4.1.8005.100.100.4"); - - /** - * The VOMS Certs extension OID. - */ - public final ASN1ObjectIdentifier VOMS_CERTS_OID = new ASN1ObjectIdentifier( - "1.3.6.1.4.1.8005.100.100.10"); - - /** - * The VOMS Generic attributes extension OID. - */ - public final ASN1ObjectIdentifier VOMS_GENERIC_ATTRS_OID = new ASN1ObjectIdentifier( - "1.3.6.1.4.1.8005.100.100.11"); - - public final Set VOMS_HANDLED_EXTENSIONS = new HashSet( - Arrays.asList(VOMS_FQANS_OID, VOMS_CERTS_OID, VOMS_GENERIC_ATTRS_OID, - Extension.targetInformation, Extension.noRevAvail, - Extension.authorityKeyIdentifier)); - + /** The VOMS attribute certificate extension OID. */ + public final ASN1ObjectIdentifier VOMS_EXTENSION_OID = + new ASN1ObjectIdentifier("1.3.6.1.4.1.8005.100.100.5"); + + /** The VOMS attributes OID. */ + public final ASN1ObjectIdentifier VOMS_FQANS_OID = + new ASN1ObjectIdentifier("1.3.6.1.4.1.8005.100.100.4"); + + /** The VOMS Certs extension OID. */ + public final ASN1ObjectIdentifier VOMS_CERTS_OID = + new ASN1ObjectIdentifier("1.3.6.1.4.1.8005.100.100.10"); + + /** The VOMS Generic attributes extension OID. */ + public final ASN1ObjectIdentifier VOMS_GENERIC_ATTRS_OID = + new ASN1ObjectIdentifier("1.3.6.1.4.1.8005.100.100.11"); + + public final Set VOMS_HANDLED_EXTENSIONS = + new HashSet( + Arrays.asList( + VOMS_FQANS_OID, + VOMS_CERTS_OID, + VOMS_GENERIC_ATTRS_OID, + Extension.targetInformation, + Extension.noRevAvail, + Extension.authorityKeyIdentifier)); } diff --git a/src/main/java/org/italiangrid/voms/asn1/package-info.java b/src/main/java/org/italiangrid/voms/asn1/package-info.java index 96008c2..ef62459 100644 --- a/src/main/java/org/italiangrid/voms/asn1/package-info.java +++ b/src/main/java/org/italiangrid/voms/asn1/package-info.java @@ -3,8 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 /** - * This package provides classes and utilities that deal with serialization and - * deserialization of VOMS attributes from ASN.1 streams. + * This package provides classes and utilities that deal with serialization and deserialization of + * VOMS attributes from ASN.1 streams. */ package org.italiangrid.voms.asn1; - diff --git a/src/main/java/org/italiangrid/voms/credential/FilePermissionError.java b/src/main/java/org/italiangrid/voms/credential/FilePermissionError.java index 28fb2b5..82ade44 100644 --- a/src/main/java/org/italiangrid/voms/credential/FilePermissionError.java +++ b/src/main/java/org/italiangrid/voms/credential/FilePermissionError.java @@ -7,9 +7,8 @@ import org.italiangrid.voms.VOMSError; /** - * This error is raised when there is an attempt to load a credential which has - * the wrong file permissions - * + * This error is raised when there is an attempt to load a credential which has the wrong file + * permissions */ public class FilePermissionError extends VOMSError { @@ -23,9 +22,6 @@ public FilePermissionError(String message, Throwable cause) { super(message, cause); } - /** - * - */ + /** */ private static final long serialVersionUID = 1L; - } diff --git a/src/main/java/org/italiangrid/voms/credential/LoadCredentialsEventListener.java b/src/main/java/org/italiangrid/voms/credential/LoadCredentialsEventListener.java index 907b85e..c74ee86 100644 --- a/src/main/java/org/italiangrid/voms/credential/LoadCredentialsEventListener.java +++ b/src/main/java/org/italiangrid/voms/credential/LoadCredentialsEventListener.java @@ -5,43 +5,31 @@ package org.italiangrid.voms.credential; /** - * A {@link LoadCredentialsEventListener} is notified of the outcome of load - * credentials operations. - * - * @author andreaceccanti + * A {@link LoadCredentialsEventListener} is notified of the outcome of load credentials operations. * + * @author andreaceccanti */ public interface LoadCredentialsEventListener { /** - * Informs that credentials are been looked for in the locations passed as - * argument. - * - * @param locations - * the locations (as strings) where the credentials - * are being searched + * Informs that credentials are been looked for in the locations passed as argument. + * + * @param locations the locations (as strings) where the credentials are being searched */ public void notifyCredentialLookup(String... locations); /** - * Informs that credentials have been succesfully loaded from the credentials - * passed as argument. - * - * @param locations - * the locations (as strings) where the credentials - * are being searched + * Informs that credentials have been succesfully loaded from the credentials passed as argument. + * + * @param locations the locations (as strings) where the credentials are being searched */ public void notifyLoadCredentialSuccess(String... locations); /** - * Informs that credentials could not be loaded form the locations passed as - * argument. - * - * @param error - * the {@link Throwable} that caused the credential load operation to - * fail - * @param locations - * the locations where the credentials where loaded from + * Informs that credentials could not be loaded form the locations passed as argument. + * + * @param error the {@link Throwable} that caused the credential load operation to fail + * @param locations the locations where the credentials where loaded from */ public void notifyLoadCredentialFailure(Throwable error, String... locations); } diff --git a/src/main/java/org/italiangrid/voms/credential/LoadCredentialsStrategy.java b/src/main/java/org/italiangrid/voms/credential/LoadCredentialsStrategy.java index 98b6766..efbd54a 100644 --- a/src/main/java/org/italiangrid/voms/credential/LoadCredentialsStrategy.java +++ b/src/main/java/org/italiangrid/voms/credential/LoadCredentialsStrategy.java @@ -4,27 +4,22 @@ package org.italiangrid.voms.credential; -import eu.emi.security.authn.x509.helpers.PasswordSupplier; - import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.helpers.PasswordSupplier; /** * A strategy to load user credentials - * - * @author andreaceccanti * + * @author andreaceccanti */ public interface LoadCredentialsStrategy { /** * Loads a user credential - * - * @param passwordFinder - * the password finder used to potentially decrypt the credential - * encrypted private key. - * - * @return an {@link X509Credential}, or null if no credential - * was found + * + * @param passwordFinder the password finder used to potentially decrypt the credential encrypted + * private key. + * @return an {@link X509Credential}, or null if no credential was found */ public X509Credential loadCredentials(PasswordSupplier passwordFinder); } diff --git a/src/main/java/org/italiangrid/voms/credential/ProxyNamingPolicy.java b/src/main/java/org/italiangrid/voms/credential/ProxyNamingPolicy.java index ae84912..79908a3 100644 --- a/src/main/java/org/italiangrid/voms/credential/ProxyNamingPolicy.java +++ b/src/main/java/org/italiangrid/voms/credential/ProxyNamingPolicy.java @@ -6,21 +6,17 @@ /** * A {@link ProxyNamingPolicy} defines the naming policy for a VOMS proxy. - * - * @author andreaceccanti * + * @author andreaceccanti */ public interface ProxyNamingPolicy { /** * Builds the file name of a VOMS proxy - * - * @param tmpPath - * the path of the temporary directory of the system - * @param userId - * the effective user id the user for which the proxy is created + * + * @param tmpPath the path of the temporary directory of the system + * @param userId the effective user id the user for which the proxy is created * @return a {@link String} representing the proxy file name */ public String buildProxyFileName(String tmpPath, int userId); - } diff --git a/src/main/java/org/italiangrid/voms/credential/UserCredentials.java b/src/main/java/org/italiangrid/voms/credential/UserCredentials.java index acda708..06979c9 100644 --- a/src/main/java/org/italiangrid/voms/credential/UserCredentials.java +++ b/src/main/java/org/italiangrid/voms/credential/UserCredentials.java @@ -4,21 +4,19 @@ package org.italiangrid.voms.credential; +import eu.emi.security.authn.x509.X509Credential; import eu.emi.security.authn.x509.helpers.PasswordSupplier; import org.italiangrid.voms.credential.impl.DefaultLoadCredentialsStrategy; -import eu.emi.security.authn.x509.X509Credential; - /** - * This class implements convenience methods to load X509 user credentials in - * PEM or PKCS12 format. - * + * This class implements convenience methods to load X509 user credentials in PEM or PKCS12 format. + * * @author Andrea Ceccanti - * */ public class UserCredentials { - private static LoadCredentialsStrategy loadCredentialsStrategy = new DefaultLoadCredentialsStrategy(); + private static LoadCredentialsStrategy loadCredentialsStrategy = + new DefaultLoadCredentialsStrategy(); public static void setLoadCredentialsStrategy(LoadCredentialsStrategy strategy) { @@ -32,13 +30,14 @@ public static X509Credential loadCredentials() { public static X509Credential loadCredentials(final char[] keyPassword) { - PasswordSupplier pf = new PasswordSupplier() { + PasswordSupplier pf = + new PasswordSupplier() { - public char[] getPassword() { + public char[] getPassword() { - return keyPassword; - } - }; + return keyPassword; + } + }; return loadCredentialsStrategy.loadCredentials(pf); } diff --git a/src/main/java/org/italiangrid/voms/credential/VOMSEnvironmentVariables.java b/src/main/java/org/italiangrid/voms/credential/VOMSEnvironmentVariables.java index d198c41..5716a16 100644 --- a/src/main/java/org/italiangrid/voms/credential/VOMSEnvironmentVariables.java +++ b/src/main/java/org/italiangrid/voms/credential/VOMSEnvironmentVariables.java @@ -13,5 +13,4 @@ public interface VOMSEnvironmentVariables { public static final String X509_USER_KEY = "X509_USER_KEY"; public static final String PKCS12_USER_CERT = "PKCS12_USER_CERT"; public static final String VOMS_USER_ID = "VOMS_UID"; - -} \ No newline at end of file +} diff --git a/src/main/java/org/italiangrid/voms/credential/impl/AbstractLoadCredentialsStrategy.java b/src/main/java/org/italiangrid/voms/credential/impl/AbstractLoadCredentialsStrategy.java index 74aa221..2fecaf1 100644 --- a/src/main/java/org/italiangrid/voms/credential/impl/AbstractLoadCredentialsStrategy.java +++ b/src/main/java/org/italiangrid/voms/credential/impl/AbstractLoadCredentialsStrategy.java @@ -4,58 +4,47 @@ package org.italiangrid.voms.credential.impl; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.helpers.PasswordSupplier; +import eu.emi.security.authn.x509.impl.KeystoreCredential; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; - -import eu.emi.security.authn.x509.helpers.PasswordSupplier; import org.italiangrid.voms.credential.LoadCredentialsEventListener; import org.italiangrid.voms.credential.LoadCredentialsStrategy; import org.italiangrid.voms.credential.VOMSEnvironmentVariables; import org.italiangrid.voms.util.FilePermissionHelper; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.KeystoreCredential; -import eu.emi.security.authn.x509.impl.PEMCredential; - /** - * Base class for load credentials strategy providing utility classes for - * loading credentials from the filesystem and notifying the results of load - * operations to interested listeners (via {@link LoadCredentialsEventListener} - * ). - * - * @author andreaceccanti + * Base class for load credentials strategy providing utility classes for loading credentials from + * the filesystem and notifying the results of load operations to interested listeners (via {@link + * LoadCredentialsEventListener} ). * + * @author andreaceccanti */ -public abstract class AbstractLoadCredentialsStrategy implements - LoadCredentialsStrategy, VOMSEnvironmentVariables { +public abstract class AbstractLoadCredentialsStrategy + implements LoadCredentialsStrategy, VOMSEnvironmentVariables { - /** - * The {@link LoadCredentialsEventListener} that is notified of load - * credentials outcome. - */ + /** The {@link LoadCredentialsEventListener} that is notified of load credentials outcome. */ LoadCredentialsEventListener listener; /** * Constructor that let client pass in a {@link LoadCredentialsEventListener}. - * - * @param listener - * the listener that is notified of load credential events from this - * {@link AbstractLoadCredentialsStrategy}. + * + * @param listener the listener that is notified of load credential events from this {@link + * AbstractLoadCredentialsStrategy}. */ - protected AbstractLoadCredentialsStrategy( - LoadCredentialsEventListener listener) { + protected AbstractLoadCredentialsStrategy(LoadCredentialsEventListener listener) { this.listener = listener; } /** * Convenience method to check if a file exists and is readable - * - * @param filename - * the file to be checked - * @return true if the file exists and is readable, - * false otherwise + * + * @param filename the file to be checked + * @return true if the file exists and is readable, false otherwise */ protected boolean fileExistsAndIsReadable(String filename) { @@ -64,21 +53,17 @@ protected boolean fileExistsAndIsReadable(String filename) { } /** - * Loads a PEM X.509 credential and notifies the registered - * {@link LoadCredentialsEventListener} of the load operation outcome. - * - * @param privateKeyPath - * the path to the private key - * @param certificatePath - * the path to the certificate - * @param pf - * a {@link PasswordSupplier} used to resolve the private key password - * when needed - * @return the loaded {@link X509Credential}, or null if the - * credential couldn't be loaded + * Loads a PEM X.509 credential and notifies the registered {@link LoadCredentialsEventListener} + * of the load operation outcome. + * + * @param privateKeyPath the path to the private key + * @param certificatePath the path to the certificate + * @param pf a {@link PasswordSupplier} used to resolve the private key password when needed + * @return the loaded {@link X509Credential}, or null if the credential couldn't be + * loaded */ - protected X509Credential loadPEMCredential(String privateKeyPath, - String certificatePath, PasswordSupplier pf) { + protected X509Credential loadPEMCredential( + String privateKeyPath, String certificatePath, PasswordSupplier pf) { PEMCredential cred = null; @@ -88,8 +73,9 @@ protected X509Credential loadPEMCredential(String privateKeyPath, FilePermissionHelper.checkPrivateKeyPermissions(privateKeyPath); - cred = new PEMCredential(new FileInputStream(privateKeyPath), - new FileInputStream(certificatePath), pf); + cred = + new PEMCredential( + new FileInputStream(privateKeyPath), new FileInputStream(certificatePath), pf); listener.notifyLoadCredentialSuccess(privateKeyPath, certificatePath); @@ -99,22 +85,18 @@ protected X509Credential loadPEMCredential(String privateKeyPath, } return cred; - } /** - * Loads a PCKS12 X.509 credential and notifies the registered - * {@link LoadCredentialsEventListener} of the load operation outcome. - * - * @param pkcs12FilePath - * the path to the pkcs12 credential - * @param pf - * a {@link PasswordSupplier} used to resolve the private key password - * @return the loaded {@link X509Credential}, or null if the - * credential couldn't be loaded + * Loads a PCKS12 X.509 credential and notifies the registered {@link + * LoadCredentialsEventListener} of the load operation outcome. + * + * @param pkcs12FilePath the path to the pkcs12 credential + * @param pf a {@link PasswordSupplier} used to resolve the private key password + * @return the loaded {@link X509Credential}, or null if the credential couldn't be + * loaded */ - protected X509Credential loadPKCS12Credential(String pkcs12FilePath, - PasswordSupplier pf) { + protected X509Credential loadPKCS12Credential(String pkcs12FilePath, PasswordSupplier pf) { KeystoreCredential cred = null; @@ -127,8 +109,7 @@ protected X509Credential loadPKCS12Credential(String pkcs12FilePath, FilePermissionHelper.checkPKCS12Permissions(pkcs12FilePath); - cred = new KeystoreCredential(pkcs12FilePath, keyPassword, keyPassword, - null, "PKCS12"); + cred = new KeystoreCredential(pkcs12FilePath, keyPassword, keyPassword, null, "PKCS12"); listener.notifyLoadCredentialSuccess(pkcs12FilePath); } catch (Throwable t) { @@ -137,20 +118,19 @@ protected X509Credential loadPKCS12Credential(String pkcs12FilePath, } } else - listener.notifyLoadCredentialFailure(new FileNotFoundException( - pkcs12FilePath + " (cannot read file)"), pkcs12FilePath); + listener.notifyLoadCredentialFailure( + new FileNotFoundException(pkcs12FilePath + " (cannot read file)"), pkcs12FilePath); return cred; } /** - * Loads an X.509 proxy credential and notifies the registered - * {@link LoadCredentialsEventListener} of the load operation outcome. - * - * @param proxyPath - * the path to the proxy credential - * @return the loaded {@link X509Credential}, or null if the - * credential couldn't be loaded + * Loads an X.509 proxy credential and notifies the registered {@link + * LoadCredentialsEventListener} of the load operation outcome. + * + * @param proxyPath the path to the proxy credential + * @return the loaded {@link X509Credential}, or null if the credential couldn't be + * loaded */ protected X509Credential loadProxyCredential(String proxyPath) { diff --git a/src/main/java/org/italiangrid/voms/credential/impl/DefaultLoadCredentialsStrategy.java b/src/main/java/org/italiangrid/voms/credential/impl/DefaultLoadCredentialsStrategy.java index b67cb35..336262c 100644 --- a/src/main/java/org/italiangrid/voms/credential/impl/DefaultLoadCredentialsStrategy.java +++ b/src/main/java/org/italiangrid/voms/credential/impl/DefaultLoadCredentialsStrategy.java @@ -4,41 +4,33 @@ package org.italiangrid.voms.credential.impl; +import eu.emi.security.authn.x509.X509Credential; import eu.emi.security.authn.x509.helpers.PasswordSupplier; import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.credential.LoadCredentialsEventListener; import org.italiangrid.voms.credential.ProxyNamingPolicy; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.X509Credential; - /** * The default strategy used to load user credentials when no file is explicitly pointed out by the * user of this API. - * - * Credentials are searched in the following places (in sequence): - * + * + *

Credentials are searched in the following places (in sequence): + * *

    - * - *
  • If the X509_USER_CERT and X509_USER_KEY environment - * variables are set, their values are used to load the user credentials
  • - * - *
  • If the X509_USER_CERT and X509_USER_KEY system properties - * are set, their values are used to load the user credentials
  • - * - *
  • If the PKCS12_USER_CERT environment variable is set, its value is used to - * load the user credentials.
  • - * - *
  • If the PKCS12_USER_CERT system property is set, its value is used to load - * the user credentials.
  • - * - *
  • The content of the .globus directory in the user's home is searched for a PEM - * certificate (in the usercert.pem and userkey.pem files).
  • - * - *
  • The content of the .globus directory in the user's home is searched for a PKC12 certificate - * (in the usercert.p12 file).
  • + *
  • If the X509_USER_CERT and X509_USER_KEY environment + * variables are set, their values are used to load the user credentials + *
  • If the X509_USER_CERT and X509_USER_KEY system properties + * are set, their values are used to load the user credentials + *
  • If the PKCS12_USER_CERT environment variable is set, its value is used + * to load the user credentials. + *
  • If the PKCS12_USER_CERT system property is set, its value is used to + * load the user credentials. + *
  • The content of the .globus directory in the user's home is searched for a PEM + * certificate (in the usercert.pem and userkey.pem files). + *
  • The content of the .globus directory in the user's home is searched for a PKC12 certificate + * (in the usercert.p12 file). *
- * */ public class DefaultLoadCredentialsStrategy extends AbstractLoadCredentialsStrategy { @@ -62,16 +54,15 @@ public class DefaultLoadCredentialsStrategy extends AbstractLoadCredentialsStrat * @param tempDir the temporary directory path * @param listener event listener for credential loading */ - public DefaultLoadCredentialsStrategy(String homeFolder, String tempDir, - LoadCredentialsEventListener listener) { + public DefaultLoadCredentialsStrategy( + String homeFolder, String tempDir, LoadCredentialsEventListener listener) { super(listener); this.home = homeFolder; this.tmpDir = tempDir; - if (home == null) - throw new VOMSError(HOME_PROPERTY + " not found in system properties!"); + if (home == null) throw new VOMSError(HOME_PROPERTY + " not found in system properties!"); } /** @@ -84,11 +75,12 @@ public DefaultLoadCredentialsStrategy(String homeFolder) { this(homeFolder, System.getProperty(TMPDIR_PROPERTY), NullListener.INSTANCE); } - /** - * Constructs a strategy using default system properties. - */ + /** Constructs a strategy using default system properties. */ public DefaultLoadCredentialsStrategy() { - this(System.getProperty(HOME_PROPERTY), System.getProperty(TMPDIR_PROPERTY), + + this( + System.getProperty(HOME_PROPERTY), + System.getProperty(TMPDIR_PROPERTY), NullListener.INSTANCE); } @@ -98,6 +90,7 @@ public DefaultLoadCredentialsStrategy() { * @param listener the credential loading event listener */ public DefaultLoadCredentialsStrategy(LoadCredentialsEventListener listener) { + this(System.getProperty(HOME_PROPERTY), System.getProperty(TMPDIR_PROPERTY), listener); } @@ -108,9 +101,9 @@ public DefaultLoadCredentialsStrategy(LoadCredentialsEventListener listener) { * @return the property value, or null if not found */ public String getFromEnvOrSystemProperty(String propName) { + String val = System.getenv(propName); - if (val == null) - val = System.getProperty(propName); + if (val == null) val = System.getProperty(propName); return val; } @@ -121,17 +114,15 @@ public String getFromEnvOrSystemProperty(String propName) { * @return the loaded credentials */ public X509Credential loadCredentials(PasswordSupplier pf) { + if (pf == null) throw new IllegalArgumentException("Please provide a non-null password finder!"); try { X509Credential cred = loadPEMCredentialFromEnv(pf); - if (cred == null) - cred = loadPKCS12CredentialFromEnv(pf); - if (cred == null) - cred = loadPEMCredentialsFromGlobusDir(pf); - if (cred == null) - cred = loadPKCS12CredentialsFromGlobusDir(pf); + if (cred == null) cred = loadPKCS12CredentialFromEnv(pf); + if (cred == null) cred = loadPEMCredentialsFromGlobusDir(pf); + if (cred == null) cred = loadPKCS12CredentialsFromGlobusDir(pf); return cred; } catch (Exception e) { throw new VOMSError("Error loading credential: " + e.getMessage(), e); @@ -144,6 +135,7 @@ public X509Credential loadCredentials(PasswordSupplier pf) { * @return the loaded proxy credential or null if not found */ protected X509Credential loadProxyFromUID() { + String uid = getFromEnvOrSystemProperty(VOMS_USER_ID); if (uid != null) { String proxyFile = proxyPathBuilder.buildProxyFileName(tmpDir, Integer.parseInt(uid)); @@ -158,9 +150,9 @@ protected X509Credential loadProxyFromUID() { * @return the loaded proxy credential or null if not found */ protected X509Credential loadProxyFromEnv() { + String proxyPath = getFromEnvOrSystemProperty(X509_USER_PROXY); - if (proxyPath != null) - return loadProxyCredential(proxyPath); + if (proxyPath != null) return loadProxyCredential(proxyPath); return null; } @@ -171,6 +163,7 @@ protected X509Credential loadProxyFromEnv() { * @return the loaded credential or null if not found */ protected X509Credential loadPEMCredentialFromEnv(PasswordSupplier pf) { + String certPath = getFromEnvOrSystemProperty(X509_USER_CERT); String keyPath = getFromEnvOrSystemProperty(X509_USER_KEY); if (certPath != null && keyPath != null) { @@ -186,6 +179,7 @@ protected X509Credential loadPEMCredentialFromEnv(PasswordSupplier pf) { * @return the loaded credential or null if not found */ protected X509Credential loadPKCS12CredentialFromEnv(PasswordSupplier pf) { + String pkcs12Path = getFromEnvOrSystemProperty(PKCS12_USER_CERT); if (pkcs12Path != null) { return loadPKCS12Credential(pkcs12Path, pf); @@ -200,6 +194,7 @@ protected X509Credential loadPKCS12CredentialFromEnv(PasswordSupplier pf) { * @return the loaded credential or null if not found */ protected X509Credential loadPKCS12CredentialsFromGlobusDir(PasswordSupplier pf) { + String credPath = String.format("%s/%s", home, GLOBUS_PKCS12_CRED_PATH_SUFFIX); return loadPKCS12Credential(credPath, pf); } @@ -211,6 +206,7 @@ protected X509Credential loadPKCS12CredentialsFromGlobusDir(PasswordSupplier pf) * @return the loaded credential or null if not found */ protected X509Credential loadPEMCredentialsFromGlobusDir(PasswordSupplier pf) { + String certPath = String.format("%s/%s", home, GLOBUS_PEM_CERT_PATH_SUFFIX); String keyPath = String.format("%s/%s", home, GLOBUS_PEM_KEY_PATH_SUFFIX); return loadPEMCredential(keyPath, certPath, pf); diff --git a/src/main/java/org/italiangrid/voms/credential/impl/DefaultProxyPathBuilder.java b/src/main/java/org/italiangrid/voms/credential/impl/DefaultProxyPathBuilder.java index 9260974..a4dde23 100644 --- a/src/main/java/org/italiangrid/voms/credential/impl/DefaultProxyPathBuilder.java +++ b/src/main/java/org/italiangrid/voms/credential/impl/DefaultProxyPathBuilder.java @@ -12,5 +12,4 @@ public String buildProxyFileName(String tmpPath, int userId) { return String.format("%s/x509up_u%d", tmpPath, userId); } - } diff --git a/src/main/java/org/italiangrid/voms/credential/impl/package-info.java b/src/main/java/org/italiangrid/voms/credential/impl/package-info.java index e8a3109..ffb900d 100644 --- a/src/main/java/org/italiangrid/voms/credential/impl/package-info.java +++ b/src/main/java/org/italiangrid/voms/credential/impl/package-info.java @@ -4,8 +4,7 @@ /** * This package provides the implementation of the user credentials loading APIs. - * - * @author andreaceccanti * + * @author andreaceccanti */ -package org.italiangrid.voms.credential.impl; \ No newline at end of file +package org.italiangrid.voms.credential.impl; diff --git a/src/main/java/org/italiangrid/voms/credential/package-info.java b/src/main/java/org/italiangrid/voms/credential/package-info.java index 16a97a4..40b8c6b 100644 --- a/src/main/java/org/italiangrid/voms/credential/package-info.java +++ b/src/main/java/org/italiangrid/voms/credential/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the API for loading user credentials. - */ +/** This package provides the API for loading user credentials. */ package org.italiangrid.voms.credential; - diff --git a/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorCode.java b/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorCode.java index ea894a8..415d765 100644 --- a/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorCode.java +++ b/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorCode.java @@ -6,9 +6,8 @@ /** * VOMS validation error codes. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public enum VOMSValidationErrorCode { @@ -16,10 +15,16 @@ public enum VOMSValidationErrorCode { acNotValidAtCurrentTime, // LSC signature checks - lscFileNotFound, emptyAcCertsExtension, lscDescriptionDoesntMatchAcCert, invalidAcCert, acCertFailsSignatureVerification, + lscFileNotFound, + emptyAcCertsExtension, + lscDescriptionDoesntMatchAcCert, + invalidAcCert, + acCertFailsSignatureVerification, // Local AA cert signature checks - aaCertNotFound, invalidAaCert, aaCertFailsSignatureVerification, + aaCertNotFound, + invalidAaCert, + aaCertFailsSignatureVerification, // Holder checks acHolderDoesntMatchCertChain, diff --git a/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorMessage.java b/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorMessage.java index 154efcf..64ed95d 100644 --- a/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorMessage.java +++ b/src/main/java/org/italiangrid/voms/error/VOMSValidationErrorMessage.java @@ -9,29 +9,27 @@ import java.util.ResourceBundle; /** - * A VOMS validation error message class (freely inspired by the CANL validation - * error message class). - * - * @author Andrea Ceccanti + * A VOMS validation error message class (freely inspired by the CANL validation error message + * class). * + * @author Andrea Ceccanti */ public class VOMSValidationErrorMessage { - static final String ERROR_BUNDLE = VOMSValidationErrorMessage.class - .getPackage().getName() + "." + "validationErrors"; + static final String ERROR_BUNDLE = + VOMSValidationErrorMessage.class.getPackage().getName() + "." + "validationErrors"; private VOMSValidationErrorCode errorCode; private String message; private Object[] parameters; - public static VOMSValidationErrorMessage newErrorMessage( - VOMSValidationErrorCode errorCode) { + public static VOMSValidationErrorMessage newErrorMessage(VOMSValidationErrorCode errorCode) { return new VOMSValidationErrorMessage(errorCode); } public static VOMSValidationErrorMessage newErrorMessage( - VOMSValidationErrorCode errorCode, Object... params) { + VOMSValidationErrorCode errorCode, Object... params) { return new VOMSValidationErrorMessage(errorCode, params); } @@ -39,11 +37,9 @@ public static VOMSValidationErrorMessage newErrorMessage( private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode) { this(errorCode, (Object[]) null); - } - private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode, - Object... params) { + private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode, Object... params) { this.errorCode = errorCode; this.parameters = params; @@ -59,7 +55,6 @@ private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode, } message = MessageFormat.format(template, parameters); - } public VOMSValidationErrorCode getErrorCode() { @@ -96,20 +91,14 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; VOMSValidationErrorMessage other = (VOMSValidationErrorMessage) obj; - if (errorCode != other.errorCode) - return false; + if (errorCode != other.errorCode) return false; if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; + if (other.message != null) return false; + } else if (!message.equals(other.message)) return false; return true; } } diff --git a/src/main/java/org/italiangrid/voms/error/package-info.java b/src/main/java/org/italiangrid/voms/error/package-info.java index 257cf9a..d4120de 100644 --- a/src/main/java/org/italiangrid/voms/error/package-info.java +++ b/src/main/java/org/italiangrid/voms/error/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides error code and message definitions for the VOMS API. - */ +/** This package provides error code and message definitions for the VOMS API. */ package org.italiangrid.voms.error; - diff --git a/src/main/java/org/italiangrid/voms/examples/ValidationExample.java b/src/main/java/org/italiangrid/voms/examples/ValidationExample.java index e13c384..44c8a26 100644 --- a/src/main/java/org/italiangrid/voms/examples/ValidationExample.java +++ b/src/main/java/org/italiangrid/voms/examples/ValidationExample.java @@ -4,6 +4,7 @@ package org.italiangrid.voms.examples; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -11,39 +12,30 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.VOMSValidators; import org.italiangrid.voms.ac.VOMSACValidator; -import eu.emi.security.authn.x509.impl.PEMCredential; - /** - * A simple example showing how VOMS attributes validation is done with the new - * API - * - * @author Andrea Ceccanti + * A simple example showing how VOMS attributes validation is done with the new API * + * @author Andrea Ceccanti */ public class ValidationExample { - public ValidationExample() throws KeyStoreException, CertificateException, - FileNotFoundException, IOException { + public ValidationExample() + throws KeyStoreException, CertificateException, FileNotFoundException, IOException { VOMSACValidator validator = VOMSValidators.newValidator(); - PEMCredential c = new PEMCredential(new FileInputStream("somefile"), - (char[]) null); + PEMCredential c = new PEMCredential(new FileInputStream("somefile"), (char[]) null); X509Certificate[] chain = c.getCertificateChain(); List attrs = validator.validate(chain); - for (VOMSAttribute a : attrs) - System.out.println(a); + for (VOMSAttribute a : attrs) System.out.println(a); validator.shutdown(); - } - } diff --git a/src/main/java/org/italiangrid/voms/examples/package-info.java b/src/main/java/org/italiangrid/voms/examples/package-info.java index 9b8bc83..bf3b1bb 100644 --- a/src/main/java/org/italiangrid/voms/examples/package-info.java +++ b/src/main/java/org/italiangrid/voms/examples/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides examples of the use of VOMS Java APIs. - */ +/** This package provides examples of the use of VOMS Java APIs. */ package org.italiangrid.voms.examples; - diff --git a/src/main/java/org/italiangrid/voms/package-info.java b/src/main/java/org/italiangrid/voms/package-info.java index faef4b2..b1dcf11 100644 --- a/src/main/java/org/italiangrid/voms/package-info.java +++ b/src/main/java/org/italiangrid/voms/package-info.java @@ -3,12 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 /** - * - * This package provides main VOMS Java APIs class and interfaces. - * For an introductory guide to the use of the API, check the API user manual - * here. - * - * @author Andrea Ceccanti + * This package provides main VOMS Java APIs class and interfaces. For an introductory guide to the + * use of the API, check the API user manual here. * + * @author Andrea Ceccanti */ -package org.italiangrid.voms; \ No newline at end of file +package org.italiangrid.voms; diff --git a/src/main/java/org/italiangrid/voms/request/ACDecodingStrategy.java b/src/main/java/org/italiangrid/voms/request/ACDecodingStrategy.java index eabc58f..cfcb3d2 100644 --- a/src/main/java/org/italiangrid/voms/request/ACDecodingStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/ACDecodingStrategy.java @@ -6,19 +6,16 @@ /** * Decodes an encoded VOMS attribute certificate - * - * @author andreaceccanti * + * @author andreaceccanti */ public interface ACDecodingStrategy { /** * Decodes an encoded VOMS attribute certificate - * - * @param ac - * the encoded VOMS attribute certificate + * + * @param ac the encoded VOMS attribute certificate * @return a byte array containing the VOMS attribute certificate */ public byte[] decode(String ac); - } diff --git a/src/main/java/org/italiangrid/voms/request/SSLSocketFactoryProvider.java b/src/main/java/org/italiangrid/voms/request/SSLSocketFactoryProvider.java index f4b3cc4..58820c9 100644 --- a/src/main/java/org/italiangrid/voms/request/SSLSocketFactoryProvider.java +++ b/src/main/java/org/italiangrid/voms/request/SSLSocketFactoryProvider.java @@ -4,31 +4,27 @@ package org.italiangrid.voms.request; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.helpers.ssl.DisabledNameMismatchCallback; +import eu.emi.security.authn.x509.helpers.ssl.EnforcingNameMismatchCallback; +import eu.emi.security.authn.x509.impl.SocketFactoryCreator2; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; - import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.util.CertificateValidatorBuilder; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.helpers.ssl.DisabledNameMismatchCallback; -import eu.emi.security.authn.x509.helpers.ssl.EnforcingNameMismatchCallback; -import eu.emi.security.authn.x509.impl.SocketFactoryCreator2; - /** * Provides an SSL socket factory configured using CAnL. * - * This class is responsible for creating an {@link SSLSocketFactory} that is configured with a + *

This class is responsible for creating an {@link SSLSocketFactory} that is configured with a * given X.509 credential and certificate validator. It supports optional hostname verification. - * */ public class SSLSocketFactoryProvider { @@ -49,8 +45,8 @@ public class SSLSocketFactoryProvider { * @param validator the certificate chain validator * @param skipHostnameChecks true to disable hostname verification, false otherwise */ - public SSLSocketFactoryProvider(X509Credential credential, X509CertChainValidatorExt validator, - boolean skipHostnameChecks) { + public SSLSocketFactoryProvider( + X509Credential credential, X509CertChainValidatorExt validator, boolean skipHostnameChecks) { this.credential = credential; this.validator = validator; @@ -97,14 +93,19 @@ public SSLSocketFactory getSSLSockectFactory() { KeyManager[] keyManagers = new KeyManager[] {credential.getKeyManager()}; - SocketFactoryCreator2 factory = new SocketFactoryCreator2(credential, validator, - skipHostnameChecks ? new DisabledNameMismatchCallback() - : new EnforcingNameMismatchCallback()); + SocketFactoryCreator2 factory = + new SocketFactoryCreator2( + credential, + validator, + skipHostnameChecks + ? new DisabledNameMismatchCallback() + : new EnforcingNameMismatchCallback()); X509TrustManager trustManager = factory.getSSLTrustManager(); TrustManager[] trustManagers = new TrustManager[] {trustManager}; - // Using new SecureRandom instead of SecureRandom.getInstance("SHA1PRNG") to avoid unnecessary + // Using new SecureRandom instead of SecureRandom.getInstance("SHA1PRNG") to + // avoid unnecessary // blocking SecureRandom secureRandom = new SecureRandom(); @@ -116,5 +117,4 @@ public SSLSocketFactory getSSLSockectFactory() { return context.getSocketFactory(); } - } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSACRequest.java b/src/main/java/org/italiangrid/voms/request/VOMSACRequest.java index 5f3df51..0b06a6e 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSACRequest.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSACRequest.java @@ -8,9 +8,8 @@ /** * A request for a VOMS Attribute certificate. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface VOMSACRequest { @@ -20,14 +19,13 @@ public interface VOMSACRequest { public int getLifetime(); /** - * @return the list of the requested FQANs specified in this - * {@link VOMSACRequest} object. + * @return the list of the requested FQANs specified in this {@link VOMSACRequest} object. */ public List getRequestedFQANs(); /** - * @return the list of targets (i.e., host where the requested ACs will be - * valid) for this {@link VOMSACRequest} object. + * @return the list of targets (i.e., host where the requested ACs will be valid) for this {@link + * VOMSACRequest} object. */ public List getTargets(); @@ -35,5 +33,4 @@ public interface VOMSACRequest { * @return the name of the VO this {@link VOMSACRequest} object is about. */ public String getVoName(); - -} \ No newline at end of file +} diff --git a/src/main/java/org/italiangrid/voms/request/VOMSACService.java b/src/main/java/org/italiangrid/voms/request/VOMSACService.java index aad46ab..88a00e8 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSACService.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSACService.java @@ -4,30 +4,24 @@ package org.italiangrid.voms.request; -import org.bouncycastle.asn1.x509.AttributeCertificate; - import eu.emi.security.authn.x509.X509Credential; +import org.bouncycastle.asn1.x509.AttributeCertificate; /** * The {@link VOMSACService} interface. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface VOMSACService { /** - * Returns an {@link AttributeCertificate} given a {@link VOMSACRequest} for - * VOMS attributes. - * - * @param credential - * the credential to be used when contacting the service - * @param request - * the request for VOMS attributes - * @return a possibly null {@link AttributeCertificate} containing (a subset - * of) the requested attributes. + * Returns an {@link AttributeCertificate} given a {@link VOMSACRequest} for VOMS attributes. + * + * @param credential the credential to be used when contacting the service + * @param request the request for VOMS attributes + * @return a possibly null {@link AttributeCertificate} containing (a subset of) the requested + * attributes. */ public AttributeCertificate getVOMSAttributeCertificate( - X509Credential credential, VOMSACRequest request); - + X509Credential credential, VOMSACRequest request); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSESLookupStrategy.java b/src/main/java/org/italiangrid/voms/request/VOMSESLookupStrategy.java index d05e1f8..935e71d 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSESLookupStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSESLookupStrategy.java @@ -8,23 +8,21 @@ import java.util.List; /** - * An strategy for building a list of {@link File} objects which will provide - * access to the local trusted VOMS server contact information. - * - * @author Andrea Ceccanti + * An strategy for building a list of {@link File} objects which will provide access to the local + * trusted VOMS server contact information. * + * @author Andrea Ceccanti */ public interface VOMSESLookupStrategy { /** - * @return a {@link List} of {@link File} objects that can be used to parse - * VOMSES information. + * @return a {@link List} of {@link File} objects that can be used to parse VOMSES information. */ public List lookupVomsesInfo(); /** - * @return a {@link List} of the paths that have been looked up to find - * {@link File} objects that can be used to parse VOMSES information. + * @return a {@link List} of the paths that have been looked up to find {@link File} objects that + * can be used to parse VOMSES information. */ public List searchedPaths(); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSESParser.java b/src/main/java/org/italiangrid/voms/request/VOMSESParser.java index 4b430fe..076c2f2 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSESParser.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSESParser.java @@ -7,43 +7,30 @@ import java.io.File; import java.io.Reader; import java.util.List; - import org.italiangrid.voms.VOMSError; - /** * A VOMSES file parser. - * + * * @author Andrea Ceccanti - * */ public interface VOMSESParser { /** - * Parses the VOMS contact information from the {@link Reader} passed as - * argument. - * - * @param vomsesReader - * the {@link Reader} object where voms contact information can be - * read from. - * @return a {@link VOMSServerInfo} object containing the VOMS server contact - * information. - * @throws VOMSError - * in case of parsing errors + * Parses the VOMS contact information from the {@link Reader} passed as argument. + * + * @param vomsesReader the {@link Reader} object where voms contact information can be read from. + * @return a {@link VOMSServerInfo} object containing the VOMS server contact information. + * @throws VOMSError in case of parsing errors */ public List parse(Reader vomsesReader); /** - * Parses the VOMS contact information from the {@link File} passed as - * argument. - * - * @param f - * the {@link File} object where voms contact information can be read - * from. - * @return a {@link VOMSServerInfo} object containing the VOMS server contact - * information. - * @throws VOMSError - * in case of parsing errors + * Parses the VOMS contact information from the {@link File} passed as argument. + * + * @param f the {@link File} object where voms contact information can be read from. + * @return a {@link VOMSServerInfo} object containing the VOMS server contact information. + * @throws VOMSError in case of parsing errors */ public List parse(File f); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSESParserFactory.java b/src/main/java/org/italiangrid/voms/request/VOMSESParserFactory.java index cb06621..963eda3 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSESParserFactory.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSESParserFactory.java @@ -8,9 +8,8 @@ /** * A factory class for {@link VOMSESParser}. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSESParserFactory { diff --git a/src/main/java/org/italiangrid/voms/request/VOMSErrorMessage.java b/src/main/java/org/italiangrid/voms/request/VOMSErrorMessage.java index 1602d95..dc32812 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSErrorMessage.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSErrorMessage.java @@ -5,13 +5,10 @@ package org.italiangrid.voms.request; /** - * - * This class is used to decode VOMS error messages contained in a VOMS - * response. - * + * This class is used to decode VOMS error messages contained in a VOMS response. + * * @author Andrea Ceccanti * @author Vincenzo Ciaschini - * */ public class VOMSErrorMessage extends VOMSMessage { @@ -23,6 +20,5 @@ public VOMSErrorMessage(int code, String message) { public String toString() { return "voms error " + code + ": " + message; - } } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSMessage.java b/src/main/java/org/italiangrid/voms/request/VOMSMessage.java index dde7e5b..4aa654e 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSMessage.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSMessage.java @@ -5,12 +5,9 @@ package org.italiangrid.voms.request; /** - * - * This class is used to decode VOMS error messages contained in a VOMS - * response. - * + * This class is used to decode VOMS error messages contained in a VOMS response. + * * @author Andrea CEccanti - * */ public class VOMSMessage { diff --git a/src/main/java/org/italiangrid/voms/request/VOMSProtocol.java b/src/main/java/org/italiangrid/voms/request/VOMSProtocol.java index 7020ac0..ec6e4e9 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSProtocol.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSProtocol.java @@ -7,27 +7,21 @@ import eu.emi.security.authn.x509.X509Credential; /** - * The request/response protocol for VOMS, with a methods accepting a rerquest - * and returning a response. - * + * The request/response protocol for VOMS, with a methods accepting a rerquest and returning a + * response. + * * @author valerioventuri - * */ public interface VOMSProtocol { /** * Makes a request, get the response. - * - * @param endpoint - * the voms server endpoint information - * @param credential - * the credentials. - * @param request - * the request. - * + * + * @param endpoint the voms server endpoint information + * @param credential the credentials. + * @param request the request. * @return a {@link VOMSResponse} containing the response. */ - public VOMSResponse doRequest(VOMSServerInfo endpoint, - X509Credential credential, VOMSACRequest request); - + public VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSProtocolError.java b/src/main/java/org/italiangrid/voms/request/VOMSProtocolError.java index 737fb78..fffe4e4 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSProtocolError.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSProtocolError.java @@ -4,47 +4,36 @@ package org.italiangrid.voms.request; -import org.italiangrid.voms.VOMSError; - import eu.emi.security.authn.x509.X509Credential; +import org.italiangrid.voms.VOMSError; /** - * Exception used when errors are raised during the interaction with a - * (possibly) remote VOMS server. - * - * @author andreaceccanti + * Exception used when errors are raised during the interaction with a (possibly) remote VOMS + * server. * + * @author andreaceccanti */ public class VOMSProtocolError extends VOMSError { - /** - * - */ + /** */ private static final long serialVersionUID = 1L; - /** - * The request that is related with this error - */ + /** The request that is related with this error */ private final VOMSACRequest request; - /** - * The credential related with this error - */ + /** The credential related with this error */ private final X509Credential credential; - /** - * The VOMS server endpoint information related with this error - */ + /** The VOMS server endpoint information related with this error */ private final VOMSServerInfo serverInfo; - public VOMSProtocolError(String message, VOMSServerInfo serv, - VOMSACRequest req, X509Credential cred, Throwable c) { + public VOMSProtocolError( + String message, VOMSServerInfo serv, VOMSACRequest req, X509Credential cred, Throwable c) { super(message, c); this.request = req; this.credential = cred; this.serverInfo = serv; - } /** @@ -70,5 +59,4 @@ public VOMSServerInfo getServerInfo() { return serverInfo; } - } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSProtocolListener.java b/src/main/java/org/italiangrid/voms/request/VOMSProtocolListener.java index 6c0afc5..fffa402 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSProtocolListener.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSProtocolListener.java @@ -6,34 +6,29 @@ /** * A listener that is notified of low-level VOMS protocol messages - * - * @author cecco * + * @author cecco */ public interface VOMSProtocolListener { /** - * Informs that a VOMS HTTP GET request is being issued for the URL passed as - * argument - * - * @param url - * the request url + * Informs that a VOMS HTTP GET request is being issued for the URL passed as argument + * + * @param url the request url */ public void notifyHTTPRequest(String url); /** * Informs that a VOMS legacy request is being issued - * - * @param xmlLegacyRequest - * a string representation of the XML legacy request + * + * @param xmlLegacyRequest a string representation of the XML legacy request */ public void notifyLegacyRequest(String xmlLegacyRequest); /** * Informs that a VOMSResponse was received from a remote VOMS server - * - * @param r - * the received {@link VOMSResponse} + * + * @param r the received {@link VOMSResponse} */ public void notifyReceivedResponse(VOMSResponse r); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSRequestListener.java b/src/main/java/org/italiangrid/voms/request/VOMSRequestListener.java index 823a321..6c61318 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSRequestListener.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSRequestListener.java @@ -6,72 +6,54 @@ /** * A listener that informs about events related with a request to a VOMS server. - * - * @author andreaceccanti * + * @author andreaceccanti */ public interface VOMSRequestListener { /** * Informs of the start of a request to a VOMS server - * - * @param request - * the request - * @param si - * the VOMS server endpoint information + * + * @param request the request + * @param si the VOMS server endpoint information */ public void notifyVOMSRequestStart(VOMSACRequest request, VOMSServerInfo si); /** * Informs of the succesfull conclusion of a request to a VOMS server - * - * @param request - * the request - * @param endpoint - * the VOMS server endpoint information + * + * @param request the request + * @param endpoint the VOMS server endpoint information */ - public void notifyVOMSRequestSuccess(VOMSACRequest request, - VOMSServerInfo endpoint); + public void notifyVOMSRequestSuccess(VOMSACRequest request, VOMSServerInfo endpoint); /** * Informs of a VOMS request failure - * - * @param request - * the request - * @param endpoint - * the VOMS server endpoint information - * @param error - * the error related with the failure + * + * @param request the request + * @param endpoint the VOMS server endpoint information + * @param error the error related with the failure */ - public void notifyVOMSRequestFailure(VOMSACRequest request, - VOMSServerInfo endpoint, Throwable error); + public void notifyVOMSRequestFailure( + VOMSACRequest request, VOMSServerInfo endpoint, Throwable error); /** - * Informs that errors were included in the VOMS response produced by a VOMS - * server - * - * @param request - * the request related to the received response - * @param si - * the VOMS server endpoint information - * @param errors - * the error messages included in the response + * Informs that errors were included in the VOMS response produced by a VOMS server + * + * @param request the request related to the received response + * @param si the VOMS server endpoint information + * @param errors the error messages included in the response */ - public void notifyErrorsInVOMSReponse(VOMSACRequest request, - VOMSServerInfo si, VOMSErrorMessage[] errors); + public void notifyErrorsInVOMSReponse( + VOMSACRequest request, VOMSServerInfo si, VOMSErrorMessage[] errors); /** - * Informs that warnings were included in the VOMS response produced by a VOMS - * server - * - * @param request - * the request related to the received response - * @param si - * the VOMS server endpoint information - * @param warnings - * the warning messages included in the response + * Informs that warnings were included in the VOMS response produced by a VOMS server + * + * @param request the request related to the received response + * @param si the VOMS server endpoint information + * @param warnings the warning messages included in the response */ - public void notifyWarningsInVOMSResponse(VOMSACRequest request, - VOMSServerInfo si, VOMSWarningMessage[] warnings); - + public void notifyWarningsInVOMSResponse( + VOMSACRequest request, VOMSServerInfo si, VOMSWarningMessage[] warnings); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSResponse.java b/src/main/java/org/italiangrid/voms/request/VOMSResponse.java index 6a8d82e..42e5474 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSResponse.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSResponse.java @@ -5,58 +5,51 @@ package org.italiangrid.voms.request; /** - * * @author Andrea Ceccanti - * */ public interface VOMSResponse { /** - * @return true if this {@link VOMSResponse} has errors, - * false otherwise + * @return true if this {@link VOMSResponse} has errors, false otherwise */ public boolean hasErrors(); /** - * @return true if this {@link VOMSResponse} has warnings, - * false otherwise + * @return true if this {@link VOMSResponse} has warnings, false + * otherwise */ public boolean hasWarnings(); /** - * * Extracts the AC from the VOMS response. - * + * * @return an array of bytes containing the AC. */ public byte[] getAC(); /** * Extracts the version from the VOMS response. - * + * * @return an integer containing the AC. */ public abstract int getVersion(); /** - * * Extracts the error messages from the VOMS response. - * + * * @return an array of {@link VOMSErrorMessage} objects. */ public VOMSErrorMessage[] errorMessages(); /** * Extracts the warning messags from the VOMS response. - * + * * @return an array of {@link VOMSWarningMessage} objects. */ public VOMSWarningMessage[] warningMessages(); /** - * * @return Returns the XML representation of the response as a string. */ public String getXMLAsString(); - -} \ No newline at end of file +} diff --git a/src/main/java/org/italiangrid/voms/request/VOMSResponseParsingStrategy.java b/src/main/java/org/italiangrid/voms/request/VOMSResponseParsingStrategy.java index e4ccd96..4fd3992 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSResponseParsingStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSResponseParsingStrategy.java @@ -8,20 +8,16 @@ /** * The strategy for parsing a response coming from a VOMS service. - * - * @author valerioventuri * + * @author valerioventuri */ public interface VOMSResponseParsingStrategy { /** - * Parse the response coming from a VOMS service and build a - * {@link VOMSResponse} object. - * - * @param inputStream - * the response from the VOMS service. + * Parse the response coming from a VOMS service and build a {@link VOMSResponse} object. + * + * @param inputStream the response from the VOMS service. * @return the response object representing the response from the service. */ public VOMSResponse parse(InputStream inputStream); - } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSServerInfo.java b/src/main/java/org/italiangrid/voms/request/VOMSServerInfo.java index d97efd3..6c88c51 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSServerInfo.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSServerInfo.java @@ -7,45 +7,41 @@ import java.net.URI; /** - * This interface represents a VOMS server contact information, typically - * provided in vomses files. - * + * This interface represents a VOMS server contact information, typically provided in vomses files. + * * @see VOMSESLookupStrategy * @see VOMSESParser - * * @author Andrea Ceccanti - * */ public interface VOMSServerInfo { /** * Returns the alias for this {@link VOMSServerInfo}. - * + * * @return the alias */ public String getAlias(); /** * Returns the VO name for this {@link VOMSServerInfo}. - * + * * @return the vo name */ public String getVoName(); /** * Returns the URL for this {@link VOMSServerInfo}. - * + * * @return the contact {@link URI} */ public URI getURL(); /** - * Returns the certificate subject as listed in the VOMSES configuration for - * this {@link VOMSServerInfo} - * - * @return a string containing the certificate subject, enconded following the - * DN openssl slash-separated syntax + * Returns the certificate subject as listed in the VOMSES configuration for this {@link + * VOMSServerInfo} + * + * @return a string containing the certificate subject, enconded following the DN openssl + * slash-separated syntax */ public String getVOMSServerDN(); - -} \ No newline at end of file +} diff --git a/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStore.java b/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStore.java index a053815..61401bc 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStore.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStore.java @@ -8,38 +8,32 @@ /** * A store containing the contact information for locally trusted VOMS servers. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface VOMSServerInfoStore { /** - * Returns a set of {@link VOMSServerInfo} object matching a vo name or alias - * passed as argument. - * - * @param voName - * a VO name - * @return a possibly empty set of {@link VOMSServerInfo} object matching the - * vo name or alias passed as argument + * Returns a set of {@link VOMSServerInfo} object matching a vo name or alias passed as argument. + * + * @param voName a VO name + * @return a possibly empty set of {@link VOMSServerInfo} object matching the vo name or alias + * passed as argument */ public Set getVOMSServerInfo(String voName); /** - * Returns a set of all {@link VOMSServerInfo} objects in this - * {@link VOMSServerInfoStore}. - * - * @return a possibly empty set of all {@link VOMSServerInfo} objects in this - * {@link VOMSServerInfoStore}. + * Returns a set of all {@link VOMSServerInfo} objects in this {@link VOMSServerInfoStore}. + * + * @return a possibly empty set of all {@link VOMSServerInfo} objects in this {@link + * VOMSServerInfoStore}. */ public Set getVOMSServerInfo(); /** * Adds a {@link VOMSServerInfo} to this {@link VOMSServerInfoStore}. - * - * @param info - * the {@link VOMSServerInfo} object to add. + * + * @param info the {@link VOMSServerInfo} object to add. */ public void addVOMSServerInfo(VOMSServerInfo info); - -} \ No newline at end of file +} diff --git a/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStoreListener.java b/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStoreListener.java index 04d5179..599cf2a 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStoreListener.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSServerInfoStoreListener.java @@ -7,39 +7,32 @@ import java.util.List; /** - * This interface is used to notify about events related to the load operations - * of VOMSES server endpoint information. - * - * @author andreaceccanti + * This interface is used to notify about events related to the load operations of VOMSES server + * endpoint information. * + * @author andreaceccanti */ public interface VOMSServerInfoStoreListener { /** * Informs that no valid VOMS information was found on the system. - * - * @param searchedPaths - * the list of searched paths + * + * @param searchedPaths the list of searched paths */ public void notifyNoValidVOMSESError(List searchedPaths); /** * Informs that VOMSES is being search at the path passed as argument - * - * @param vomsesPath - * the path where VOMSES information are being looked for + * + * @param vomsesPath the path where VOMSES information are being looked for */ public void notifyVOMSESlookup(String vomsesPath); /** * Informs that VOMSES information was succesfully loaded from a given path - * - * @param vomsesPath - * the path where VOMSES information was loaded from - * @param info - * the {@link VOMSServerInfo} voms endpoint information + * + * @param vomsesPath the path where VOMSES information was loaded from + * @param info the {@link VOMSServerInfo} voms endpoint information */ - public void notifyVOMSESInformationLoaded(String vomsesPath, - VOMSServerInfo info); - + public void notifyVOMSESInformationLoaded(String vomsesPath, VOMSServerInfo info); } diff --git a/src/main/java/org/italiangrid/voms/request/VOMSWarningMessage.java b/src/main/java/org/italiangrid/voms/request/VOMSWarningMessage.java index ceaa40f..6f45bf8 100644 --- a/src/main/java/org/italiangrid/voms/request/VOMSWarningMessage.java +++ b/src/main/java/org/italiangrid/voms/request/VOMSWarningMessage.java @@ -5,12 +5,9 @@ package org.italiangrid.voms.request; /** - * - * This class is used to decode VOMS error messages contained in a VOMS - * response. - * + * This class is used to decode VOMS error messages contained in a VOMS response. + * * @author Andrea CEccanti - * */ public class VOMSWarningMessage extends VOMSMessage { @@ -22,6 +19,5 @@ public VOMSWarningMessage(int code, String message) { public String toString() { return "voms warning " + code + ": " + message; - } } diff --git a/src/main/java/org/italiangrid/voms/request/impl/ACGenerationParams.java b/src/main/java/org/italiangrid/voms/request/impl/ACGenerationParams.java index 01ef475..deb23d4 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/ACGenerationParams.java +++ b/src/main/java/org/italiangrid/voms/request/impl/ACGenerationParams.java @@ -7,7 +7,6 @@ import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.util.Objects.isNull; - import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.FQANS; import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.GAS; import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.HOST; @@ -16,7 +15,6 @@ import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.PORT; import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.SERIAL; import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.VO; - import static org.italiangrid.voms.util.GaParser.parseGaString; import static org.italiangrid.voms.util.TimeUtils.parseDate; @@ -24,31 +22,37 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; - import org.italiangrid.voms.VOMSGenericAttribute; import org.italiangrid.voms.ac.impl.VOMSGenericAttributeImpl; /** - * This class represents the parameters required for generating an Attribute Certificate (AC). - * It encapsulates various attributes such as Virtual Organization (VO), Fully Qualified Attribute Names (FQANs), - * Generic Attributes (GAs), host details, validity periods, and a serial number. + * This class represents the parameters required for generating an Attribute Certificate (AC). It + * encapsulates various attributes such as Virtual Organization (VO), Fully Qualified Attribute + * Names (FQANs), Generic Attributes (GAs), host details, validity periods, and a serial number. */ public class ACGenerationParams { /** The Virtual Organization name. */ final String vo; + /** The list of Fully Qualified Attribute Names. */ final List fqans; + /** The list of Generic Attributes. */ final List gas; + /** The host associated with the AC request. */ final String host; + /** The port associated with the AC request. */ final int port; + /** The start time of the validity period. */ final Date notBefore; + /** The end time of the validity period. */ final Date notAfter; + /** The serial number of the attribute certificate. */ final BigInteger serialNo; @@ -58,6 +62,7 @@ public class ACGenerationParams { * @param builder the builder instance used to construct this object */ private ACGenerationParams(Builder builder) { + this.vo = builder.vo; this.fqans = builder.fqans; this.gas = builder.gas; @@ -68,50 +73,73 @@ private ACGenerationParams(Builder builder) { this.serialNo = builder.serialNo; } - /** @return the Virtual Organization name */ + /** + * @return the Virtual Organization name + */ public String getVo() { + return vo; } - /** @return the list of Fully Qualified Attribute Names */ + /** + * @return the list of Fully Qualified Attribute Names + */ public List getFqans() { + return fqans; } - /** @return the list of Generic Attributes */ + /** + * @return the list of Generic Attributes + */ public List getGas() { + return gas; } - /** @return the host associated with the AC request */ + /** + * @return the host associated with the AC request + */ public String getHost() { + return host; } - /** @return the port associated with the AC request */ + /** + * @return the port associated with the AC request + */ public int getPort() { + return port; } - /** @return the start time of the validity period */ + /** + * @return the start time of the validity period + */ public Date getNotBefore() { + return notBefore; } - /** @return the end time of the validity period */ + /** + * @return the end time of the validity period + */ public Date getNotAfter() { + return notAfter; } - /** @return the serial number of the attribute certificate */ + /** + * @return the serial number of the attribute certificate + */ public BigInteger getSerialNo() { + return serialNo; } - /** - * Builder class for constructing {@link ACGenerationParams} instances. - */ + /** Builder class for constructing {@link ACGenerationParams} instances. */ public static class Builder { + String vo = "test"; List fqans; List gas; @@ -123,38 +151,45 @@ public static class Builder { /** Default constructor initializing lists. */ public Builder() { + fqans = new ArrayList<>(); gas = new ArrayList<>(); } /** * Sets the VO. + * * @param vo the Virtual Organization name * @return the Builder instance */ public Builder vo(String vo) { + this.vo = vo; return this; } /** * Adds a Fully Qualified Attribute Name. + * * @param fqan the FQAN to add * @return the Builder instance */ public Builder fqan(String fqan) { + fqans.add(fqan); return this; } /** * Adds a Generic Attribute. + * * @param name the attribute name * @param value the attribute value * @param context the attribute context * @return the Builder instance */ public Builder ga(String name, String value, String context) { + VOMSGenericAttributeImpl ga = new VOMSGenericAttributeImpl(); ga.setName(name); ga.setValue(value); @@ -165,65 +200,80 @@ public Builder ga(String name, String value, String context) { /** * Sets the host. + * * @param host the host * @return the Builder instance */ public Builder host(String host) { + this.host = host; return this; } /** * Sets the port. + * * @param port the port number * @return the Builder instance */ public Builder port(int port) { + this.port = port; return this; } /** * Sets the not-before validity time. + * * @param notBefore the start of the validity period * @return the Builder instance */ public Builder notBefore(Date notBefore) { + this.notBefore = notBefore; return this; } /** * Sets the not-after validity time. + * * @param notAfter the end of the validity period * @return the Builder instance */ public Builder notAfter(Date notAfter) { + this.notAfter = notAfter; return this; } /** * Sets the serial number. + * * @param serialNo the serial number * @return the Builder instance */ public Builder serialNo(long serialNo) { + this.serialNo = BigInteger.valueOf(serialNo); return this; } /** * Builds the {@link ACGenerationParams} instance. + * * @return a new ACGenerationParams object */ public ACGenerationParams build() { + return new ACGenerationParams(this); } } - /** @return a new Builder instance */ + /** + * @return a new Builder instance + */ public static Builder builder() { + return new Builder(); } @@ -233,6 +283,7 @@ public static Builder builder() { * @return a configured ACGenerationParams instance. */ public static ACGenerationParams fromSystemProperties() { + ACGenerationParams.Builder builder = ACGenerationParams.builder(); builder.vo(VO.getSystemPropertyValue()); String fqansString = FQANS.getSystemPropertyValue(); @@ -265,4 +316,3 @@ public static ACGenerationParams fromSystemProperties() { return builder.build(); } } - diff --git a/src/main/java/org/italiangrid/voms/request/impl/AbstractVOMSProtocol.java b/src/main/java/org/italiangrid/voms/request/impl/AbstractVOMSProtocol.java index 7eeb9c5..1e65751 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/AbstractVOMSProtocol.java +++ b/src/main/java/org/italiangrid/voms/request/impl/AbstractVOMSProtocol.java @@ -4,65 +4,45 @@ package org.italiangrid.voms.request.impl; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.X509Credential; import javax.net.ssl.SSLSocketFactory; - import org.italiangrid.voms.request.SSLSocketFactoryProvider; import org.italiangrid.voms.request.VOMSProtocol; import org.italiangrid.voms.request.VOMSProtocolListener; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.X509Credential; - /** * Abstract base class providing a skeletal implementation of the VOMS client-server protocol. This * class handles SSL authentication, connection timeouts, and hostname verification. */ public abstract class AbstractVOMSProtocol implements VOMSProtocol { - /** - * Enabled TLS protocols for VOMS legacy connections. - */ + /** Enabled TLS protocols for VOMS legacy connections. */ public static final String[] VOMS_LEGACY_ENABLED_PROTOCOLS = {"TLSv1", "TLSv1.1", "TLSv1.2"}; - /** - * The default value for the socket connection timeout (in milliseconds). - */ + /** The default value for the socket connection timeout (in milliseconds). */ public static final int DEFAULT_CONNECT_TIMEOUT = 5000; - /** - * The default value for the socket read timeout (in milliseconds). - */ + /** The default value for the socket read timeout (in milliseconds). */ public static final int DEFAULT_READ_TIMEOUT = 5000; - /** - * The default policy for skipping hostname verification. - */ + /** The default policy for skipping hostname verification. */ public static final boolean DEFAULT_SKIP_HOSTNAME_CHECKS = false; - /** - * Listener for protocol events. - */ + /** Listener for protocol events. */ protected VOMSProtocolListener listener = NullListener.INSTANCE; - /** - * Validator used for SSL authentication. - */ + /** Validator used for SSL authentication. */ protected X509CertChainValidatorExt validator; - /** - * TCP connection timeout in milliseconds. - */ + /** TCP connection timeout in milliseconds. */ protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT; - /** - * Socket read timeout in milliseconds. - */ + /** Socket read timeout in milliseconds. */ protected int readTimeout = DEFAULT_READ_TIMEOUT; - /** - * Flag indicating whether hostname verification is disabled. - */ + /** Flag indicating whether hostname verification is disabled. */ protected boolean skipHostnameChecks = DEFAULT_SKIP_HOSTNAME_CHECKS; /** @@ -83,8 +63,11 @@ public AbstractVOMSProtocol(X509CertChainValidatorExt validator) { * @param connectTimeout the socket connection timeout in milliseconds * @param readTimeout the socket read timeout in milliseconds */ - public AbstractVOMSProtocol(X509CertChainValidatorExt validator, VOMSProtocolListener listener, - int connectTimeout, int readTimeout) { + public AbstractVOMSProtocol( + X509CertChainValidatorExt validator, + VOMSProtocolListener listener, + int connectTimeout, + int readTimeout) { this.validator = validator; this.connectTimeout = connectTimeout; @@ -159,7 +142,7 @@ public boolean isSkipHostnameChecks() { * Configures whether SSL hostname verification should be skipped. * * @param skipHostnameChecks {@code true} to disable hostname verification, {@code false} to - * enable it + * enable it */ public void setSkipHostnameChecks(boolean skipHostnameChecks) { diff --git a/src/main/java/org/italiangrid/voms/request/impl/BaseVOMSESLookupStrategy.java b/src/main/java/org/italiangrid/voms/request/impl/BaseVOMSESLookupStrategy.java index 507310c..7f49626 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/BaseVOMSESLookupStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/impl/BaseVOMSESLookupStrategy.java @@ -7,15 +7,12 @@ import java.io.File; import java.util.ArrayList; import java.util.List; - import org.italiangrid.voms.request.VOMSESLookupStrategy; /** - * A base VOMSES lookup strategy which just run a existence check on a given - * list of paths. - * + * A base VOMSES lookup strategy which just run a existence check on a given list of paths. + * * @author Andrea Ceccanti - * */ public class BaseVOMSESLookupStrategy implements VOMSESLookupStrategy { @@ -40,8 +37,7 @@ public List lookupVomsesInfo() { for (String p : checkedPaths) { File f = new File(p); - if (f.exists()) - vomsesPaths.add(f); + if (f.exists()) vomsesPaths.add(f); } return vomsesPaths; diff --git a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACRequest.java b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACRequest.java index 03502a8..4eb99bc 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACRequest.java +++ b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACRequest.java @@ -7,14 +7,12 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; - import org.italiangrid.voms.request.VOMSACRequest; /** * The default implementation for a {@link VOMSACRequest}. - * + * * @author Valerio Venturi - * */ public class DefaultVOMSACRequest implements VOMSACRequest { @@ -79,23 +77,19 @@ public Builder lifetime(int l) { public Builder fqans(List fqans) { - if (fqans != null) - this.requestedFQANs = fqans; + if (fqans != null) this.requestedFQANs = fqans; return this; } public Builder targets(List targets) { - if (targets != null) - this.targets = targets; + if (targets != null) this.targets = targets; return this; } public DefaultVOMSACRequest build() { return new DefaultVOMSACRequest(this); - } } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACService.java b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACService.java index 5056cda..f28e23f 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACService.java +++ b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACService.java @@ -4,10 +4,11 @@ package org.italiangrid.voms.request.impl; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.X509Credential; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSError; @@ -24,57 +25,38 @@ import org.italiangrid.voms.request.VOMSServerInfoStoreListener; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.X509Credential; - /** * The default implementation of the {@link VOMSACService}. - * - * + * * @author Valerio Venturi * @author Andrea Ceccanti - * */ public class DefaultVOMSACService implements VOMSACService { - /** - * The listener that will be informed about request events - */ + /** The listener that will be informed about request events */ protected final VOMSRequestListener requestListener; - /** - * The listener that will be informed about low-level protocol details - */ + /** The listener that will be informed about low-level protocol details */ protected final VOMSProtocolListener protocolListener; - /** - * The validator used for the SSL handshake - */ + /** The validator used for the SSL handshake */ protected final X509CertChainValidatorExt validator; - /** - * The store used to keep VOMS server contact information. - */ + /** The store used to keep VOMS server contact information. */ protected final VOMSServerInfoStore serverInfoStore; - /** - * The http protocol implementation - */ + /** The http protocol implementation */ protected final VOMSProtocol httpProtocol; - /** - * The voms legacy protocol implementation - */ + /** The voms legacy protocol implementation */ protected final VOMSProtocol legacyProtocol; - /** - * Whether VOMS legacy protocol should be used as a fallback when REST protocol fails - */ + /** Whether VOMS legacy protocol should be used as a fallback when REST protocol fails */ protected final boolean legacyProtocolEnabled; /** * Constructor which builds a {@link DefaultVOMSACService} from a {@link Builder} - * + * * @param builder the builder object that provides the settings for this {@link VOMSACService} */ protected DefaultVOMSACService(Builder builder) { @@ -90,7 +72,7 @@ protected DefaultVOMSACService(Builder builder) { /** * Extracts an AC from a VOMS response - * + * * @param request the request * @param response the received response * @return a possibly null {@link AttributeCertificate} object @@ -99,8 +81,7 @@ protected AttributeCertificate getACFromResponse(VOMSACRequest request, VOMSResp byte[] acBytes = response.getAC(); - if (acBytes == null) - return null; + if (acBytes == null) return null; ASN1InputStream asn1InputStream = new ASN1InputStream(acBytes); @@ -115,15 +96,15 @@ protected AttributeCertificate getACFromResponse(VOMSACRequest request, VOMSResp } catch (Throwable e) { - requestListener.notifyVOMSRequestFailure(request, null, - new VOMSError("Error unmarshalling VOMS AC. Cause: " + e.getMessage(), e)); + requestListener.notifyVOMSRequestFailure( + request, null, new VOMSError("Error unmarshalling VOMS AC. Cause: " + e.getMessage(), e)); return null; } } - private VOMSResponse doRequest(VOMSProtocol protocol, VOMSServerInfo endpoint, - X509Credential cred, VOMSACRequest req) { + private VOMSResponse doRequest( + VOMSProtocol protocol, VOMSServerInfo endpoint, X509Credential cred, VOMSACRequest req) { VOMSResponse response = null; @@ -136,46 +117,47 @@ private VOMSResponse doRequest(VOMSProtocol protocol, VOMSServerInfo endpoint, } return response; - } /** * Handles errors included in the VOMS response - * + * * @param request the request * @param si the VOMS server endpoint information * @param response the received {@link VOMSResponse} */ - protected void handleErrorsInResponse(VOMSACRequest request, VOMSServerInfo si, - VOMSResponse response) { + protected void handleErrorsInResponse( + VOMSACRequest request, VOMSServerInfo si, VOMSResponse response) { if (response.hasErrors()) requestListener.notifyErrorsInVOMSReponse(request, si, response.errorMessages()); - } /** * Handles warnings included in the VOMS response - * + * * @param request the request * @param si the VOMS server endpoint information * @param response the received {@link VOMSResponse} */ - protected void handleWarningsInResponse(VOMSACRequest request, VOMSServerInfo si, - VOMSResponse response) { + protected void handleWarningsInResponse( + VOMSACRequest request, VOMSServerInfo si, VOMSResponse response) { if (response.hasWarnings()) requestListener.notifyWarningsInVOMSResponse(request, si, response.warningMessages()); } - public AttributeCertificate getVOMSAttributeCertificate(X509Credential credential, - VOMSACRequest request) { + public AttributeCertificate getVOMSAttributeCertificate( + X509Credential credential, VOMSACRequest request) { List vomsServerInfos = getVOMSServerInfos(request); if (vomsServerInfos.isEmpty()) - throw new VOMSError("VOMS server for VO " + request.getVoName() + " " - + "is not known! Check your vomses configuration."); + throw new VOMSError( + "VOMS server for VO " + + request.getVoName() + + " " + + "is not known! Check your vomses configuration."); VOMSResponse response = null; @@ -196,8 +178,8 @@ public AttributeCertificate getVOMSAttributeCertificate(X509Credential credentia if (response == null) { if (legacyProtocolEnabled) { - requestListener.notifyVOMSRequestFailure(request, vomsServerInfo, - new VOMSError("REST and legacy VOMS endpoints failed.")); + requestListener.notifyVOMSRequestFailure( + request, vomsServerInfo, new VOMSError("REST and legacy VOMS endpoints failed.")); } continue; @@ -219,23 +201,21 @@ public AttributeCertificate getVOMSAttributeCertificate(X509Credential credentia if (!response.hasErrors() && vomsAC != null) { return vomsAC; } - } // if we reach this point we had failures in contacting // all known voms server for the VO requestListener.notifyVOMSRequestFailure(request, null, null); return null; - } /** * Get VOMS server endpoint information that matches with the {@link VOMSACRequest} passed as * argument. - * - * This method returns a random shuffle of the {@link VOMSServerInfo} objects that match the input - * request. - * + * + *

This method returns a random shuffle of the {@link VOMSServerInfo} objects that match the + * input request. + * * @param request the request * @return a possibly empty {@link List} of {@link VOMSServerInfo} objects */ @@ -253,53 +233,37 @@ protected List getVOMSServerInfos(VOMSACRequest request) { /** * Creates a {@link DefaultVOMSACService} object. The {@link DefaultVOMSACService} parameters can * be set with the appropriate methods. Example: - * + * *

-   * 
-   * 
-   * 
+   *
    * {
    *   @code
-   *   VOMSACService acService =
-   *       new DefaultVOMSACService.Builder(certChainValidator).requestListener(requestListener)
-   *         .serverInfoStoreListener(serverInfoStoreListener)
-   *         .protocolListener(protocolListener)
-   *         .build();
+   *   VOMSACService acService = new DefaultVOMSACService.Builder(
+   *     certChainValidator).requestListener(requestListener)
+   *     .serverInfoStoreListener(serverInfoStoreListener)
+   *     .protocolListener(protocolListener)
+   *     .build();
    * }
    * 
- * - * */ public static class Builder { - /** - * The listener that will be informed about request events - */ + /** The listener that will be informed about request events */ private VOMSRequestListener requestListener = NullListener.INSTANCE; - /** - * The listener that will be informed about low-level protocol details - */ + /** The listener that will be informed about low-level protocol details */ private VOMSProtocolListener protocolListener = NullListener.INSTANCE; - /** - * The listener that will be informed about server info store events - */ + /** The listener that will be informed about server info store events */ private VOMSServerInfoStoreListener storeListener = NullListener.INSTANCE; - /** - * The validator used for the SSL handshake - */ + /** The validator used for the SSL handshake */ private X509CertChainValidatorExt validator; - /** - * The store used to keep VOMS server contact information. - */ + /** The store used to keep VOMS server contact information. */ private VOMSServerInfoStore serverInfoStore; - /** - * The provided strategy to lookup vomses information. - */ + /** The provided strategy to lookup vomses information. */ private VOMSESLookupStrategy vomsesLookupStrategy; /** @@ -308,41 +272,29 @@ public static class Builder { */ private List vomsesLocations; - /** - * The connect timeout value - */ + /** The connect timeout value */ private int connectTimeout = AbstractVOMSProtocol.DEFAULT_CONNECT_TIMEOUT; - /** - * The read timeout used - */ + /** The read timeout used */ private int readTimeout = AbstractVOMSProtocol.DEFAULT_READ_TIMEOUT; - /** - * Whether the client should skip hostname checking - */ + /** Whether the client should skip hostname checking */ private boolean skipHostnameChecks = true; - /** - * The http protocol implementation - */ + /** The http protocol implementation */ protected VOMSProtocol httpProtocol; - /** - * The voms legacy protocol implementation - */ + /** The voms legacy protocol implementation */ protected VOMSProtocol legacyProtocol; - /** - * Whether the client should attempt legacy protocol requests - */ + /** Whether the client should attempt legacy protocol requests */ private boolean legacyProtocolEnabled = false; /** * Creates a Builder for a {@link DefaultVOMSACService}. - * + * * @param certChainValidator the validator to use to setup the SSL connection and validate the - * certificates + * certificates */ public Builder(X509CertChainValidatorExt certChainValidator) { @@ -354,7 +306,7 @@ public Builder(X509CertChainValidatorExt certChainValidator) { /** * Sets the request listener for the {@link DefaultVOMSACService} that this builder is creating - * + * * @param l the request listener that will receive notifications about request events * @return this {@link Builder} instance */ @@ -367,7 +319,7 @@ public Builder requestListener(VOMSRequestListener l) { /** * Sets the {@link VOMSServerInfoStoreListener} for the {@link DefaultVOMSACService} that this * builder is creating - * + * * @param sl the store listener that will receive notifications about store events * @return this {@link Builder} instance */ @@ -380,7 +332,7 @@ public Builder serverInfoStoreListener(VOMSServerInfoStoreListener sl) { /** * Sets the {@link VOMSServerInfoStore} for the {@link DefaultVOMSACService} that this builder * is creating - * + * * @param sis a {@link VOMSServerInfoStore} object * @return this {@link Builder} instance */ @@ -393,9 +345,9 @@ public Builder serverInfoStore(VOMSServerInfoStore sis) { /** * Sets the {@link VOMSProtocolListener} for the {@link DefaultVOMSACService} that this builder * is creating - * + * * @param pl the {@link VOMSProtocolListener} that will receive notifications about protocol - * events + * events * @return this {@link Builder} instance */ public Builder protocolListener(VOMSProtocolListener pl) { @@ -407,7 +359,7 @@ public Builder protocolListener(VOMSProtocolListener pl) { /** * Sets the connect timeout (in millisecods) for the {@link DefaultVOMSACService} that this * builder is creating - * + * * @param timeout the timeout value in milliseconds * @return this {@link Builder} instance */ @@ -420,7 +372,7 @@ public Builder connectTimeout(int timeout) { /** * Sets the read timeout (in milliseconds) for the {@link DefaultVOMSACService} that this * builder is creating - * + * * @param timeout the timeout value in milliseconds * @return this {@link Builder} instance */ @@ -433,9 +385,8 @@ public Builder readTimeout(int timeout) { /** * Sets a flag to skip VOMS hostname checking. Allows for creative VOMS server side certificate * configuration. - * + * * @param s true to skip the checks, false otherwise - * * @return this {@link Builder} instance */ public Builder skipHostnameChecks(boolean s) { @@ -447,7 +398,7 @@ public Builder skipHostnameChecks(boolean s) { /** * Sets the vomses lookup strategy for the {@link DefaultVOMSACService} that this builder is * creating - * + * * @param strategy the {@link VOMSESLookupStrategy} object * @return this {@link Builder} instance */ @@ -460,7 +411,7 @@ public Builder vomsesLookupStrategy(VOMSESLookupStrategy strategy) { /** * Sets a list of locations that will be used to build a {@link VOMSESLookupStrategy} for the * {@link DefaultVOMSACService} that this builder is creating - * + * * @param vomsesLocations a list of paths where vomses information will be looked for * @return this {@link Builder} instance */ @@ -472,7 +423,7 @@ public Builder vomsesLocations(List vomsesLocations) { /** * Sets the http protocol implementation - * + * * @param httpProtocol the http protocol implementatino * @return this {@link Builder} instance */ @@ -484,9 +435,8 @@ public Builder httpProtocol(VOMSProtocol httpProtocol) { /** * Sets the legacy protocol implementation - * + * * @param legacyProtocol the legacy protocol implementation - * * @return the {@link Builder} */ public Builder legacyProtocol(VOMSProtocol legacyProtocol) { @@ -497,9 +447,8 @@ public Builder legacyProtocol(VOMSProtocol legacyProtocol) { /** * Enables/disables the fallback the VOMS legacy protocol. - * + * * @param lpe true to enable the legacy protocol, false otherwise - * * @return this {@link Builder} instance */ public Builder legacyProtocolEnabled(boolean lpe) { @@ -508,24 +457,20 @@ public Builder legacyProtocolEnabled(boolean lpe) { return this; } - /** - * Builds the server info store - */ + /** Builds the server info store */ protected void buildServerInfoStore() { - if (serverInfoStore != null) - return; + if (serverInfoStore != null) return; serverInfoStore = - new DefaultVOMSServerInfoStore.Builder().lookupStrategy(vomsesLookupStrategy) - .storeListener(storeListener) - .vomsesPaths(vomsesLocations) - .build(); + new DefaultVOMSServerInfoStore.Builder() + .lookupStrategy(vomsesLookupStrategy) + .storeListener(storeListener) + .vomsesPaths(vomsesLocations) + .build(); } - /** - * Builds default protocols if needed - */ + /** Builds default protocols if needed */ protected void buildProtocols() { if (httpProtocol == null) { @@ -535,7 +480,6 @@ protected void buildProtocols() { p.setSkipHostnameChecks(skipHostnameChecks); httpProtocol = p; - } if (legacyProtocol == null) { @@ -546,13 +490,12 @@ protected void buildProtocols() { p.setSkipHostnameChecks(skipHostnameChecks); legacyProtocol = p; - } } /** * Builds the {@link DefaultVOMSACService} - * + * * @return a {@link DefaultVOMSACService} configured as required by this builder */ public DefaultVOMSACService build() { diff --git a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSESLookupStrategy.java b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSESLookupStrategy.java index b84786b..463e8d7 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSESLookupStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSESLookupStrategy.java @@ -8,16 +8,16 @@ /** * Default VOMSES information lookup strategy. - * - * This implementation looks for vomses information in the following paths: + * + *

This implementation looks for vomses information in the following paths: + * *

    - *
  • /etc/vomses - *
  • ${user.home}/.glite/vomses - *
  • ${user.home}/.voms/vomses + *
  • /etc/vomses + *
  • ${user.home}/.glite/vomses + *
  • ${user.home}/.voms/vomses *
- * + * * @author Andrea Ceccanti - * */ public class DefaultVOMSESLookupStrategy extends BaseVOMSESLookupStrategy { @@ -25,7 +25,10 @@ public class DefaultVOMSESLookupStrategy extends BaseVOMSESLookupStrategy { public DefaultVOMSESLookupStrategy() { - super(Arrays.asList(DEFAULT_VOMSES_DIR, System.getProperty("user.home") - + "/.glite/vomses", System.getProperty("user.home") + "/.voms/vomses")); + super( + Arrays.asList( + DEFAULT_VOMSES_DIR, + System.getProperty("user.home") + "/.glite/vomses", + System.getProperty("user.home") + "/.voms/vomses")); } } diff --git a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfo.java b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfo.java index 55a5ef6..f984ea6 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfo.java +++ b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfo.java @@ -5,30 +5,28 @@ package org.italiangrid.voms.request.impl; import java.net.URI; - import org.italiangrid.voms.request.VOMSServerInfo; /** - * The default implementation of the {@link VOMSServerInfo} endpoint - * information. - * - * @author andreaceccanti + * The default implementation of the {@link VOMSServerInfo} endpoint information. * + * @author andreaceccanti */ public class DefaultVOMSServerInfo implements VOMSServerInfo { - /** The VOMS server alias **/ + /** The VOMS server alias * */ String alias; - /** The VO name **/ + + /** The VO name * */ String voName; - /** The VOMS server URI **/ + + /** The VOMS server URI * */ URI URL; - /** The VOMS server certificate subject **/ - String vomsServerDN; - public DefaultVOMSServerInfo() { + /** The VOMS server certificate subject * */ + String vomsServerDN; - } + public DefaultVOMSServerInfo() {} public String getAlias() { @@ -78,48 +76,43 @@ public int hashCode() { result = prime * result + ((URL == null) ? 0 : URL.hashCode()); result = prime * result + ((alias == null) ? 0 : alias.hashCode()); result = prime * result + ((voName == null) ? 0 : voName.hashCode()); - result = prime * result - + ((vomsServerDN == null) ? 0 : vomsServerDN.hashCode()); + result = prime * result + ((vomsServerDN == null) ? 0 : vomsServerDN.hashCode()); return result; } @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; DefaultVOMSServerInfo other = (DefaultVOMSServerInfo) obj; if (URL == null) { - if (other.URL != null) - return false; - } else if (!URL.equals(other.URL)) - return false; + if (other.URL != null) return false; + } else if (!URL.equals(other.URL)) return false; if (alias == null) { - if (other.alias != null) - return false; - } else if (!alias.equals(other.alias)) - return false; + if (other.alias != null) return false; + } else if (!alias.equals(other.alias)) return false; if (voName == null) { - if (other.voName != null) - return false; - } else if (!voName.equals(other.voName)) - return false; + if (other.voName != null) return false; + } else if (!voName.equals(other.voName)) return false; if (vomsServerDN == null) { - if (other.vomsServerDN != null) - return false; - } else if (!vomsServerDN.equals(other.vomsServerDN)) - return false; + if (other.vomsServerDN != null) return false; + } else if (!vomsServerDN.equals(other.vomsServerDN)) return false; return true; } @Override public String toString() { - return "VOMSServerInfo [alias=" + alias + ", voName=" + voName + ", URL=" - + URL + ", vomsServerDN=" + vomsServerDN + "]"; + return "VOMSServerInfo [alias=" + + alias + + ", voName=" + + voName + + ", URL=" + + URL + + ", vomsServerDN=" + + vomsServerDN + + "]"; } } diff --git a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfoStore.java b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfoStore.java index aab9638..b85b30a 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfoStore.java +++ b/src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSServerInfoStore.java @@ -11,7 +11,6 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; - import org.italiangrid.voms.request.VOMSESLookupStrategy; import org.italiangrid.voms.request.VOMSESParser; import org.italiangrid.voms.request.VOMSESParserFactory; @@ -21,21 +20,19 @@ import org.italiangrid.voms.util.NullListener; /** - * - * A {@link DefaultVOMSServerInfoStore} organizes voms servers found in vomses - * configuration files in map keyed by vo alias. This way is easy to know which - * servers acts as replicas for the same vos. - * + * A {@link DefaultVOMSServerInfoStore} organizes voms servers found in vomses configuration files + * in map keyed by vo alias. This way is easy to know which servers acts as replicas for the same + * vos. + * * @author Andrea Ceccanti - * - * */ public class DefaultVOMSServerInfoStore implements VOMSServerInfoStore { private VOMSESLookupStrategy lookupStrategy; private VOMSServerInfoStoreListener listener; - protected Map> serverInfoStore = new TreeMap>(); + protected Map> serverInfoStore = + new TreeMap>(); private VOMSESParser vomsesParser; private DefaultVOMSServerInfoStore(Builder b) { @@ -44,7 +41,6 @@ private DefaultVOMSServerInfoStore(Builder b) { this.listener = b.listener; this.vomsesParser = b.vomsesParser; initializeStore(); - } public void addVOMSServerInfo(VOMSServerInfo info) { @@ -72,8 +68,7 @@ public Set getVOMSServerInfo() { Set allEntries = new HashSet(); - for (Map.Entry> entry : serverInfoStore - .entrySet()) + for (Map.Entry> entry : serverInfoStore.entrySet()) allEntries.addAll(entry.getValue()); return allEntries; @@ -82,11 +77,11 @@ public Set getVOMSServerInfo() { public Set getVOMSServerInfo(String voName) { Set result = serverInfoStore.get(voName); - + if (result == null) { - result = Collections.emptySet(); + result = Collections.emptySet(); } - + return result; } @@ -94,8 +89,7 @@ private void initializeStore() { List vomsesPaths = lookupStrategy.lookupVomsesInfo(); - if (vomsesPaths.isEmpty()) - listener.notifyNoValidVOMSESError(lookupStrategy.searchedPaths()); + if (vomsesPaths.isEmpty()) listener.notifyNoValidVOMSESError(lookupStrategy.searchedPaths()); for (File f : vomsesPaths) { @@ -105,57 +99,45 @@ private void initializeStore() { for (VOMSServerInfo si : vomsServerInfo) { addVOMSServerInfo(si, f.getAbsolutePath()); } - } } /** - * Creates a {@link DefaultVOMSServerInfoStore}. The - * {@link DefaultVOMSServerInfoStore} parameters can be set with the - * appropriate methods. Example: - * + * Creates a {@link DefaultVOMSServerInfoStore}. The {@link DefaultVOMSServerInfoStore} parameters + * can be set with the appropriate methods. Example: + * *
-   * 
+   *
    * {
    *   @code
    *   VOMSServerInfoStore serverInfoStore = new DefaultVOMSServerInfoStore.Builder()
-   *     .storeListener(storeListener).vomsesPaths(vomsesLocations).build();
+   *     .storeListener(storeListener)
+   *     .vomsesPaths(vomsesLocations)
+   *     .build();
    * };
    * 
- * */ public static class Builder { - /** - * A list of paths where vomses information will be looked for - */ + /** A list of paths where vomses information will be looked for */ private List vomsesPaths; - /** - * The {@link VOMSESLookupStrategy} that will be used to lookup vomses - * information - */ + + /** The {@link VOMSESLookupStrategy} that will be used to lookup vomses information */ private VOMSESLookupStrategy lookupStrategy; - /** - * The listener that will be notified of interesting store events - */ + + /** The listener that will be notified of interesting store events */ private VOMSServerInfoStoreListener listener = NullListener.INSTANCE; - /** - * The parser implementation used to parse VOMSES files - */ + /** The parser implementation used to parse VOMSES files */ private VOMSESParser vomsesParser = VOMSESParserFactory.newVOMSESParser(); - public Builder() { - - } + public Builder() {} /** - * Sets the {@link VOMSESLookupStrategy} that will be used to lookup vomses - * information for the {@link DefaultVOMSServerInfoStore} that this builder - * is creating - * - * @param strategy - * The strategy that will be used to lookup vomses information + * Sets the {@link VOMSESLookupStrategy} that will be used to lookup vomses information for the + * {@link DefaultVOMSServerInfoStore} that this builder is creating + * + * @param strategy The strategy that will be used to lookup vomses information * @return this {@link Builder} instance */ public Builder lookupStrategy(VOMSESLookupStrategy strategy) { @@ -165,12 +147,10 @@ public Builder lookupStrategy(VOMSESLookupStrategy strategy) { } /** - * Sets the {@link VOMSServerInfoStoreListener} that will receive - * store-related notifications for the {@link DefaultVOMSServerInfoStore} - * that this builder is creating - * - * @param l - * the listener + * Sets the {@link VOMSServerInfoStoreListener} that will receive store-related notifications + * for the {@link DefaultVOMSServerInfoStore} that this builder is creating + * + * @param l the listener * @return this {@link Builder} instance */ public Builder storeListener(VOMSServerInfoStoreListener l) { @@ -180,11 +160,9 @@ public Builder storeListener(VOMSServerInfoStoreListener l) { } /** - * Sets the {@link VOMSESParser} implementation that will be used to parse - * vomses files - * - * @param p - * the parser + * Sets the {@link VOMSESParser} implementation that will be used to parse vomses files + * + * @param p the parser * @return this {@link Builder} instance */ public Builder vomsesParser(VOMSESParser p) { @@ -194,11 +172,10 @@ public Builder vomsesParser(VOMSESParser p) { } /** - * Sets a list of paths where vomses files will be looked up by the - * {@link DefaultVOMSServerInfoStore} that this builder is creating - * - * @param paths - * a list of paths + * Sets a list of paths where vomses files will be looked up by the {@link + * DefaultVOMSServerInfoStore} that this builder is creating + * + * @param paths a list of paths * @return this {@link Builder} instance */ public Builder vomsesPaths(List paths) { @@ -209,27 +186,21 @@ public Builder vomsesPaths(List paths) { private void buildLookupStrategy() { - if (lookupStrategy != null) - return; + if (lookupStrategy != null) return; - if (vomsesPaths != null) - lookupStrategy = new BaseVOMSESLookupStrategy(vomsesPaths); - else - lookupStrategy = new DefaultVOMSESLookupStrategy(); + if (vomsesPaths != null) lookupStrategy = new BaseVOMSESLookupStrategy(vomsesPaths); + else lookupStrategy = new DefaultVOMSESLookupStrategy(); } /** * Builds the {@link DefaultVOMSServerInfoStore} - * - * @return a {@link DefaultVOMSServerInfoStore} configured as required by - * this builder + * + * @return a {@link DefaultVOMSServerInfoStore} configured as required by this builder */ public DefaultVOMSServerInfoStore build() { buildLookupStrategy(); return new DefaultVOMSServerInfoStore(this); - } } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACService.java b/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACService.java index 6ab2c82..13471d6 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACService.java +++ b/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACService.java @@ -7,6 +7,8 @@ import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.AA_CERT; import static org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties.AA_KEY; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; @@ -14,7 +16,6 @@ import java.util.Date; import java.util.List; import java.util.Objects; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.italiangrid.voms.VOMSError; @@ -24,9 +25,6 @@ import org.italiangrid.voms.request.VOMSRequestListener; import org.italiangrid.voms.request.VOMSServerInfo; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class FakeVOMSACService implements VOMSACService { final VOMSACGenerator acGenerator; @@ -36,8 +34,9 @@ public class FakeVOMSACService implements VOMSACService { long acSerialNumber = 0; - private FakeVOMSACService(X509Credential aaCredential, ACGenerationParams acParams, - VOMSRequestListener listener) { + private FakeVOMSACService( + X509Credential aaCredential, ACGenerationParams acParams, VOMSRequestListener listener) { + this.acGenerator = new VOMSACGenerator(aaCredential); this.listener = listener; this.acParams = acParams; @@ -45,6 +44,7 @@ private FakeVOMSACService(X509Credential aaCredential, ACGenerationParams acPara private VOMSServerInfo buildFakeServerInfo(String vo, String host, int port) throws URISyntaxException { + DefaultVOMSServerInfo info = new DefaultVOMSServerInfo(); info.setAlias("Fake local VOMS server"); info.setVoName(vo); @@ -55,9 +55,8 @@ private VOMSServerInfo buildFakeServerInfo(String vo, String host, int port) return info; } - protected X509AttributeCertificateHolder buildAC(X509Credential credential, - VOMSACRequest request) { - + protected X509AttributeCertificateHolder buildAC( + X509Credential credential, VOMSACRequest request) { Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); @@ -82,7 +81,6 @@ protected X509AttributeCertificateHolder buildAC(X509Credential credential, notBefore = now; } - Date notAfter = acParams.getNotAfter(); if (Objects.isNull(notAfter)) { cal.add(Calendar.SECOND, request.getLifetime()); @@ -94,9 +92,18 @@ protected X509AttributeCertificateHolder buildAC(X509Credential credential, VOMSServerInfo fakeEndpoint = buildFakeServerInfo(vo, acParams.getHost(), acParams.getPort()); listener.notifyVOMSRequestStart(request, fakeEndpoint); - X509AttributeCertificateHolder ac = acGenerator.generateVOMSAttributeCertificate(fqans, - acParams.getGas(), request.getTargets(), credential.getCertificate(), serialNo, notBefore, - notAfter, vo, acParams.getHost(), acParams.getPort()); + X509AttributeCertificateHolder ac = + acGenerator.generateVOMSAttributeCertificate( + fqans, + acParams.getGas(), + request.getTargets(), + credential.getCertificate(), + serialNo, + notBefore, + notAfter, + vo, + acParams.getHost(), + acParams.getPort()); listener.notifyVOMSRequestSuccess(request, fakeEndpoint); @@ -104,41 +111,44 @@ protected X509AttributeCertificateHolder buildAC(X509Credential credential, } catch (URISyntaxException e) { throw new VOMSError(e.getMessage(), e); } - } @Override - public AttributeCertificate getVOMSAttributeCertificate(X509Credential credential, - VOMSACRequest request) { + public AttributeCertificate getVOMSAttributeCertificate( + X509Credential credential, VOMSACRequest request) { X509AttributeCertificateHolder acHolder = buildAC(credential, request); return acHolder.toASN1Structure(); - - } public ACGenerationParams getAcParams() { + return acParams; } public void setAcParams(ACGenerationParams acParams) { + this.acParams = acParams; } public long getAcSerialNumber() { + return acSerialNumber; } public void setAcSerialNumber(long acSerialNumber) { + this.acSerialNumber = acSerialNumber; } - public static FakeVOMSACService newInstance(X509Credential aaCredential, - ACGenerationParams params, VOMSRequestListener listener) { + public static FakeVOMSACService newInstance( + X509Credential aaCredential, ACGenerationParams params, VOMSRequestListener listener) { + return new FakeVOMSACService(aaCredential, params, listener); } public static FakeVOMSACService newInstanceFromProperties(VOMSRequestListener listener) { + String aaCert = AA_CERT.getSystemPropertyValue(); String aaKey = AA_KEY.getSystemPropertyValue(); @@ -159,8 +169,9 @@ public static FakeVOMSACService newInstanceFromProperties(VOMSRequestListener li } catch (Exception e) { String errorMsg = - String.format("Error loading VOMS fake AC AA credential from '%s' and '%s': %s", aaKey, - aaCert, e.getMessage()); + String.format( + "Error loading VOMS fake AC AA credential from '%s' and '%s': %s", + aaKey, aaCert, e.getMessage()); throw new VOMSError(errorMsg, e); } diff --git a/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACServiceProperties.java b/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACServiceProperties.java index 8acfc6c..a746660 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACServiceProperties.java +++ b/src/main/java/org/italiangrid/voms/request/impl/FakeVOMSACServiceProperties.java @@ -5,7 +5,6 @@ package org.italiangrid.voms.request.impl; public enum FakeVOMSACServiceProperties { - FAKE("voms.fake"), AA_CERT("voms.fake.aaCert", "/etc/grid-security/hostcert.pem"), AA_KEY("voms.fake.aaKey", "/etc/grid-security/hostkey.pem"), @@ -17,25 +16,28 @@ public enum FakeVOMSACServiceProperties { NOT_BEFORE("voms.fake.notBefore"), NOT_AFTER("voms.fake.notAfter"), SERIAL("voms.fake.serial", "0"); - + private String propertyName; private String defaultValue; - + private FakeVOMSACServiceProperties(String propName, String defaultValue) { + this.propertyName = propName; this.defaultValue = defaultValue; } - + private FakeVOMSACServiceProperties(String propName) { + this(propName, null); } - + public String getPropertyName() { + return propertyName; } - + public String getSystemPropertyValue() { + return System.getProperty(getPropertyName(), defaultValue); } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/GoodACDecodingStrategy.java b/src/main/java/org/italiangrid/voms/request/impl/GoodACDecodingStrategy.java index e0e4ec4..107315a 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/GoodACDecodingStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/impl/GoodACDecodingStrategy.java @@ -13,5 +13,4 @@ public byte[] decode(String ac) { return Base64.decode(ac.trim().replaceAll("\n", "")); } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/LegacyProtocol.java b/src/main/java/org/italiangrid/voms/request/impl/LegacyProtocol.java index 822e213..37510d5 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/LegacyProtocol.java +++ b/src/main/java/org/italiangrid/voms/request/impl/LegacyProtocol.java @@ -4,16 +4,19 @@ package org.italiangrid.voms.request.impl; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.impl.CertificateUtils; +import eu.emi.security.authn.x509.impl.FormatMode; +import eu.emi.security.authn.x509.impl.HostnameMismatchCallback2; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; - import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; - import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSProtocol; import org.italiangrid.voms.request.VOMSProtocolError; @@ -21,28 +24,21 @@ import org.italiangrid.voms.request.VOMSResponse; import org.italiangrid.voms.request.VOMSServerInfo; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.CertificateUtils; -import eu.emi.security.authn.x509.impl.FormatMode; -import eu.emi.security.authn.x509.impl.HostnameMismatchCallback2; +/** Protocol implementing the legacy interface. */ +public class LegacyProtocol extends AbstractVOMSProtocol + implements VOMSProtocol, HostnameMismatchCallback2 { -/** - * Protocol implementing the legacy interface. - * - * - */ -public class LegacyProtocol extends AbstractVOMSProtocol implements - VOMSProtocol, HostnameMismatchCallback2 { - - public LegacyProtocol(X509CertChainValidatorExt validator, - VOMSProtocolListener listener, int connectTimeout, int readTimeout) { + public LegacyProtocol( + X509CertChainValidatorExt validator, + VOMSProtocolListener listener, + int connectTimeout, + int readTimeout) { super(validator, listener, connectTimeout, readTimeout); } - public synchronized VOMSResponse doRequest(VOMSServerInfo endpoint, - X509Credential credential, VOMSACRequest request) { + public synchronized VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request) { SSLSocketFactory sslSocketFactory = getSSLSocketFactory(credential); @@ -54,16 +50,14 @@ public synchronized VOMSResponse doRequest(VOMSServerInfo endpoint, sslSocket.setSoTimeout(readTimeout); sslSocket.setEnabledProtocols(VOMS_LEGACY_ENABLED_PROTOCOLS); - SocketAddress sa = new InetSocketAddress(endpoint.getURL().getHost(), - endpoint.getURL().getPort()); + SocketAddress sa = + new InetSocketAddress(endpoint.getURL().getHost(), endpoint.getURL().getPort()); sslSocket.connect(sa, connectTimeout); } catch (Throwable t) { - throw new VOMSProtocolError(t.getMessage(), endpoint, request, - credential, t); - + throw new VOMSProtocolError(t.getMessage(), endpoint, request, credential, t); } LegacyRequestSender protocol = LegacyRequestSender.instance(listener); @@ -82,8 +76,7 @@ public synchronized VOMSResponse doRequest(VOMSServerInfo endpoint, } catch (IOException e) { - throw new VOMSProtocolError(e.getMessage(), endpoint, request, - credential, e); + throw new VOMSProtocolError(e.getMessage(), endpoint, request, credential, e); } listener.notifyReceivedResponse(response); @@ -94,13 +87,11 @@ public synchronized VOMSResponse doRequest(VOMSServerInfo endpoint, public void nameMismatch(X509Certificate peerCertificate, String hostName) throws CertificateException { - String peerCertString = CertificateUtils.format(peerCertificate, - FormatMode.MEDIUM_ONE_LINE); - String message = String - .format( - "No subject alternative DNS name matching %s found. Peer certificate : %s", - hostName, peerCertString); - throw new CertificateException(message); + String peerCertString = CertificateUtils.format(peerCertificate, FormatMode.MEDIUM_ONE_LINE); + String message = + String.format( + "No subject alternative DNS name matching %s found. Peer certificate : %s", + hostName, peerCertString); + throw new CertificateException(message); } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/LegacyRequestSender.java b/src/main/java/org/italiangrid/voms/request/impl/LegacyRequestSender.java index b67cbe7..c090a4e 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/LegacyRequestSender.java +++ b/src/main/java/org/italiangrid/voms/request/impl/LegacyRequestSender.java @@ -6,14 +6,12 @@ import java.io.OutputStream; import java.io.StringWriter; - import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSProtocolListener; @@ -21,11 +19,9 @@ import org.w3c.dom.Document; /** - * This class manages the client-side communication protocol with the VOMS - * server. - * + * This class manages the client-side communication protocol with the VOMS server. + * * @author Andrea Ceccanti - * */ public class LegacyRequestSender { @@ -56,7 +52,6 @@ protected String xmlDocAsString(Document doc) { } catch (TransformerConfigurationException e) { throw new VOMSError(e.getMessage(), e); - } StringWriter writer = new StringWriter(); @@ -72,7 +67,6 @@ protected String xmlDocAsString(Document doc) { } catch (TransformerException e) { throw new VOMSError(e.getMessage(), e); - } writer.flush(); @@ -81,20 +75,13 @@ protected String xmlDocAsString(Document doc) { } /** - * * This method is used to send a request to a VOMS server. - * - * - * @param acRequest - * the AC request parameters. See {@link VOMSACRequest}. - * @param endpoint - * the {@link VOMSServerInfo} endpoint to use for this - * request - * @param stream - * an output stream. + * + * @param acRequest the AC request parameters. See {@link VOMSACRequest}. + * @param endpoint the {@link VOMSServerInfo} endpoint to use for this request + * @param stream an output stream. */ - public void sendRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint, - OutputStream stream) { + public void sendRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint, OutputStream stream) { Document request = requestFactory.buildRequest(acRequest, endpoint); @@ -123,7 +110,6 @@ public void sendRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint, } catch (Exception e) { throw new VOMSError(e.getMessage(), e); - } } } diff --git a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSESParserImpl.java b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSESParserImpl.java index b279008..9740da7 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSESParserImpl.java +++ b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSESParserImpl.java @@ -15,26 +15,23 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSESParser; import org.italiangrid.voms.request.VOMSServerInfo; /** - * Implementation of the {@link org.italiangrid.voms.request.VOMSESParser} interface. - * This class is responsible for parsing VOMSES configuration files and extracting - * {@link org.italiangrid.voms.request.VOMSServerInfo} instances from them. + * Implementation of the {@link org.italiangrid.voms.request.VOMSESParser} interface. This class is + * responsible for parsing VOMSES configuration files and extracting {@link + * org.italiangrid.voms.request.VOMSServerInfo} instances from them. * - *

It supports parsing from files, directories, and readers, and ensures that - * the VOMSES files exist and are readable before processing.

+ *

It supports parsing from files, directories, and readers, and ensures that the VOMSES files + * exist and are readable before processing. * - *

VOMSES files typically contain server connection information in a structured format.

+ *

VOMSES files typically contain server connection information in a structured format. */ public class LegacyVOMSESParserImpl implements VOMSESParser { - /** - * Line parser used to process individual VOMSES lines. - */ + /** Line parser used to process individual VOMSES lines. */ private final VOMSESLineParser lineParser = new VOMSESLineParser(); /** @@ -60,8 +57,7 @@ protected void fileSanityChecks(File f) { * @return a {@link VOMSServerInfo} instance representing the parsed line * @throws URISyntaxException if the URI in the line is malformed */ - protected VOMSServerInfo parseLine(String vomsesLine) - throws URISyntaxException { + protected VOMSServerInfo parseLine(String vomsesLine) throws URISyntaxException { return lineParser.parse(vomsesLine); } @@ -84,18 +80,14 @@ public List parse(Reader vomsesReader) { while ((line = reader.readLine()) != null) { // Ignore comments - if (line.startsWith("#")) - continue; + if (line.startsWith("#")) continue; // skip empty lines - if (line.matches("\\s*$")) - continue; + if (line.matches("\\s*$")) continue; VOMSServerInfo parsedInfo = parseLine(line); - if (parsedInfo != null) - result.add(parsedInfo); - + if (parsedInfo != null) result.add(parsedInfo); } } catch (Exception e) { @@ -115,16 +107,17 @@ protected List parseDirectory(File directory) { Set joinedServerInfo = new HashSet(); - File[] certFiles = directory.listFiles(new FileFilter() { + File[] certFiles = + directory.listFiles( + new FileFilter() { - public boolean accept(File pathname) { + public boolean accept(File pathname) { - return pathname.isFile() && !pathname.getName().startsWith("."); - } - }); + return pathname.isFile() && !pathname.getName().startsWith("."); + } + }); - for (File f : certFiles) - joinedServerInfo.addAll(parse(f)); + for (File f : certFiles) joinedServerInfo.addAll(parse(f)); return new ArrayList(joinedServerInfo); } @@ -140,8 +133,7 @@ public List parse(File f) { fileSanityChecks(f); - if (f.isDirectory()) - return parseDirectory(f); + if (f.isDirectory()) return parseDirectory(f); try { @@ -152,9 +144,7 @@ public List parse(File f) { throw new VOMSError("VOMSES file not found: " + f.getAbsolutePath(), e); } catch (VOMSError e) { - throw new VOMSError("Error parsing VOMSES file: " + f.getAbsolutePath(), - e); + throw new VOMSError("Error parsing VOMSES file: " + f.getAbsolutePath(), e); } } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponse.java b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponse.java index ab3d6d1..fb6abde 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponse.java +++ b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponse.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.List; - import org.italiangrid.voms.request.VOMSErrorMessage; import org.italiangrid.voms.request.VOMSResponse; import org.italiangrid.voms.request.VOMSWarningMessage; @@ -23,11 +22,9 @@ public class LegacyVOMSResponse implements VOMSResponse { protected Document xmlResponse; /** - * Builds a VOMSResponse starting from a DOM an XML document (see - * {@link Document}). - * - * @param res - * the XML document for the response + * Builds a VOMSResponse starting from a DOM an XML document (see {@link Document}). + * + * @param res the XML document for the response */ public LegacyVOMSResponse(Document res) { @@ -36,13 +33,12 @@ public LegacyVOMSResponse(Document res) { /* * (non-Javadoc) - * + * * @see org.glite.voms.contact.VOMSResponseIF#getVersion() */ public int getVersion() { - Element versionElement = (Element) xmlResponse.getElementsByTagName( - "version").item(0); + Element versionElement = (Element) xmlResponse.getElementsByTagName("version").item(0); if (versionElement == null) { @@ -54,7 +50,7 @@ public int getVersion() { /* * (non-Javadoc) - * + * * @see org.glite.voms.contact.VOMSResponseIF#hasErrors() */ public boolean hasErrors() { @@ -64,7 +60,7 @@ public boolean hasErrors() { /* * (non-Javadoc) - * + * * @see org.glite.voms.contact.VOMSResponseIF#hasWarnings() */ public boolean hasWarnings() { @@ -74,35 +70,31 @@ public boolean hasWarnings() { /* * (non-Javadoc) - * + * * @see org.glite.voms.contact.VOMSResponseIF#getAC() */ public byte[] getAC() { - Element acElement = (Element) xmlResponse.getElementsByTagName("ac") - .item(0); + Element acElement = (Element) xmlResponse.getElementsByTagName("ac").item(0); - byte[] ac = VOMSBase64Decoder.decode(acElement.getFirstChild() - .getNodeValue()); + byte[] ac = VOMSBase64Decoder.decode(acElement.getFirstChild().getNodeValue()); if (ac == null) - ac = new GoodACDecodingStrategy().decode(acElement.getFirstChild() - .getNodeValue()); + ac = new GoodACDecodingStrategy().decode(acElement.getFirstChild().getNodeValue()); return ac; } /* * (non-Javadoc) - * + * * @see org.glite.voms.contact.VOMSResponseIF#errorMessages() */ public VOMSErrorMessage[] errorMessages() { NodeList nodes = xmlResponse.getElementsByTagName("item"); - if (nodes.getLength() == 0) - return null; + if (nodes.getLength() == 0) return null; List errorList = new ArrayList(); @@ -110,21 +102,15 @@ public VOMSErrorMessage[] errorMessages() { Element itemElement = (Element) nodes.item(i); - Element numberElement = (Element) itemElement.getElementsByTagName( - "number").item(0); - Element messageElement = (Element) itemElement.getElementsByTagName( - "message").item(0); + Element numberElement = (Element) itemElement.getElementsByTagName("number").item(0); + Element messageElement = (Element) itemElement.getElementsByTagName("message").item(0); - int number = Integer.parseInt(numberElement.getFirstChild() - .getNodeValue()); + int number = Integer.parseInt(numberElement.getFirstChild().getNodeValue()); if (number >= ERROR_OFFSET) - errorList.add(new VOMSErrorMessage(number, messageElement - .getFirstChild().getNodeValue())); - + errorList.add(new VOMSErrorMessage(number, messageElement.getFirstChild().getNodeValue())); } - if (errorList.isEmpty()) - return null; + if (errorList.isEmpty()) return null; return errorList.toArray(new VOMSErrorMessage[errorList.size()]); } @@ -133,8 +119,7 @@ public VOMSWarningMessage[] warningMessages() { NodeList nodes = xmlResponse.getElementsByTagName("item"); - if (nodes.getLength() == 0) - return null; + if (nodes.getLength() == 0) return null; List warningList = new ArrayList(); @@ -142,22 +127,17 @@ public VOMSWarningMessage[] warningMessages() { Element itemElement = (Element) nodes.item(i); - Element numberElement = (Element) itemElement.getElementsByTagName( - "number").item(0); - Element messageElement = (Element) itemElement.getElementsByTagName( - "message").item(0); + Element numberElement = (Element) itemElement.getElementsByTagName("number").item(0); + Element messageElement = (Element) itemElement.getElementsByTagName("message").item(0); - int number = Integer.parseInt(numberElement.getFirstChild() - .getNodeValue()); + int number = Integer.parseInt(numberElement.getFirstChild().getNodeValue()); if (number < ERROR_OFFSET) - warningList.add(new VOMSWarningMessage(number, messageElement - .getFirstChild().getNodeValue())); - + warningList.add( + new VOMSWarningMessage(number, messageElement.getFirstChild().getNodeValue())); } - if (warningList.isEmpty()) - return null; + if (warningList.isEmpty()) return null; return warningList.toArray(new VOMSWarningMessage[warningList.size()]); } @@ -165,7 +145,5 @@ public VOMSWarningMessage[] warningMessages() { public String getXMLAsString() { return XMLUtils.documentAsString(xmlResponse); - } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponseParsingStrategy.java b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponseParsingStrategy.java index 07a39e5..ab3b3e9 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponseParsingStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/impl/LegacyVOMSResponseParsingStrategy.java @@ -5,11 +5,9 @@ package org.italiangrid.voms.request.impl; import java.io.InputStream; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSResponse; import org.italiangrid.voms.request.VOMSResponseParsingStrategy; @@ -17,12 +15,10 @@ /** * Parsing strategy for legacy VOMS responses. - * - * @author valerioventuri * + * @author valerioventuri */ -public class LegacyVOMSResponseParsingStrategy implements - VOMSResponseParsingStrategy { +public class LegacyVOMSResponseParsingStrategy implements VOMSResponseParsingStrategy { protected DocumentBuilder documentBuilder; @@ -54,8 +50,6 @@ public VOMSResponse parse(InputStream inputStream) { } catch (Exception e) { throw new VOMSError(e.getMessage()); - } - } } diff --git a/src/main/java/org/italiangrid/voms/request/impl/RESTProtocol.java b/src/main/java/org/italiangrid/voms/request/impl/RESTProtocol.java index 8ba3382..12215dc 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/RESTProtocol.java +++ b/src/main/java/org/italiangrid/voms/request/impl/RESTProtocol.java @@ -4,14 +4,14 @@ package org.italiangrid.voms.request.impl; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.X509Credential; import java.io.IOException; import java.io.InputStream; import java.net.URL; - import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; - import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSProtocol; import org.italiangrid.voms.request.VOMSProtocolError; @@ -19,25 +19,24 @@ import org.italiangrid.voms.request.VOMSResponse; import org.italiangrid.voms.request.VOMSServerInfo; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.X509Credential; - /** * Protocol implementing the REST-style interface. - * + * * @author valerioventuri - * */ public class RESTProtocol extends AbstractVOMSProtocol implements VOMSProtocol { - public RESTProtocol(X509CertChainValidatorExt validator, - VOMSProtocolListener listener, int connectTimeout, int readTimeout) { + public RESTProtocol( + X509CertChainValidatorExt validator, + VOMSProtocolListener listener, + int connectTimeout, + int readTimeout) { super(validator, listener, connectTimeout, readTimeout); } - public VOMSResponse doRequest(VOMSServerInfo endpoint, - X509Credential credential, VOMSACRequest request) { + public VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request) { RESTServiceURLBuilder restQueryBuilder = new RESTServiceURLBuilder(); URL serviceUrl = restQueryBuilder.build(endpoint, request); @@ -48,13 +47,16 @@ public VOMSResponse doRequest(VOMSServerInfo endpoint, try { connection = (HttpsURLConnection) serviceUrl.openConnection(); - - if (isSkipHostnameChecks()){ - connection.setHostnameVerifier(new HostnameVerifier() { - public boolean verify(String arg0, SSLSession arg1) { - return true; - } - }); + + if (isSkipHostnameChecks()) { + connection.setHostnameVerifier( + new HostnameVerifier() { + + public boolean verify(String arg0, SSLSession arg1) { + + return true; + } + }); } connection.setConnectTimeout(connectTimeout); @@ -62,8 +64,7 @@ public boolean verify(String arg0, SSLSession arg1) { } catch (IOException e) { - throw new VOMSProtocolError(e.getMessage(), endpoint, request, - credential, e); + throw new VOMSProtocolError(e.getMessage(), endpoint, request, credential, e); } connection.setSSLSocketFactory(getSSLSocketFactory(credential)); @@ -76,9 +77,7 @@ public boolean verify(String arg0, SSLSession arg1) { } catch (IOException e) { - throw new VOMSProtocolError(e.getMessage(), endpoint, request, - credential, e); - + throw new VOMSProtocolError(e.getMessage(), endpoint, request, credential, e); } InputStream is = null; @@ -86,13 +85,11 @@ public boolean verify(String arg0, SSLSession arg1) { try { if (connection.getResponseCode() != 200) { is = connection.getErrorStream(); - } else - is = connection.getInputStream(); + } else is = connection.getInputStream(); } catch (IOException e) { - throw new VOMSProtocolError(e.getMessage(), endpoint, request, - credential, e); + throw new VOMSProtocolError(e.getMessage(), endpoint, request, credential, e); } VOMSResponse response = responseParsingStrategy.parse(is); @@ -102,5 +99,4 @@ public boolean verify(String arg0, SSLSession arg1) { return response; } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/RESTServiceURLBuilder.java b/src/main/java/org/italiangrid/voms/request/impl/RESTServiceURLBuilder.java index 36a0be8..8b1271d 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/RESTServiceURLBuilder.java +++ b/src/main/java/org/italiangrid/voms/request/impl/RESTServiceURLBuilder.java @@ -8,17 +8,15 @@ import java.net.URL; import java.util.Iterator; import java.util.List; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSServerInfo; /** - * An helper class which builds a URL suitable for an HTTPS VOMS REST request - * starting from the VOMS URI as available in a {@link VOMSServerInfo} object. - * + * An helper class which builds a URL suitable for an HTTPS VOMS REST request starting from the VOMS + * URI as available in a {@link VOMSServerInfo} object. + * * @author Valerio Venturi - * */ public class RESTServiceURLBuilder { @@ -28,8 +26,12 @@ public URL build(VOMSServerInfo endpoint, VOMSACRequest request) { try { - url = new URL("https", endpoint.getURL().getHost(), endpoint.getURL() - .getPort(), buildPath(endpoint, request)); + url = + new URL( + "https", + endpoint.getURL().getHost(), + endpoint.getURL().getPort(), + buildPath(endpoint, request)); } catch (MalformedURLException e) { @@ -59,8 +61,7 @@ private String buildPath(VOMSServerInfo endpoint, VOMSACRequest request) { while (i.hasNext()) { - if (!first) - stringBuilder.append(","); + if (!first) stringBuilder.append(","); stringBuilder.append((String) i.next()); diff --git a/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponse.java b/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponse.java index e89727a..1bd3157 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponse.java +++ b/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponse.java @@ -14,10 +14,8 @@ import org.w3c.dom.NodeList; /** - * * This class is used to parse and represent VOMS server responses coming from a RESTful VOMS * service. - * */ public class RESTVOMSResponse implements VOMSResponse { @@ -137,7 +135,7 @@ public VOMSErrorMessage[] errorMessages() { * Retrieves warning messages from the response. * * @return an array of {@link VOMSWarningMessage} objects, or {@code null} if no warnings are - * found + * found */ public VOMSWarningMessage[] warningMessages() { @@ -183,5 +181,4 @@ public String getXMLAsString() { return XMLUtils.documentAsString(xmlResponse); } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponseParsingStrategy.java b/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponseParsingStrategy.java index 999a30c..c2eb13e 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponseParsingStrategy.java +++ b/src/main/java/org/italiangrid/voms/request/impl/RESTVOMSResponseParsingStrategy.java @@ -5,11 +5,9 @@ package org.italiangrid.voms.request.impl; import java.io.InputStream; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSResponse; import org.italiangrid.voms.request.VOMSResponseParsingStrategy; @@ -17,18 +15,14 @@ /** * Strategy for parsing a response coming from a RESTFul VOMS. - * - * @author valerioventuri * + * @author valerioventuri */ -public class RESTVOMSResponseParsingStrategy implements - VOMSResponseParsingStrategy { +public class RESTVOMSResponseParsingStrategy implements VOMSResponseParsingStrategy { private DocumentBuilder docBuilder; - /** - * - */ + /** */ public RESTVOMSResponseParsingStrategy() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -44,17 +38,14 @@ public RESTVOMSResponseParsingStrategy() { throw new VOMSError(e.getMessage(), e); } - } /** - * Parse a response coming from a RESTFul VOMS service and builds a - * {@link VOMSResponse} object representing the response. - * - * @param inputStream - * the response coming from the service + * Parse a response coming from a RESTFul VOMS service and builds a {@link VOMSResponse} object + * representing the response. + * + * @param inputStream the response coming from the service * @return a {@link VOMSResponse} object representing the response. - * */ public VOMSResponse parse(InputStream inputStream) { @@ -67,8 +58,6 @@ public VOMSResponse parse(InputStream inputStream) { } catch (Exception e) { throw new VOMSError(e.getMessage()); - } } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/VOMSESLineParser.java b/src/main/java/org/italiangrid/voms/request/impl/VOMSESLineParser.java index 4a1aaaa..bbee073 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/VOMSESLineParser.java +++ b/src/main/java/org/italiangrid/voms/request/impl/VOMSESLineParser.java @@ -6,59 +6,63 @@ import java.net.URI; import java.net.URISyntaxException; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSServerInfo; /** * A parser for VOMSES lines. - * - * The VOMSES line format is as follows: - * + * + *

The VOMSES line format is as follows: + * *

  * "alias" "hostname" "port" "server DN" "vo_name"
  * 
- * - * This parser eats up whitespace and characters outside of quotes and tolerates - * an additional quoted field ("globus_version") that was for some time needed. - * - * + * + * This parser eats up whitespace and characters outside of quotes and tolerates an additional + * quoted field ("globus_version") that was for some time needed. + * * @author andreaceccanti - * */ public class VOMSESLineParser { private interface ParserState { void parse(char c); - }; + } + ; - private final ParserState outsideQuotes = new ParserState() { + private final ParserState outsideQuotes = + new ParserState() { - public void parse(char c) { + public void parse(char c) { - if (c == '"') - VOMSESLineParser.this.tokenStart(); - } - }; + if (c == '"') VOMSESLineParser.this.tokenStart(); + } + }; - private final ParserState insideQuotes = new ParserState() { + private final ParserState insideQuotes = + new ParserState() { - public void parse(char c) { + public void parse(char c) { - if (c == '"') { - VOMSESLineParser.this.tokenEnd(); - } else { - VOMSESLineParser.this.tokenChar(c); - } - } - }; + if (c == '"') { + VOMSESLineParser.this.tokenEnd(); + } else { + VOMSESLineParser.this.tokenChar(c); + } + } + }; - static final String VOMSES_FIELD_NAMES[] = { "vo alias", "voms host", - "voms port", "voms server DN", "vo name", "globus version" }; + static final String VOMSES_FIELD_NAMES[] = { + "vo alias", "voms host", "voms port", "voms server DN", "vo name", "globus version" + }; - static final int VO_ALIAS = 0, VOMS_HOST = 1, VOMS_PORT = 2, - VOMS_SERVER_DN = 3, VO_NAME = 4, GLOBUS_VERSION = 5; + static final int VO_ALIAS = 0, + VOMS_HOST = 1, + VOMS_PORT = 2, + VOMS_SERVER_DN = 3, + VO_NAME = 4, + GLOBUS_VERSION = 5; static final int MIN_VOMSES_FIELD_COUNT = 4; @@ -72,8 +76,7 @@ public void parse(char c) { private void lineSanityChecks(String line) { - if (line == null) - throw new VOMSError("Cannot parse a null VOMSES line"); + if (line == null) throw new VOMSError("Cannot parse a null VOMSES line"); } private void init() { @@ -82,8 +85,7 @@ private void init() { currentToken = null; tokenComplete = false; currentState = outsideQuotes; - for (int i = 0; i < tokens.length; i++) - tokens[i] = null; + for (int i = 0; i < tokens.length; i++) tokens[i] = null; } public VOMSServerInfo parse(String line) { @@ -92,8 +94,7 @@ public VOMSServerInfo parse(String line) { lineSanityChecks(line); - if (line.isEmpty()) - return null; + if (line.isEmpty()) return null; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); @@ -101,23 +102,22 @@ public VOMSServerInfo parse(String line) { } if (!tokenComplete) { - String msg = String.format( - "Invalid VOMSES line: incomplete '%s' field. [line: %s]", - VOMSES_FIELD_NAMES[tokenCount], line); + String msg = + String.format( + "Invalid VOMSES line: incomplete '%s' field. [line: %s]", + VOMSES_FIELD_NAMES[tokenCount], line); throw new VOMSError(msg); } if (tokenCount < MIN_VOMSES_FIELD_COUNT) { - String msg = String.format( - "Invalid VOMSES line: incomplete information. [line: %s]", line); + String msg = String.format("Invalid VOMSES line: incomplete information. [line: %s]", line); throw new VOMSError(msg); } DefaultVOMSServerInfo si = new DefaultVOMSServerInfo(); si.setAlias(tokens[VO_ALIAS]); - String url = String.format("voms://%s:%s", tokens[VOMS_HOST], - tokens[VOMS_PORT]); + String url = String.format("voms://%s:%s", tokens[VOMS_HOST], tokens[VOMS_PORT]); validateTokens(line); @@ -129,9 +129,9 @@ public VOMSServerInfo parse(String line) { return si; } catch (URISyntaxException e) { - String msg = String.format( - "Invalid VOMSES line: cannot build URL for voms " + "service: %s", - e.getMessage()); + String msg = + String.format( + "Invalid VOMSES line: cannot build URL for voms " + "service: %s", e.getMessage()); throw new VOMSError(msg); } @@ -144,14 +144,15 @@ private void validateTokens(String line) { int portNo = Integer.parseInt(tokens[VOMS_PORT]); if (portNo <= 0 || portNo > 65535) { - String msg = String.format( - "Invalid VOMSES line: invalid port number: %d. [line: %s]", portNo, - line); + String msg = + String.format("Invalid VOMSES line: invalid port number: %d. [line: %s]", portNo, line); throw new VOMSError(msg); } } catch (NumberFormatException e) { - String msg = String.format("Invalid VOMSES line: invalid port number. " - + "[line: %s]. Error: %s", line, e.getMessage()); + String msg = + String.format( + "Invalid VOMSES line: invalid port number. " + "[line: %s]. Error: %s", + line, e.getMessage()); throw new VOMSError(msg, e); } @@ -177,17 +178,15 @@ public void tokenEnd() { } else { - String msg = String.format("Invalid VOMSES line: empty '%s' field.", - VOMSES_FIELD_NAMES[tokenCount]); + String msg = + String.format("Invalid VOMSES line: empty '%s' field.", VOMSES_FIELD_NAMES[tokenCount]); throw new VOMSError(msg); } - } public void tokenChar(char c) { currentToken.append(c); } - } diff --git a/src/main/java/org/italiangrid/voms/request/impl/VOMSRequestFactory.java b/src/main/java/org/italiangrid/voms/request/impl/VOMSRequestFactory.java index 6441f2d..41f55b4 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/VOMSRequestFactory.java +++ b/src/main/java/org/italiangrid/voms/request/impl/VOMSRequestFactory.java @@ -5,11 +5,9 @@ package org.italiangrid.voms.request.impl; import java.util.Iterator; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSServerInfo; @@ -19,12 +17,9 @@ import org.w3c.dom.Element; /** - * - * This class builds VOMS XML requests starting from {@link VOMSACRequest} - * objects. - * + * This class builds VOMS XML requests starting from {@link VOMSACRequest} objects. + * * @author Andrea Ceccanti - * */ public class VOMSRequestFactory { @@ -36,13 +31,11 @@ public class VOMSRequestFactory { protected DocumentBuilder docBuilder; - public synchronized static VOMSRequestFactory instance() { + public static synchronized VOMSRequestFactory instance() { - if (instance == null) - instance = new VOMSRequestFactory(); + if (instance == null) instance = new VOMSRequestFactory(); return instance; - } private VOMSRequestFactory() { @@ -57,7 +50,6 @@ private VOMSRequestFactory() { } catch (ParserConfigurationException e) { throw new VOMSError(e.getMessage()); } - } public long getLifetime() { @@ -92,11 +84,9 @@ public void setTargetString(String targetString) { private void setOptionsForRequest(VOMSRequestFragment fragment) { - if (orderString != null && orderString != "") - fragment.buildOrderElement(orderString); + if (orderString != null && orderString != "") fragment.buildOrderElement(orderString); - if (targetString != null && targetString != "") - fragment.buildTargetsElement(targetString); + if (targetString != null && targetString != "") fragment.buildTargetsElement(targetString); fragment.buildLifetime(lifetime); } @@ -142,8 +132,8 @@ public Document buildRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint) { } else if (VOMSFQANNamingScheme.isQualifiedRole(FQAN)) { - frag.mappingCommand(VOMSFQANNamingScheme.getGroupName(FQAN), - VOMSFQANNamingScheme.getRoleName(FQAN)); + frag.mappingCommand( + VOMSFQANNamingScheme.getGroupName(FQAN), VOMSFQANNamingScheme.getRoleName(FQAN)); } } @@ -152,14 +142,12 @@ public Document buildRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint) { request.appendChild(frag.getFragment()); return request; } - } /** * Helper class to manage the creation of VOMS XML requests. - * + * * @author andreaceccanti - * */ class VOMSRequestFragment { @@ -186,7 +174,6 @@ protected void buildRootElement() { root = doc.createElement("voms"); fragment.appendChild(root); - } private void appendTextChild(Element e, String text) { @@ -198,8 +185,7 @@ private String buildCompatibleOrderString(String s) { String[] FQANs = s.split(","); - if (FQANs.length == 0) - return ""; + if (FQANs.length == 0) return ""; for (int i = 0; i < FQANs.length; i++) { if (VOMSFQANNamingScheme.isQualifiedRole(FQANs[i])) @@ -210,8 +196,7 @@ private String buildCompatibleOrderString(String s) { for (int i = 0; i < FQANs.length; i++) { fqansString.append(FQANs); - if (i < FQANs.length - 1) - fqansString.append(","); + if (i < FQANs.length - 1) fqansString.append(","); } return fqansString.toString(); @@ -239,7 +224,6 @@ void buildTargetsElement(String targetString) { targets = doc.createElement("targets"); appendTextChild(targets, targetString); root.appendChild(targets); - } void buildLifetime(long lifetime) { @@ -281,13 +265,11 @@ public void groupCommand(String groupName) { public void roleCommand(String roleName) { buildCommandElement("R" + roleName); - } public void mappingCommand(String groupName, String roleName) { buildCommandElement("B" + groupName + ":" + roleName); - } public void allCommand() { diff --git a/src/main/java/org/italiangrid/voms/request/impl/package-info.java b/src/main/java/org/italiangrid/voms/request/impl/package-info.java index f32e99c..80e09f8 100644 --- a/src/main/java/org/italiangrid/voms/request/impl/package-info.java +++ b/src/main/java/org/italiangrid/voms/request/impl/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the implementation logic for VOMS attributes requests. - */ +/** This package provides the implementation logic for VOMS attributes requests. */ package org.italiangrid.voms.request.impl; - diff --git a/src/main/java/org/italiangrid/voms/request/package-info.java b/src/main/java/org/italiangrid/voms/request/package-info.java index 2398944..1b6010b 100644 --- a/src/main/java/org/italiangrid/voms/request/package-info.java +++ b/src/main/java/org/italiangrid/voms/request/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the API for requesting VOMS attribtues from a remote VOMS server. - */ +/** This package provides the API for requesting VOMS attribtues from a remote VOMS server. */ package org.italiangrid.voms.request; - diff --git a/src/main/java/org/italiangrid/voms/store/LSCFileParser.java b/src/main/java/org/italiangrid/voms/store/LSCFileParser.java index 67d0a0a..7764033 100644 --- a/src/main/java/org/italiangrid/voms/store/LSCFileParser.java +++ b/src/main/java/org/italiangrid/voms/store/LSCFileParser.java @@ -6,47 +6,35 @@ import java.io.File; import java.io.InputStream; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.impl.LSCFile; /** * This interface defines a parser for VOMS LSC files. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface LSCFileParser { /** * Parses an LSC file. - * - * @param vo - * the name of the VO this LSC file is about - * @param hostname - * the name of host this LSC file is about - * @param file - * the LSC file + * + * @param vo the name of the VO this LSC file is about + * @param hostname the name of host this LSC file is about + * @param file the LSC file * @return an {@link LSCFile} object - * @throws VOMSError - * in case of parsing errors + * @throws VOMSError in case of parsing errors */ public LSCFile parse(String vo, String hostname, File file); /** * Parses an LSC file from a generic input stream. - * - * @param vo - * the name of the VO this LSC file is about - * @param hostname - * the name of host this LSC file is about - * @param is - * an {@link InputStream} that contains the LSC information - * + * + * @param vo the name of the VO this LSC file is about + * @param hostname the name of host this LSC file is about + * @param is an {@link InputStream} that contains the LSC information * @return an {@link LSCFile} object - * @throws VOMSError - * in case of parsing errors + * @throws VOMSError in case of parsing errors */ public LSCFile parse(String vo, String hostname, InputStream is); - } diff --git a/src/main/java/org/italiangrid/voms/store/LSCInfo.java b/src/main/java/org/italiangrid/voms/store/LSCInfo.java index ef3bc0f..6d92871 100644 --- a/src/main/java/org/italiangrid/voms/store/LSCInfo.java +++ b/src/main/java/org/italiangrid/voms/store/LSCInfo.java @@ -9,66 +9,57 @@ /** * The VOMS LSC information. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public interface LSCInfo { /** * Sets the name of the file from where this LSC info was parsed from. - * - * @param filename - * the name of the file from where this LSC info was parsed from. + * + * @param filename the name of the file from where this LSC info was parsed from. */ public void setFilename(String filename); /** * Returns the name of file from where this LSC info was parsed from. - * + * * @return the name of the file from where this LSC info was parsed from. */ public String getFilename(); /** * Returns the VO name this LSC info applies to. - * + * * @return the VO name this LSC info applies to */ public String getVOName(); /** * Returns the host name of the VOMS AA this LSC info applies to. - * + * * @return the host name of the VOMS AA this LSC info applies to */ public String getHostname(); /** - * Returns the certificate chain description of the VOMS AA for the given VO - * and hostname. - * - * The certificate chain description is a list of X.500 distinguished names - * encoded as strings according to the OpenSSL slash-separated format, as in: - * /C=IT/O=INFN/CN=INFN CA - * - * The first element in the description is the leaf certificate, while the - * last is the CA certificate. - * - * @return the certificate chain description of the VOMS AA for the given VO - * and hostname. + * Returns the certificate chain description of the VOMS AA for the given VO and hostname. + * + *

The certificate chain description is a list of X.500 distinguished names encoded as strings + * according to the OpenSSL slash-separated format, as in: /C=IT/O=INFN/CN=INFN CA + * The first element in the description is the leaf certificate, while the last is the CA + * certificate. + * + * @return the certificate chain description of the VOMS AA for the given VO and hostname. */ public List getCertificateChainDescription(); /** - * Checks if the certificate chain description maintained in the LSC - * information matches the certificate chain passed as argument. - * - * @param certChain - * the certificate chain to be checked - * @return true if the description matches, false - * otherwise + * Checks if the certificate chain description maintained in the LSC information matches the + * certificate chain passed as argument. + * + * @param certChain the certificate chain to be checked + * @return true if the description matches, false otherwise */ public boolean matches(X509Certificate[] certChain); - } diff --git a/src/main/java/org/italiangrid/voms/store/Updateable.java b/src/main/java/org/italiangrid/voms/store/Updateable.java index ded8187..c2b3adf 100644 --- a/src/main/java/org/italiangrid/voms/store/Updateable.java +++ b/src/main/java/org/italiangrid/voms/store/Updateable.java @@ -5,28 +5,20 @@ package org.italiangrid.voms.store; /** - * Represents an object which can be periodically updated according to an update - * frequency. - * - * @author Andrea Ceccanti + * Represents an object which can be periodically updated according to an update frequency. * + * @author Andrea Ceccanti */ public interface Updateable { /** - * @return the frequency (in milliseconds) currently set for this - * {@link Updateable} object. + * @return the frequency (in milliseconds) currently set for this {@link Updateable} object. */ public long getUpdateFrequency(); - /** - * Updates the object. - */ + /** Updates the object. */ public void update(); - /** - * Cancels the future updates of this {@link Updateable} object. - */ + /** Cancels the future updates of this {@link Updateable} object. */ public void cancel(); - } diff --git a/src/main/java/org/italiangrid/voms/store/UpdatingVOMSTrustStore.java b/src/main/java/org/italiangrid/voms/store/UpdatingVOMSTrustStore.java index d9f4320..c632928 100644 --- a/src/main/java/org/italiangrid/voms/store/UpdatingVOMSTrustStore.java +++ b/src/main/java/org/italiangrid/voms/store/UpdatingVOMSTrustStore.java @@ -6,10 +6,7 @@ /** * A VOMS trust store that can be periodically refreshed. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ -public interface UpdatingVOMSTrustStore extends VOMSTrustStore, Updateable { - -} +public interface UpdatingVOMSTrustStore extends VOMSTrustStore, Updateable {} diff --git a/src/main/java/org/italiangrid/voms/store/VOMSTrustStore.java b/src/main/java/org/italiangrid/voms/store/VOMSTrustStore.java index 33e12bf..0a57747 100644 --- a/src/main/java/org/italiangrid/voms/store/VOMSTrustStore.java +++ b/src/main/java/org/italiangrid/voms/store/VOMSTrustStore.java @@ -8,81 +8,68 @@ import java.util.List; import java.util.Map; import java.util.Set; - import javax.security.auth.x500.X500Principal; /** - * The VOMS trust store takes care of parsing local trusted information (being - * certificates or LSC files) for known VOMS servers. - * - * @author Andrea Ceccanti + * The VOMS trust store takes care of parsing local trusted information (being certificates or LSC + * files) for known VOMS servers. * + * @author Andrea Ceccanti */ public interface VOMSTrustStore { /** - * Returns the locally trusted directories where VOMS trust information (being - * VOMS server certificates or LSC files) are searched for. - * + * Returns the locally trusted directories where VOMS trust information (being VOMS server + * certificates or LSC files) are searched for. + * * @return a {@link List} of local paths */ public List getLocalTrustedDirectories(); /** - * Returns the list of VOMS Attribute Authority certificates held in this - * {@link VOMSTrustStore}. - * - * @return the collection of VOMS Attribute Authority certificates held in - * this {@link VOMSTrustStore}, an empty list if no certificate was - * found. + * Returns the list of VOMS Attribute Authority certificates held in this {@link VOMSTrustStore}. + * + * @return the collection of VOMS Attribute Authority certificates held in this {@link + * VOMSTrustStore}, an empty list if no certificate was found. */ public List getLocalAACertificates(); /** - * Returns the VOMS Attribute Authority certificate held in this - * {@link VOMSTrustStore} whose subject matches the subject passed as - * argument. - * - * @param aaCertSubject - * a certificate subject - * @return the VOMS AA {@link X509Certificate} that matches the subject passed - * as argument or null if no matching certificate is found in this - * store + * Returns the VOMS Attribute Authority certificate held in this {@link VOMSTrustStore} whose + * subject matches the subject passed as argument. + * + * @param aaCertSubject a certificate subject + * @return the VOMS AA {@link X509Certificate} that matches the subject passed as argument or null + * if no matching certificate is found in this store */ public X509Certificate getAACertificateBySubject(X500Principal aaCertSubject); /** - * Returns the LSC information held in this {@link VOMSTrustStore} for the vo - * and hostname passed as arguments. - * - * @param voName - * the name of the VO for which the LSC applies - * @param hostname - * the name of the host for which the LSC applies - * @return a {@link LSCInfo} object, or null if no LSC matching the arguments - * was found + * Returns the LSC information held in this {@link VOMSTrustStore} for the vo and hostname passed + * as arguments. + * + * @param voName the name of the VO for which the LSC applies + * @param hostname the name of the host for which the LSC applies + * @return a {@link LSCInfo} object, or null if no LSC matching the arguments was found */ public LSCInfo getLSC(String voName, String hostname); /** - * Returns all the LSC information held in this {@link VOMSTrustStore}. The - * returned {@link Map} is keyed by VO name. - * + * Returns all the LSC information held in this {@link VOMSTrustStore}. The returned {@link Map} + * is keyed by VO name. + * * @return a possibly empty map {@link LSCInfo} objects */ public Map> getAllLSCInfo(); - /** - * Loads trust information from the sources configured for this trust store. - */ + /** Loads trust information from the sources configured for this trust store. */ public void loadTrustInformation(); /** - * Sets a {@link VOMSTrustStoreStatusListener} that is notified of events - * related to this VOMS trust store - * - * @param statusListener - * the status listener that will be notified + * Sets a {@link VOMSTrustStoreStatusListener} that is notified of events related to this VOMS + * trust store + * + * @param statusListener the status listener that will be notified */ public void setStatusListener(VOMSTrustStoreStatusListener statusListener); } diff --git a/src/main/java/org/italiangrid/voms/store/VOMSTrustStoreStatusListener.java b/src/main/java/org/italiangrid/voms/store/VOMSTrustStoreStatusListener.java index 53655d8..4e8795c 100644 --- a/src/main/java/org/italiangrid/voms/store/VOMSTrustStoreStatusListener.java +++ b/src/main/java/org/italiangrid/voms/store/VOMSTrustStoreStatusListener.java @@ -8,51 +8,39 @@ import java.security.cert.X509Certificate; /** - * - * This interface used to notify interested listeners in status changes of a - * VOMS trust store. - * - * @author Andrea Ceccanti + * This interface used to notify interested listeners in status changes of a VOMS trust store. * + * @author Andrea Ceccanti */ public interface VOMSTrustStoreStatusListener { /** - * Informs that certificates are being looked for in the directory passed as - * argument - * - * @param dir - * the directory where certificates are being looked for + * Informs that certificates are being looked for in the directory passed as argument + * + * @param dir the directory where certificates are being looked for */ public void notifyCertficateLookupEvent(String dir); /** - * Informs that VOMS LSC file information is being looked for in the directory - * passed as argument. - * - * @param dir - * the directory where certificates are being looked for + * Informs that VOMS LSC file information is being looked for in the directory passed as argument. + * + * @param dir the directory where certificates are being looked for */ public void notifyLSCLookupEvent(String dir); /** * Informs that a VOMS AA certificate has been loaded in the store - * - * @param cert - * the VOMS AA certificate loaded - * @param f - * the file from which the certificate has been loaded + * + * @param cert the VOMS AA certificate loaded + * @param f the file from which the certificate has been loaded */ public void notifyCertificateLoadEvent(X509Certificate cert, File f); /** * Informs that VOMS LSC information has been loaded in the store - * - * @param lsc - * the loaded VOMS LSC information - * @param f - * the file from which the LSC information has been loaded + * + * @param lsc the loaded VOMS LSC information + * @param f the file from which the LSC information has been loaded */ public void notifyLSCLoadEvent(LSCInfo lsc, File f); - } diff --git a/src/main/java/org/italiangrid/voms/store/VOMSTrustStores.java b/src/main/java/org/italiangrid/voms/store/VOMSTrustStores.java index b11acdd..bbf61ed 100644 --- a/src/main/java/org/italiangrid/voms/store/VOMSTrustStores.java +++ b/src/main/java/org/italiangrid/voms/store/VOMSTrustStores.java @@ -5,20 +5,18 @@ package org.italiangrid.voms.store; import java.util.List; - import org.italiangrid.voms.store.impl.DefaultUpdatingVOMSTrustStore; /** * A factory for VOMS trust stores - * - * @author cecco * + * @author cecco */ public class VOMSTrustStores { /** * Creates a {@link VOMSTrustStore} configured with default settings. - * + * * @return a {@link VOMSTrustStore} configured with default settings. */ public static VOMSTrustStore newTrustStore() { @@ -27,31 +25,25 @@ public static VOMSTrustStore newTrustStore() { } /** - * Creates a {@link VOMSTrustStore} configured according to the parameters - * passed as argument - * - * @param localTrustDirs - * the directory where voms information will be searched - * @param updateFrequency - * the trust store update frequency in milliseconds - * @param statusListener - * a listener that is notified of events related to the created trust - * store + * Creates a {@link VOMSTrustStore} configured according to the parameters passed as argument + * + * @param localTrustDirs the directory where voms information will be searched + * @param updateFrequency the trust store update frequency in milliseconds + * @param statusListener a listener that is notified of events related to the created trust store * @return a {@link VOMSTrustStore} configured as requested. */ - public static VOMSTrustStore newTrustStore(List localTrustDirs, - long updateFrequency, VOMSTrustStoreStatusListener statusListener) { + public static VOMSTrustStore newTrustStore( + List localTrustDirs, + long updateFrequency, + VOMSTrustStoreStatusListener statusListener) { - return new DefaultUpdatingVOMSTrustStore(localTrustDirs, updateFrequency, - statusListener); + return new DefaultUpdatingVOMSTrustStore(localTrustDirs, updateFrequency, statusListener); } /** - * Creates a {@link VOMSTrustStore} configured according to the parameters - * passed as argument - * - * @param localTrustDirs - * the directory where voms information will be searched + * Creates a {@link VOMSTrustStore} configured according to the parameters passed as argument + * + * @param localTrustDirs the directory where voms information will be searched * @return a {@link VOMSTrustStore} configured as requested. */ public static VOMSTrustStore newTrustStore(List localTrustDirs) { @@ -60,16 +52,13 @@ public static VOMSTrustStore newTrustStore(List localTrustDirs) { } /** - * Creates a {@link VOMSTrustStore} configured according to the parameters - * passed as argument - * - * @param updateFrequency - * the trust store update frequency in milliseconds + * Creates a {@link VOMSTrustStore} configured according to the parameters passed as argument + * + * @param updateFrequency the trust store update frequency in milliseconds * @return a {@link VOMSTrustStore} configured as requested. */ public static VOMSTrustStore newTrustStore(long updateFrequency) { return new DefaultUpdatingVOMSTrustStore(updateFrequency); } - } diff --git a/src/main/java/org/italiangrid/voms/store/impl/DefaultLSCFileParser.java b/src/main/java/org/italiangrid/voms/store/impl/DefaultLSCFileParser.java index 9679a5c..b826e30 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/DefaultLSCFileParser.java +++ b/src/main/java/org/italiangrid/voms/store/impl/DefaultLSCFileParser.java @@ -12,19 +12,18 @@ import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.LSCFileParser; /** * The default implementation for the LSC file parser. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class DefaultLSCFileParser implements LSCFileParser { - public static final String MALFORMED_LSC_FILE_ERROR_TEMPLATE = "LSC file parsing error: Malformed LSC file (vo=%s, host=%s): %s"; + public static final String MALFORMED_LSC_FILE_ERROR_TEMPLATE = + "LSC file parsing error: Malformed LSC file (vo=%s, host=%s): %s"; private void checkFileExistanceAndReadabilty(File f) { @@ -74,14 +73,23 @@ public synchronized LSCFile parse(String vo, String hostname, InputStream is) { } private void validateChain(List certificateChainDescription, String vo, String hostname) { + if (certificateChainDescription.size() % 2 != 0) { - String errorMessage = String.format(MALFORMED_LSC_FILE_ERROR_TEMPLATE, vo, hostname, - "Odd number of distinguished name entries."); + String errorMessage = + String.format( + MALFORMED_LSC_FILE_ERROR_TEMPLATE, + vo, + hostname, + "Odd number of distinguished name entries."); throw new VOMSError(errorMessage); } if (certificateChainDescription.size() == 0) { - String errorMessage = String.format(MALFORMED_LSC_FILE_ERROR_TEMPLATE, vo, hostname, - "No distinguished name entries found."); + String errorMessage = + String.format( + MALFORMED_LSC_FILE_ERROR_TEMPLATE, + vo, + hostname, + "No distinguished name entries found."); throw new VOMSError(errorMessage); } diff --git a/src/main/java/org/italiangrid/voms/store/impl/DefaultUpdatingVOMSTrustStore.java b/src/main/java/org/italiangrid/voms/store/impl/DefaultUpdatingVOMSTrustStore.java index c0ec63c..a848bb5 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/DefaultUpdatingVOMSTrustStore.java +++ b/src/main/java/org/italiangrid/voms/store/impl/DefaultUpdatingVOMSTrustStore.java @@ -8,53 +8,39 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.UpdatingVOMSTrustStore; import org.italiangrid.voms.store.VOMSTrustStoreStatusListener; import org.italiangrid.voms.util.NullListener; /** - * A VOMS trust store that periodically updates itself. The update frequency is - * set once at VOMS trust store creation time. - * - * - * @author Andrea Ceccanti + * A VOMS trust store that periodically updates itself. The update frequency is set once at VOMS + * trust store creation time. * + * @author Andrea Ceccanti */ public class DefaultUpdatingVOMSTrustStore extends DefaultVOMSTrustStore - implements UpdatingVOMSTrustStore { + implements UpdatingVOMSTrustStore { - /** - * Default trust store update frequency (10 minutes). - */ - public static final long DEFAULT_UPDATE_FREQUENCY = TimeUnit.MINUTES - .toMillis(10); + /** Default trust store update frequency (10 minutes). */ + public static final long DEFAULT_UPDATE_FREQUENCY = TimeUnit.MINUTES.toMillis(10); - /** - * This trust store update frequency in milliseconds. - */ + /** This trust store update frequency in milliseconds. */ private long updateFrequency; - /** - * The scheduler used to schedule the update tasks. - */ - private final ScheduledExecutorService scheduler = Executors - .newSingleThreadScheduledExecutor(new VOMSNamedThreadFactory()); + /** The scheduler used to schedule the update tasks. */ + private final ScheduledExecutorService scheduler = + Executors.newSingleThreadScheduledExecutor(new VOMSNamedThreadFactory()); /** * Builds a trust store configured as defined in the parameters. - * - * @param localTrustDirs - * where VOMS trust information will be looked for - * @param updateFrequency - * the update frequency in milliseconds - * @param listener - * a listener that is notified of interesting events related to this - * store + * + * @param localTrustDirs where VOMS trust information will be looked for + * @param updateFrequency the update frequency in milliseconds + * @param listener a listener that is notified of interesting events related to this store */ - public DefaultUpdatingVOMSTrustStore(List localTrustDirs, - long updateFrequency, VOMSTrustStoreStatusListener listener) { + public DefaultUpdatingVOMSTrustStore( + List localTrustDirs, long updateFrequency, VOMSTrustStoreStatusListener listener) { super(localTrustDirs, listener); updateFrequencySanityChecks(updateFrequency); @@ -64,10 +50,8 @@ public DefaultUpdatingVOMSTrustStore(List localTrustDirs, /** * Builds a trust store configured as defined in the parameters. - * - * @param updateFrequency - * the update frequency in milliseconds - * + * + * @param updateFrequency the update frequency in milliseconds */ public DefaultUpdatingVOMSTrustStore(long updateFrequency) { @@ -76,24 +60,19 @@ public DefaultUpdatingVOMSTrustStore(long updateFrequency) { /** * Builds a trust store configured as defined in the parameters. - * - * @param localTrustDirs - * where VOMS trust information will be looked for - * @param updateFrequency - * the update frequency in milliseconds - * + * + * @param localTrustDirs where VOMS trust information will be looked for + * @param updateFrequency the update frequency in milliseconds */ - public DefaultUpdatingVOMSTrustStore(List localTrustDirs, - long updateFrequency) { + public DefaultUpdatingVOMSTrustStore(List localTrustDirs, long updateFrequency) { this(localTrustDirs, updateFrequency, NullListener.INSTANCE); } /** * Builds a trust store configured as defined in the parameters. - * - * @param localTrustDirs - * where VOMS trust information will be looked for + * + * @param localTrustDirs where VOMS trust information will be looked for */ public DefaultUpdatingVOMSTrustStore(List localTrustDirs) { @@ -101,23 +80,20 @@ public DefaultUpdatingVOMSTrustStore(List localTrustDirs) { } /** - * Builds a trust store. VOMS information will be searched in the default VOMS - * dir location ({@link DefaultVOMSTrustStore#DEFAULT_VOMS_DIR}). - * - * This store will be refreshed according to the value of - * {@link #DEFAULT_UPDATE_FREQUENCY}. + * Builds a trust store. VOMS information will be searched in the default VOMS dir location + * ({@link DefaultVOMSTrustStore#DEFAULT_VOMS_DIR}). + * + *

This store will be refreshed according to the value of {@link #DEFAULT_UPDATE_FREQUENCY}. */ public DefaultUpdatingVOMSTrustStore() { - this(buildDefaultTrustedDirs(), DEFAULT_UPDATE_FREQUENCY, - NullListener.INSTANCE); + this(buildDefaultTrustedDirs(), DEFAULT_UPDATE_FREQUENCY, NullListener.INSTANCE); } protected void updateFrequencySanityChecks(long updateFrequency) { if (updateFrequency <= 0) - throw new VOMSError( - "Please provide a positive value for this store update frequency!"); + throw new VOMSError("Please provide a positive value for this store update frequency!"); } protected void scheduleUpdate() { @@ -127,25 +103,25 @@ protected void scheduleUpdate() { long frequency = getUpdateFrequency(); - scheduler.scheduleWithFixedDelay(new Runnable() { + scheduler.scheduleWithFixedDelay( + new Runnable() { - // Just run update on the VOMS trust store and log any error - public void run() { + // Just run update on the VOMS trust store and log any error + public void run() { - update(); - } - }, frequency, // First execution delay - frequency, // Next iterations delay - TimeUnit.MILLISECONDS); + update(); + } + }, + frequency, // First execution delay + frequency, // Next iterations delay + TimeUnit.MILLISECONDS); } finally { write.unlock(); } } - /** - * Returns the update frequency, in milliseconds, for this store. - */ + /** Returns the update frequency, in milliseconds, for this store. */ public long getUpdateFrequency() { read.lock(); @@ -156,17 +132,13 @@ public long getUpdateFrequency() { } } - /** - * Updates the information in this store - */ + /** Updates the information in this store */ public void update() { loadTrustInformation(); } - /** - * Cancel the background tasks which updates this store. - */ + /** Cancel the background tasks which updates this store. */ public void cancel() { write.lock(); @@ -176,5 +148,4 @@ public void cancel() { write.unlock(); } } - } diff --git a/src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java b/src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java index e91008b..f303967 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java +++ b/src/main/java/org/italiangrid/voms/store/impl/DefaultVOMSTrustStore.java @@ -4,6 +4,9 @@ package org.italiangrid.voms.store.impl; +import eu.emi.security.authn.x509.helpers.trust.OpensslTruststoreHelper; +import eu.emi.security.authn.x509.impl.CertificateUtils; +import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; @@ -20,82 +23,68 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; - import javax.security.auth.x500.X500Principal; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.LSCInfo; import org.italiangrid.voms.store.VOMSTrustStore; import org.italiangrid.voms.store.VOMSTrustStoreStatusListener; import org.italiangrid.voms.util.NullListener; -import eu.emi.security.authn.x509.helpers.trust.OpensslTruststoreHelper; -import eu.emi.security.authn.x509.impl.CertificateUtils; -import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; - /** - * * The default implementation for the VOMS trust store. This implementation does not refresh - * the trust information on a periodic basis. For an updating trust store see - * {@link DefaultUpdatingVOMSTrustStore}. - * + * the trust information on a periodic basis. For an updating trust store see {@link + * DefaultUpdatingVOMSTrustStore}. + * * @author Andrea Ceccanti - * */ public class DefaultVOMSTrustStore implements VOMSTrustStore { /** * The default directory where local VOMS trust information is rooted: {@value #DEFAULT_VOMS_DIR} - **/ + */ public static final String DEFAULT_VOMS_DIR = "/etc/grid-security/vomsdir"; - /** - * The filename suffix used to match certificates in the VOMS local trust directories - **/ + /** The filename suffix used to match certificates in the VOMS local trust directories */ public static final String CERTIFICATE_FILENAME_SUFFIX = ".pem"; - /** - * The filename suffix used to match LSC files in the VOMS local trust directories - **/ + /** The filename suffix used to match LSC files in the VOMS local trust directories */ public static final String LSC_FILENAME_SUFFIX = ".lsc"; /** * The list of local trusted directories that is searched for trust information (certs or LSC * files) - **/ + */ private final List localTrustedDirs; - /** Map of local parsed AA certificates keyed by certificate subject hash **/ + /** Map of local parsed AA certificates keyed by certificate subject hash * */ private Map localAACertificatesByHash = new HashMap(); - /** The set of local parsed LSC information keyed by VO **/ + /** The set of local parsed LSC information keyed by VO * */ private Map> localLSCInfo = new HashMap>(); - /** - * The trust store status listener that will be notified of changes in this trust store - **/ + /** The trust store status listener that will be notified of changes in this trust store */ private VOMSTrustStoreStatusListener listener; - /** The read/write lock that implements thread safety for this store **/ + /** The read/write lock that implements thread safety for this store * */ protected final ReadWriteLock rwLock = new ReentrantReadWriteLock(); - /** A reference to the read lock **/ + /** A reference to the read lock * */ protected final Lock read = rwLock.readLock(); - /** A reference to the write lock **/ + /** A reference to the write lock * */ protected final Lock write = rwLock.writeLock(); - /** A lock to guard the setting of the status listener **/ + /** A lock to guard the setting of the status listener * */ protected final Object listenerLock = new Object(); private final List voNames; /** * Builds a list of trusted directories containing only {@link #DEFAULT_VOMS_DIR}. - * + * * @return a list of default trusted directory containing the {@link #DEFAULT_VOMS_DIR} - **/ + */ protected static List buildDefaultTrustedDirs() { List tDirs = new ArrayList(); @@ -104,19 +93,17 @@ protected static List buildDefaultTrustedDirs() { } /** - * * @param localTrustDirs a non-null list of local trust directories * @param listener the {@link VOMSTrustStoreStatusListener} to use for this trust store * @throws IllegalArgumentException when the list passed as argument is null - * */ public DefaultVOMSTrustStore(List localTrustDirs, VOMSTrustStoreStatusListener listener) { this(localTrustDirs, null, listener); } - public DefaultVOMSTrustStore(List localTrustDirs, List voNames, - VOMSTrustStoreStatusListener listener) { + public DefaultVOMSTrustStore( + List localTrustDirs, List voNames, VOMSTrustStoreStatusListener listener) { if (localTrustDirs == null) { throw new IllegalArgumentException( @@ -141,10 +128,8 @@ public DefaultVOMSTrustStore(List localTrustDirs) { /** * Default constructor. - * - * Sets the local trusted directories to the default of {@value #DEFAULT_VOMS_DIR}. - * - * + * + *

Sets the local trusted directories to the default of {@value #DEFAULT_VOMS_DIR}. */ public DefaultVOMSTrustStore() { @@ -166,8 +151,8 @@ public List getLocalAACertificates() { read.lock(); try { - return Collections - .unmodifiableList(new ArrayList(localAACertificatesByHash.values())); + return Collections.unmodifiableList( + new ArrayList(localAACertificatesByHash.values())); } finally { read.unlock(); } @@ -181,14 +166,11 @@ public LSCInfo getLSC(String voName, String hostname) { Set candidates = localLSCInfo.get(voName); - if (candidates == null) - return null; + if (candidates == null) return null; for (LSCInfo lsc : candidates) { - if (lsc.getHostname().equals(hostname)) - return lsc; - + if (lsc.getHostname().equals(hostname)) return lsc; } return null; @@ -201,7 +183,7 @@ public LSCInfo getLSC(String voName, String hostname) { /** * Loads all the certificates in the local directory. Only files with the extension matching the * {@link #CERTIFICATE_FILENAME_PATTERN} are considered. - * + * * @param directory */ private void loadCertificatesFromDirectory(File directory) { @@ -212,23 +194,23 @@ private void loadCertificatesFromDirectory(File directory) { listener.notifyCertficateLookupEvent(directory.getAbsolutePath()); } - File[] certFiles = directory.listFiles(new FilenameFilter() { + File[] certFiles = + directory.listFiles( + new FilenameFilter() { - public boolean accept(File dir, String name) { - - return name.endsWith(CERTIFICATE_FILENAME_SUFFIX); - } - }); + public boolean accept(File dir, String name) { - for (File f : certFiles) - loadCertificateFromFile(f); + return name.endsWith(CERTIFICATE_FILENAME_SUFFIX); + } + }); + for (File f : certFiles) loadCertificateFromFile(f); } /** * Loads a VOMS AA certificate from a given file and stores this certificate in the local map of * trusted VOMS AA certificate. - * + * * @param file */ private void loadCertificateFromFile(File file) { @@ -253,15 +235,14 @@ private void loadCertificateFromFile(File file) { } catch (IOException e) { String errorMessage = - String.format("Error parsing VOMS trusted certificate from %s. Reason: %s", + String.format( + "Error parsing VOMS trusted certificate from %s. Reason: %s", file.getAbsolutePath(), e.getMessage()); throw new VOMSError(errorMessage, e); } - } /** - * * @param directory */ private void loadLSCFromDirectory(File directory) { @@ -272,16 +253,17 @@ private void loadLSCFromDirectory(File directory) { listener.notifyLSCLookupEvent(directory.getAbsolutePath()); } - File[] lscFiles = directory.listFiles(new FilenameFilter() { + File[] lscFiles = + directory.listFiles( + new FilenameFilter() { - public boolean accept(File dir, String name) { + public boolean accept(File dir, String name) { - return name.endsWith(LSC_FILENAME_SUFFIX); - } - }); + return name.endsWith(LSC_FILENAME_SUFFIX); + } + }); - if (lscFiles.length == 0) - return; + if (lscFiles.length == 0) return; DefaultLSCFileParser lscParser = new DefaultLSCFileParser(); @@ -313,14 +295,12 @@ public boolean accept(File dir, String name) { localLscForVo.add(info); listener.notifyLSCLoadEvent(info, lsc); - } - } /** * Performs basic sanity checks performed on a file supposed to hold a VOMS AA certificate. - * + * * @param certFile */ private void certificateFileSanityChecks(File certFile) { @@ -332,13 +312,12 @@ private void certificateFileSanityChecks(File certFile) { if (!certFile.canRead()) throw new VOMSError( "Local VOMS trusted certificate is not readable:" + certFile.getAbsolutePath()); - } /** * Performs basic sanity checks on a directory that is supposed to contain VOMS AA certificates * and LSC files. - * + * * @param directory */ private void directorySanityChecks(File directory) { @@ -356,14 +335,12 @@ private void directorySanityChecks(File directory) { if (!directory.canExecute()) throw new VOMSError( "Local trust directory is not traversable:" + directory.getAbsolutePath()); - } private void cleanupStores() { localAACertificatesByHash.clear(); localLSCInfo.clear(); - } public void loadTrustInformation() { @@ -389,13 +366,15 @@ public void loadTrustInformation() { // Load LSC and certificates files starting from each of the // sub-directory of the starting trust info directory - File[] voDirs = baseTrustDir.listFiles(new FileFilter() { + File[] voDirs = + baseTrustDir.listFiles( + new FileFilter() { - public boolean accept(File pathname) { + public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + return pathname.isDirectory(); + } + }); for (File voDir : voDirs) { @@ -414,7 +393,6 @@ public boolean accept(File pathname) { private String getOpensslCAHash(X500Principal principal) { return OpensslTruststoreHelper.getOpenSSLCAHash(principal, false); - } public X509Certificate getAACertificateBySubject(X500Principal aaCertSubject) { diff --git a/src/main/java/org/italiangrid/voms/store/impl/LSCFile.java b/src/main/java/org/italiangrid/voms/store/impl/LSCFile.java index c347cb7..02e0973 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/LSCFile.java +++ b/src/main/java/org/italiangrid/voms/store/impl/LSCFile.java @@ -4,29 +4,24 @@ package org.italiangrid.voms.store.impl; +import eu.emi.security.authn.x509.impl.OpensslNameUtils; +import eu.emi.security.authn.x509.impl.X500NameUtils; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; - import javax.security.auth.x500.X500Principal; - import org.italiangrid.voms.store.LSCInfo; -import eu.emi.security.authn.x509.impl.OpensslNameUtils; -import eu.emi.security.authn.x509.impl.X500NameUtils; - /** * Represents a VOMS LSC (Legacy Secure Channel) file. - * - *

The LSC file describes the certificate chain that a VOMS attribute authority - * uses to sign a VOMS attribute certificate. The LSC mechanism helps in solving - * the public key distribution problem for VOMS AA certificates and is used in - * the VOMS validation process to validate the signature on the AC. It does this by - * extracting the VOMS AA certificate included in the VOMS extension and ensuring - * that the chain conforms to the description in the LSC file.

- * - *

Two {@link LSCFile} objects are considered equal if their VO and hostname fields match.

- * + * + *

The LSC file describes the certificate chain that a VOMS attribute authority uses to sign a + * VOMS attribute certificate. The LSC mechanism helps in solving the public key distribution + * problem for VOMS AA certificates and is used in the VOMS validation process to validate the + * signature on the AC. It does this by extracting the VOMS AA certificate included in the VOMS + * extension and ensuring that the chain conforms to the description in the LSC file. + * + *

Two {@link LSCFile} objects are considered equal if their VO and hostname fields match. */ public class LSCFile implements LSCInfo { @@ -146,23 +141,16 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; LSCFile other = (LSCFile) obj; if (hostname == null) { - if (other.hostname != null) - return false; - } else if (!hostname.equals(other.hostname)) - return false; + if (other.hostname != null) return false; + } else if (!hostname.equals(other.hostname)) return false; if (vo == null) { - if (other.vo != null) - return false; - } else if (!vo.equals(other.vo)) - return false; + if (other.vo != null) return false; + } else if (!vo.equals(other.vo)) return false; return true; } @@ -174,8 +162,15 @@ public boolean equals(Object obj) { @Override public String toString() { - return "LSCFile [filename=" + filename + ", vo=" + vo + ", hostname=" - + hostname + ", certChainDescription=" + certChainDescription + "]"; + return "LSCFile [filename=" + + filename + + ", vo=" + + vo + + ", hostname=" + + hostname + + ", certChainDescription=" + + certChainDescription + + "]"; } /** @@ -218,6 +213,7 @@ public boolean matches(X509Certificate[] certChain) { */ @SuppressWarnings("deprecation") private boolean matches(X500Principal certDn, String lscDn) { + return X500NameUtils.equal(certDn, OpensslNameUtils.opensslToRfc2253(lscDn)); } } diff --git a/src/main/java/org/italiangrid/voms/store/impl/VOMSNamedThreadFactory.java b/src/main/java/org/italiangrid/voms/store/impl/VOMSNamedThreadFactory.java index 1af0f26..49bcf29 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/VOMSNamedThreadFactory.java +++ b/src/main/java/org/italiangrid/voms/store/impl/VOMSNamedThreadFactory.java @@ -10,9 +10,8 @@ /** * A simple thread factory to create named VOMS background threads. - * - * @author Andrea Ceccanti * + * @author Andrea Ceccanti */ public class VOMSNamedThreadFactory implements ThreadFactory { @@ -26,13 +25,10 @@ public VOMSNamedThreadFactory(UncaughtExceptionHandler h) { this.handler = h; } - public VOMSNamedThreadFactory() { - - } + public VOMSNamedThreadFactory() {} public Thread newThread(Runnable r) { - return new VOMSThread(r, poolBaseName + "-" + created.incrementAndGet(), - handler); + return new VOMSThread(r, poolBaseName + "-" + created.incrementAndGet(), handler); } } diff --git a/src/main/java/org/italiangrid/voms/store/impl/VOMSThread.java b/src/main/java/org/italiangrid/voms/store/impl/VOMSThread.java index fcc5604..238f150 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/VOMSThread.java +++ b/src/main/java/org/italiangrid/voms/store/impl/VOMSThread.java @@ -5,28 +5,21 @@ package org.italiangrid.voms.store.impl; /** - * An helper class to create a named VOMS thread. This class just sets the name - * for the thread and set an {@link java.lang.Thread.UncaughtExceptionHandler} - * which logs the caught exception. - * - * @author Andrea Ceccanti + * An helper class to create a named VOMS thread. This class just sets the name for the thread and + * set an {@link java.lang.Thread.UncaughtExceptionHandler} which logs the caught exception. * + * @author Andrea Ceccanti */ public class VOMSThread extends Thread { /** * Default constructor. - * - * @param target - * the object whose run method is called. - * @param name - * the name of the new thread. - * @param handler - * the {@link java.lang.Thread.UncaughtExceptionHandler} - * used for this thread + * + * @param target the object whose run method is called. + * @param name the name of the new thread. + * @param handler the {@link java.lang.Thread.UncaughtExceptionHandler} used for this thread */ - public VOMSThread(Runnable target, String name, - UncaughtExceptionHandler handler) { + public VOMSThread(Runnable target, String name, UncaughtExceptionHandler handler) { super(target, name); setUncaughtExceptionHandler(handler); diff --git a/src/main/java/org/italiangrid/voms/store/impl/package-info.java b/src/main/java/org/italiangrid/voms/store/impl/package-info.java index 10ca200..1081c66 100644 --- a/src/main/java/org/italiangrid/voms/store/impl/package-info.java +++ b/src/main/java/org/italiangrid/voms/store/impl/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the implementation of VOMS trust store management. - */ +/** This package provides the implementation of VOMS trust store management. */ package org.italiangrid.voms.store.impl; - diff --git a/src/main/java/org/italiangrid/voms/store/package-info.java b/src/main/java/org/italiangrid/voms/store/package-info.java index 61c1526..4097ff6 100644 --- a/src/main/java/org/italiangrid/voms/store/package-info.java +++ b/src/main/java/org/italiangrid/voms/store/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides the API for managing VOMS trust stores. - */ +/** This package provides the API for managing VOMS trust stores. */ package org.italiangrid.voms.store; - diff --git a/src/main/java/org/italiangrid/voms/util/CachingCertificateValidator.java b/src/main/java/org/italiangrid/voms/util/CachingCertificateValidator.java index 3f05e4d..1533eaa 100644 --- a/src/main/java/org/italiangrid/voms/util/CachingCertificateValidator.java +++ b/src/main/java/org/italiangrid/voms/util/CachingCertificateValidator.java @@ -4,13 +4,6 @@ package org.italiangrid.voms.util; -import java.security.cert.CertPath; -import java.security.cert.X509Certificate; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.italiangrid.voms.VOMSError; - import eu.emi.security.authn.x509.ProxySupport; import eu.emi.security.authn.x509.RevocationParameters; import eu.emi.security.authn.x509.StoreUpdateListener; @@ -19,43 +12,36 @@ import eu.emi.security.authn.x509.X509CertChainValidatorExt; import eu.emi.security.authn.x509.impl.CertificateUtils; import eu.emi.security.authn.x509.impl.FormatMode; +import java.security.cert.CertPath; +import java.security.cert.X509Certificate; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import org.italiangrid.voms.VOMSError; /** - * A Certificate validator that caches validation results for a configurable - * period of time. The cache is keyed by the fingerprint of the certificate at - * the top of the chain (likely the EEC). - * + * A Certificate validator that caches validation results for a configurable period of time. The + * cache is keyed by the fingerprint of the certificate at the top of the chain (likely the EEC). * * @author andreaceccanti - * */ public class CachingCertificateValidator implements X509CertChainValidatorExt { - /** - * Simple concurrent cache for validation results - */ + /** Simple concurrent cache for validation results */ protected final ConcurrentMap validationResultsCache; - /** - * The wrapped CANL certificate validator - */ + /** The wrapped CANL certificate validator */ protected final X509CertChainValidatorExt validator; - /** - * The cache entry lifetime for this validator - */ + /** The cache entry lifetime for this validator */ protected final long cacheEntryLifetimeMsec; /** * Builds a caching validator wrapping the validator passed as argument. * - * @param val - * The CANL validator to be wrapped. - * @param maxCacheEntryLifetime - * the maximum cache entry lifetime (in msecs) + * @param val The CANL validator to be wrapped. + * @param maxCacheEntryLifetime the maximum cache entry lifetime (in msecs) */ - public CachingCertificateValidator(X509CertChainValidatorExt val, - long maxCacheEntryLifetime) { + public CachingCertificateValidator(X509CertChainValidatorExt val, long maxCacheEntryLifetime) { cacheEntryLifetimeMsec = maxCacheEntryLifetime; validator = val; @@ -63,18 +49,15 @@ public CachingCertificateValidator(X509CertChainValidatorExt val, } /** - * Checks whether the {@link CachedValidationResult} passed as argument has - * expired with respect to the {@link #cacheEntryLifetimeMsec} defined for - * this validator and the reference time passed as argument. + * Checks whether the {@link CachedValidationResult} passed as argument has expired with respect + * to the {@link #cacheEntryLifetimeMsec} defined for this validator and the reference time passed + * as argument. * - * @param cvr - * a {@link CachedValidationResult} object - * @param referenceTime - * the reference time (msecs since the epoch) + * @param cvr a {@link CachedValidationResult} object + * @param referenceTime the reference time (msecs since the epoch) * @return true when expired, false otherwise */ - public boolean cachedValidationResultHasExpired(CachedValidationResult cvr, - long referenceTime) { + public boolean cachedValidationResultHasExpired(CachedValidationResult cvr, long referenceTime) { return (referenceTime - cvr.getTimestamp() > cacheEntryLifetimeMsec); } @@ -82,17 +65,14 @@ public boolean cachedValidationResultHasExpired(CachedValidationResult cvr, /** * Gets a validation result from the memory cache * - * @param certFingerprint - * the certificate fingerprint for the certificate at the top of the - * chain + * @param certFingerprint the certificate fingerprint for the certificate at the top of the chain * @return the validation result, if found. null otherwise. */ protected ValidationResult getCachedResult(String certFingerprint) { CachedValidationResult cvr = validationResultsCache.get(certFingerprint); - if (cvr == null) - return null; + if (cvr == null) return null; if (!cachedValidationResultHasExpired(cvr, System.currentTimeMillis())) { return cvr.getResult(); @@ -105,27 +85,24 @@ protected ValidationResult getCachedResult(String certFingerprint) { /** * Obvious sanity checks on input certificate chain * - * @param certChain - * the chain to be checked + * @param certChain the chain to be checked */ private void certChainSanityChecks(X509Certificate[] certChain) { - if (certChain == null) - throw new IllegalArgumentException("Cannot validate a null cert chain."); + if (certChain == null) throw new IllegalArgumentException("Cannot validate a null cert chain."); if (certChain.length == 0) - throw new IllegalArgumentException( - "Cannot validate a cert chain of length 0."); + throw new IllegalArgumentException("Cannot validate a cert chain of length 0."); } /** - * Validates a certificate chain using the wrapped validator, caching the - * result for future validation calls. + * Validates a certificate chain using the wrapped validator, caching the result for future + * validation calls. * - * @param certChain - * the certificate chain that will be validated + * @param certChain the certificate chain that will be validated * @return a possibly cached {@link ValidationResult} - * @see eu.emi.security.authn.x509.X509CertChainValidator#validate(java.security.cert.X509Certificate[]) + * @see + * eu.emi.security.authn.x509.X509CertChainValidator#validate(java.security.cert.X509Certificate[]) */ public ValidationResult validate(X509Certificate[] certChain) { @@ -134,30 +111,27 @@ public ValidationResult validate(X509Certificate[] certChain) { String certFingerprint = null; try { - certFingerprint = FingerprintHelper - .getFingerprint(certChain[certChain.length - 1]); + certFingerprint = FingerprintHelper.getFingerprint(certChain[certChain.length - 1]); } catch (Throwable t) { - String errorMsg = String.format("Error computing fingerprint for " - + "certificate: %s. Cause: %s", - CertificateUtils.format(certChain[0], FormatMode.COMPACT_ONE_LINE), - t.getMessage()); + String errorMsg = + String.format( + "Error computing fingerprint for " + "certificate: %s. Cause: %s", + CertificateUtils.format(certChain[0], FormatMode.COMPACT_ONE_LINE), t.getMessage()); throw new VOMSError(errorMsg, t); - } ValidationResult res = getCachedResult(certFingerprint); if (res == null) { res = validator.validate(certChain); - validationResultsCache.putIfAbsent(certFingerprint, - new CachedValidationResult(certFingerprint, res)); + validationResultsCache.putIfAbsent( + certFingerprint, new CachedValidationResult(certFingerprint, res)); } return res; - } /** @@ -178,8 +152,7 @@ public ProxySupport getProxySupport() { } /** - * @param certPath - * the certificate path that will be validated + * @param certPath the certificate path that will be validated * @return the {@link ValidationResult} * @see eu.emi.security.authn.x509.X509CertChainValidator#validate(java.security.cert.CertPath) */ @@ -207,10 +180,9 @@ public X509Certificate[] getTrustedIssuers() { } /** - * @param listener - * the {@link ValidationErrorListener} to be added to this validator - * - * @see eu.emi.security.authn.x509.X509CertChainValidator#addValidationListener(eu.emi.security.authn.x509.ValidationErrorListener) + * @param listener the {@link ValidationErrorListener} to be added to this validator + * @see + * eu.emi.security.authn.x509.X509CertChainValidator#addValidationListener(eu.emi.security.authn.x509.ValidationErrorListener) */ public void addValidationListener(ValidationErrorListener listener) { @@ -218,10 +190,9 @@ public void addValidationListener(ValidationErrorListener listener) { } /** - * @param listener - * the {@link ValidationErrorListener} that must be removed from - * this validator - * @see eu.emi.security.authn.x509.X509CertChainValidator#removeValidationListener(eu.emi.security.authn.x509.ValidationErrorListener) + * @param listener the {@link ValidationErrorListener} that must be removed from this validator + * @see + * eu.emi.security.authn.x509.X509CertChainValidator#removeValidationListener(eu.emi.security.authn.x509.ValidationErrorListener) */ public void removeValidationListener(ValidationErrorListener listener) { @@ -229,11 +200,9 @@ public void removeValidationListener(ValidationErrorListener listener) { } /** - * @param listener - * the {@link StoreUpdateListener} that must be added to this - * validator - * - * @see eu.emi.security.authn.x509.X509CertChainValidator#addUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener) + * @param listener the {@link StoreUpdateListener} that must be added to this validator + * @see + * eu.emi.security.authn.x509.X509CertChainValidator#addUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener) */ public void addUpdateListener(StoreUpdateListener listener) { @@ -241,50 +210,43 @@ public void addUpdateListener(StoreUpdateListener listener) { } /** - * @param listener - * the {@link StoreUpdateListener} that must be removed from this - * validator - * - * @see eu.emi.security.authn.x509.X509CertChainValidator#removeUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener) + * @param listener the {@link StoreUpdateListener} that must be removed from this validator + * @see + * eu.emi.security.authn.x509.X509CertChainValidator#removeUpdateListener(eu.emi.security.authn.x509.StoreUpdateListener) */ public void removeUpdateListener(StoreUpdateListener listener) { validator.removeUpdateListener(listener); } - } /** * A validation result cache entry. * * @author cecco - * */ class CachedValidationResult { /** * Default constructor. * - * @param certificateFingerprint - * the certificate fingerprint for this entry - * @param res - * the validation result + * @param certificateFingerprint the certificate fingerprint for this entry + * @param res the validation result */ - public CachedValidationResult(String certificateFingerprint, - ValidationResult res) { + public CachedValidationResult(String certificateFingerprint, ValidationResult res) { certFingerprint = certificateFingerprint; result = res; timestamp = System.currentTimeMillis(); } - /** The certificate fingerprint for this cache entry **/ + /** The certificate fingerprint for this cache entry * */ private String certFingerprint; - /** The validation result for this cache entry **/ + /** The validation result for this cache entry * */ private ValidationResult result; - /** The cache entry creation timestamp **/ + /** The cache entry creation timestamp * */ private long timestamp; /** @@ -300,8 +262,7 @@ public ValidationResult getResult() { /** * Sets the validation result for this entry * - * @param result - * a {@link ValidationResult} + * @param result a {@link ValidationResult} */ public void setResult(ValidationResult result) { @@ -321,8 +282,7 @@ public long getTimestamp() { /** * Sets this entry creation timestamp (in milliseconds since the epoch). * - * @param timestamp - * the timestamp + * @param timestamp the timestamp */ public void setTimestamp(long timestamp) { @@ -332,10 +292,7 @@ public void setTimestamp(long timestamp) { /** * Returns the certificate fingerprint for this entry. * - * The certificate fingerprint is the SHA1 hash of the DER encoding of the - * certificate. - * - * + *

The certificate fingerprint is the SHA1 hash of the DER encoding of the certificate. * * @return the fingerprint for this entry * @see FingerprintHelper @@ -346,15 +303,13 @@ public String getCertFingerprint() { } /** + * Sets the certificate finger for this entry. The certificate fingerprint is the SHA1 hash of the + * DER encoding of the certificate. * - * Sets the certificate finger for this entry. The certificate fingerprint is - * the SHA1 hash of the DER encoding of the certificate. - * - * It can be computed with the - * {@link FingerprintHelper#getFingerprint(X509Certificate)} method. + *

It can be computed with the {@link FingerprintHelper#getFingerprint(X509Certificate)} + * method. * - * @param certFingerprint - * a certificate fingerprint describing a certificate + * @param certFingerprint a certificate fingerprint describing a certificate */ public void setCertFingerprint(String certFingerprint) { @@ -366,26 +321,20 @@ public int hashCode() { final int prime = 31; int result = 1; - result = prime * result - + ((certFingerprint == null) ? 0 : certFingerprint.hashCode()); + result = prime * result + ((certFingerprint == null) ? 0 : certFingerprint.hashCode()); return result; } @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; CachedValidationResult other = (CachedValidationResult) obj; if (certFingerprint == null) { - if (other.certFingerprint != null) - return false; - } else if (!certFingerprint.equals(other.certFingerprint)) - return false; + if (other.certFingerprint != null) return false; + } else if (!certFingerprint.equals(other.certFingerprint)) return false; return true; } } diff --git a/src/main/java/org/italiangrid/voms/util/CertificateValidatorBuilder.java b/src/main/java/org/italiangrid/voms/util/CertificateValidatorBuilder.java index 5559d6e..c55bfe0 100644 --- a/src/main/java/org/italiangrid/voms/util/CertificateValidatorBuilder.java +++ b/src/main/java/org/italiangrid/voms/util/CertificateValidatorBuilder.java @@ -4,10 +4,6 @@ package org.italiangrid.voms.util; -import java.util.Arrays; - -import org.italiangrid.voms.ac.impl.DefaultVOMSValidator; - import eu.emi.security.authn.x509.CrlCheckingMode; import eu.emi.security.authn.x509.NamespaceCheckingMode; import eu.emi.security.authn.x509.OCSPCheckingMode; @@ -20,20 +16,20 @@ import eu.emi.security.authn.x509.impl.OpensslCertChainValidator; import eu.emi.security.authn.x509.impl.RevocationParametersExt; import eu.emi.security.authn.x509.impl.ValidatorParamsExt; +import java.util.Arrays; +import org.italiangrid.voms.ac.impl.DefaultVOMSValidator; /** - * A utility class which provides convenient methods to build a certificate - * validator with defaults that are meaningful for VOMS usage. - * + * A utility class which provides convenient methods to build a certificate validator with defaults + * that are meaningful for VOMS usage. + * * @author cecco - * */ public class CertificateValidatorBuilder { /** - * This enum determine which hash function is configured for the canl - * {@link OpensslCertChainValidator} to resolve CRLs and other trust anchors - * files. + * This enum determine which hash function is configured for the canl {@link + * OpensslCertChainValidator} to resolve CRLs and other trust anchors files. */ public static enum OpensslHashFunction { MD5, @@ -41,39 +37,28 @@ public static enum OpensslHashFunction { }; /** - * The default Openssl hash function value. MD5 is chosen to ensure - * compatibility with Openssl pre 1.0 deployments. + * The default Openssl hash function value. MD5 is chosen to ensure compatibility with Openssl pre + * 1.0 deployments. */ public static final OpensslHashFunction DEFAULT_OPENSSL_HASH_FUNCTION = OpensslHashFunction.MD5; - /** - * The default CRL checking policy. - */ + /** The default CRL checking policy. */ public static final CrlCheckingMode DEFAULT_CRL_CHECKS = CrlCheckingMode.IF_VALID; - /** - * The default OCSP checking policy. - */ + /** The default OCSP checking policy. */ public static final OCSPCheckingMode DEFAULT_OCSP_CHECKS = OCSPCheckingMode.IGNORE; - /** - * The default namespace checking policy. - */ - public static final NamespaceCheckingMode DEFAULT_NS_CHECKS = NamespaceCheckingMode.GLOBUS_EUGRIDPMA; + /** The default namespace checking policy. */ + public static final NamespaceCheckingMode DEFAULT_NS_CHECKS = + NamespaceCheckingMode.GLOBUS_EUGRIDPMA; - /** - * The default trust anchors directory. - */ + /** The default trust anchors directory. */ public static final String DEFAULT_TRUST_ANCHORS_DIR = "/etc/grid-security/certificates"; - /** - * By default this builder builds non-lazy validators - */ + /** By default this builder builds non-lazy validators */ public static final Boolean DEFAULT_VALIDATOR_IS_LAZY = Boolean.FALSE; - /** - * Default validator trust anchor update interval. - */ + /** Default validator trust anchor update interval. */ public static final long DEFAULT_TRUST_ANCHORS_UPDATE_INTERVAL = 0L; private String trustAnchorsDir = DEFAULT_TRUST_ANCHORS_DIR; @@ -88,20 +73,15 @@ public static enum OpensslHashFunction { private OCSPCheckingMode ocspChecks = DEFAULT_OCSP_CHECKS; private OpensslHashFunction opensslHashFunction = DEFAULT_OPENSSL_HASH_FUNCTION; - public CertificateValidatorBuilder() { - - } + public CertificateValidatorBuilder() {} /** * Sets the openssl hash function for this builder - * - * @param f - * the {@link OpensslHashFunction} - * + * + * @param f the {@link OpensslHashFunction} * @return the builder object */ - public CertificateValidatorBuilder opensslHashFunction( - OpensslHashFunction f) { + public CertificateValidatorBuilder opensslHashFunction(OpensslHashFunction f) { opensslHashFunction = f; return this; @@ -109,13 +89,11 @@ public CertificateValidatorBuilder opensslHashFunction( /** * Sets the store update listener for this builder - * - * @param l - * the {@link StoreUpdateListener} + * + * @param l the {@link StoreUpdateListener} * @return the builder object */ - public CertificateValidatorBuilder storeUpdateListener( - StoreUpdateListener l) { + public CertificateValidatorBuilder storeUpdateListener(StoreUpdateListener l) { storeUpdateListener = l; return this; @@ -123,9 +101,8 @@ public CertificateValidatorBuilder storeUpdateListener( /** * Sets the trust anchors dir for this builder - * - * @param dir - * the trust anchors directory + * + * @param dir the trust anchors directory * @return the builder object */ public CertificateValidatorBuilder trustAnchorsDir(String dir) { @@ -136,13 +113,11 @@ public CertificateValidatorBuilder trustAnchorsDir(String dir) { /** * Sets the validation error listener for this builder - * - * @param l - * the {@link ValidationErrorListener} + * + * @param l the {@link ValidationErrorListener} * @return the builder object */ - public CertificateValidatorBuilder validationErrorListener( - ValidationErrorListener l) { + public CertificateValidatorBuilder validationErrorListener(ValidationErrorListener l) { validationErrorListener = l; return this; @@ -150,9 +125,8 @@ public CertificateValidatorBuilder validationErrorListener( /** * Sets the trust anchors update interval for this builder - * - * @param interval - * the update interval + * + * @param interval the update interval * @return the builder object */ public CertificateValidatorBuilder trustAnchorsUpdateInterval(long interval) { @@ -163,11 +137,9 @@ public CertificateValidatorBuilder trustAnchorsUpdateInterval(long interval) { /** * Sets whether the created validator will be lazy in loading anchors - * - * @param lazyness - * the boolean flag that determines if the validator will be lazy in - * loading trust anchors - * + * + * @param lazyness the boolean flag that determines if the validator will be lazy in loading trust + * anchors * @return the builder object */ public CertificateValidatorBuilder lazyAnchorsLoading(boolean lazyness) { @@ -178,13 +150,11 @@ public CertificateValidatorBuilder lazyAnchorsLoading(boolean lazyness) { /** * Sets the namespace checking mode for this builder - * - * @param nsChecks - * the {@link NamespaceCheckingMode} + * + * @param nsChecks the {@link NamespaceCheckingMode} * @return the builder object */ - public CertificateValidatorBuilder namespaceChecks( - NamespaceCheckingMode nsChecks) { + public CertificateValidatorBuilder namespaceChecks(NamespaceCheckingMode nsChecks) { namespaceChecks = nsChecks; return this; @@ -192,9 +162,8 @@ public CertificateValidatorBuilder namespaceChecks( /** * Sets the crl checking mode for this builder - * - * @param crl - * the {@link CrlCheckingMode} + * + * @param crl the {@link CrlCheckingMode} * @return the builder object */ public CertificateValidatorBuilder crlChecks(CrlCheckingMode crl) { @@ -205,9 +174,8 @@ public CertificateValidatorBuilder crlChecks(CrlCheckingMode crl) { /** * Sets the ocsp checking mode for this builder - * - * @param ocsp - * the {@link OCSPCheckingMode} + * + * @param ocsp the {@link OCSPCheckingMode} * @return the builder object */ public CertificateValidatorBuilder ocspChecks(OCSPCheckingMode ocsp) { @@ -217,329 +185,318 @@ public CertificateValidatorBuilder ocspChecks(OCSPCheckingMode ocsp) { } /** - * Builds an {@link OpensslCertChainValidator} according to the parameters set - * for this builder - * + * Builds an {@link OpensslCertChainValidator} according to the parameters set for this builder + * * @return the {@link X509CertChainValidatorExt} */ public X509CertChainValidatorExt build() { - RevocationParametersExt revocationParameters = new RevocationParametersExt( - crlChecks, new CRLParameters(), new OCSPParametes(ocspChecks)); + RevocationParametersExt revocationParameters = + new RevocationParametersExt(crlChecks, new CRLParameters(), new OCSPParametes(ocspChecks)); - ValidatorParamsExt validationParams = new ValidatorParamsExt( - revocationParameters, ProxySupport.ALLOW); + ValidatorParamsExt validationParams = + new ValidatorParamsExt(revocationParameters, ProxySupport.ALLOW); - if (storeUpdateListener != null){ + if (storeUpdateListener != null) { validationParams.setInitialListeners(Arrays.asList(storeUpdateListener)); } - + boolean openssl1xMode = false; - - if (opensslHashFunction == OpensslHashFunction.SHA1){ + + if (opensslHashFunction == OpensslHashFunction.SHA1) { openssl1xMode = true; } - - OpensslCertChainValidator validator = new OpensslCertChainValidator( - trustAnchorsDir, openssl1xMode, namespaceChecks, trustAnchorsUpdateInterval, - validationParams, lazyAnchorsLoading); - if (validationErrorListener != null){ + OpensslCertChainValidator validator = + new OpensslCertChainValidator( + trustAnchorsDir, + openssl1xMode, + namespaceChecks, + trustAnchorsUpdateInterval, + validationParams, + lazyAnchorsLoading); + + if (validationErrorListener != null) { validator.addValidationListener(validationErrorListener); } - + return validator; } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param storeUpdateListener - * the listener that will receive notifications about trust store - * update events - * @param updateInterval - * the trust anchor store update interval - * @param namespaceChecks - * the namespace checking policy - * @param crlChecks - * the crl checking policy - * @param ocspChecks - * the ocsp checking policy - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param storeUpdateListener the listener that will receive notifications about trust store + * update events + * @param updateInterval the trust anchor store update interval + * @param namespaceChecks the namespace checking policy + * @param crlChecks the crl checking policy + * @param ocspChecks the ocsp checking policy + * @return an Openssl-style certificate validator configured as specified in the parameters */ public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - StoreUpdateListener storeUpdateListener, long updateInterval, - NamespaceCheckingMode namespaceChecks, CrlCheckingMode crlChecks, - OCSPCheckingMode ocspChecks) { - - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - storeUpdateListener, updateInterval, namespaceChecks, crlChecks, - ocspChecks, true); + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + StoreUpdateListener storeUpdateListener, + long updateInterval, + NamespaceCheckingMode namespaceChecks, + CrlCheckingMode crlChecks, + OCSPCheckingMode ocspChecks) { + + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + storeUpdateListener, + updateInterval, + namespaceChecks, + crlChecks, + ocspChecks, + true); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param storeUpdateListener - * the listener that will receive notifications about trust store - * update events - * @param updateInterval - * the trust anchor store update interval - * @param namespaceChecks - * the namespace checking policy - * @param crlChecks - * the crl checking policy - * @param ocspChecks - * the ocsp checking policy - * @param lazy - * whether the validator should be lazy in loading crls and - * certificates - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param storeUpdateListener the listener that will receive notifications about trust store + * update events + * @param updateInterval the trust anchor store update interval + * @param namespaceChecks the namespace checking policy + * @param crlChecks the crl checking policy + * @param ocspChecks the ocsp checking policy + * @param lazy whether the validator should be lazy in loading crls and certificates + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - StoreUpdateListener storeUpdateListener, long updateInterval, - NamespaceCheckingMode namespaceChecks, CrlCheckingMode crlChecks, - OCSPCheckingMode ocspChecks, boolean lazy) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + StoreUpdateListener storeUpdateListener, + long updateInterval, + NamespaceCheckingMode namespaceChecks, + CrlCheckingMode crlChecks, + OCSPCheckingMode ocspChecks, + boolean lazy) { CertificateValidatorBuilder builder = new CertificateValidatorBuilder(); - return builder.trustAnchorsDir(trustAnchorsDir) - .validationErrorListener(validationErrorListener) - .storeUpdateListener(storeUpdateListener) - .trustAnchorsUpdateInterval(updateInterval) - .namespaceChecks(namespaceChecks).crlChecks(crlChecks) - .ocspChecks(ocspChecks).lazyAnchorsLoading(lazy).build(); + return builder + .trustAnchorsDir(trustAnchorsDir) + .validationErrorListener(validationErrorListener) + .storeUpdateListener(storeUpdateListener) + .trustAnchorsUpdateInterval(updateInterval) + .namespaceChecks(namespaceChecks) + .crlChecks(crlChecks) + .ocspChecks(ocspChecks) + .lazyAnchorsLoading(lazy) + .build(); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener) { + String trustAnchorsDir, ValidationErrorListener validationErrorListener) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - null, 0L, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, DEFAULT_OCSP_CHECKS); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + null, + 0L, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param storeListener - * the listener that will be informed of trust store load errors - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param storeListener the listener that will be informed of trust store load errors + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - StoreUpdateListener storeListener) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + StoreUpdateListener storeListener) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - storeListener, 0L, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, - DEFAULT_OCSP_CHECKS); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + storeListener, + 0L, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param storeListener - * the listener that will be informed of trust store load errors - * - * @param updateInterval - * the trust anchor store update interval - * - * @param lazy - * whether the certificate validator should be lazy in loading crls - * and CAs - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param storeListener the listener that will be informed of trust store load errors + * @param updateInterval the trust anchor store update interval + * @param lazy whether the certificate validator should be lazy in loading crls and CAs + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. - * */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - StoreUpdateListener storeListener, long updateInterval, boolean lazy) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + StoreUpdateListener storeListener, + long updateInterval, + boolean lazy) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - storeListener, updateInterval, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, - DEFAULT_OCSP_CHECKS, lazy); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + storeListener, + updateInterval, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS, + lazy); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param storeListener - * the listener that will be informed of trust store load errors - * - * @param updateInterval - * the trust anchor store update interval - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param storeListener the listener that will be informed of trust store load errors + * @param updateInterval the trust anchor store update interval + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. - * */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - StoreUpdateListener storeListener, long updateInterval) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + StoreUpdateListener storeListener, + long updateInterval) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - storeListener, updateInterval, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, - DEFAULT_OCSP_CHECKS); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + storeListener, + updateInterval, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param updateInterval - * the trust anchor store update interval - * @param lazy - * whether the certificate validator should be lazy in loading crls - * and CAs - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param updateInterval the trust anchor store update interval + * @param lazy whether the certificate validator should be lazy in loading crls and CAs + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. - * */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - long updateInterval, boolean lazy) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + long updateInterval, + boolean lazy) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - null, updateInterval, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, - DEFAULT_OCSP_CHECKS, lazy); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + null, + updateInterval, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS, + lazy); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * @param validationErrorListener - * the listener that will receive notification about validation - * errors - * @param updateInterval - * the trust anchor store update interval - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @param validationErrorListener the listener that will receive notification about validation + * errors + * @param updateInterval the trust anchor store update interval + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. - * */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir, ValidationErrorListener validationErrorListener, - long updateInterval) { + String trustAnchorsDir, + ValidationErrorListener validationErrorListener, + long updateInterval) { - return buildCertificateValidator(trustAnchorsDir, validationErrorListener, - null, updateInterval, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, - DEFAULT_OCSP_CHECKS); + return buildCertificateValidator( + trustAnchorsDir, + validationErrorListener, + null, + updateInterval, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } /** - * Builds an Openssl-style certificate validator configured as specified in - * the parameters - * - * @param trustAnchorsDir - * the directory where trust anchors are loaded from - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * Builds an Openssl-style certificate validator configured as specified in the parameters + * + * @param trustAnchorsDir the directory where trust anchors are loaded from + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. */ @Deprecated - public static X509CertChainValidatorExt buildCertificateValidator( - String trustAnchorsDir) { + public static X509CertChainValidatorExt buildCertificateValidator(String trustAnchorsDir) { - return buildCertificateValidator(trustAnchorsDir, null, null, 0L, - DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, DEFAULT_OCSP_CHECKS); + return buildCertificateValidator( + trustAnchorsDir, + null, + null, + 0L, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } /** * Builds an Openssl-style certificate validator. - * - * @return an Openssl-style certificate validator configured as specified in - * the parameters - * + * + * @return an Openssl-style certificate validator configured as specified in the parameters * @deprecated Create a {@link CertificateValidatorBuilder} object instead. */ @Deprecated public static X509CertChainValidatorExt buildCertificateValidator() { return buildCertificateValidator( - DefaultVOMSValidator.DEFAULT_TRUST_ANCHORS_DIR, null, null, 0L, - DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, DEFAULT_OCSP_CHECKS); + DefaultVOMSValidator.DEFAULT_TRUST_ANCHORS_DIR, + null, + null, + 0L, + DEFAULT_NS_CHECKS, + DEFAULT_CRL_CHECKS, + DEFAULT_OCSP_CHECKS); } } diff --git a/src/main/java/org/italiangrid/voms/util/CredentialsUtils.java b/src/main/java/org/italiangrid/voms/util/CredentialsUtils.java index c057e88..5c1803a 100644 --- a/src/main/java/org/italiangrid/voms/util/CredentialsUtils.java +++ b/src/main/java/org/italiangrid/voms/util/CredentialsUtils.java @@ -7,6 +7,10 @@ import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.WRITE; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.helpers.CertificateHelpers; +import eu.emi.security.authn.x509.impl.CertificateUtils; +import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -28,130 +32,99 @@ import java.util.HashSet; import java.util.Set; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.helpers.CertificateHelpers; -import eu.emi.security.authn.x509.impl.CertificateUtils; -import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; - /** * An utility class for handling credentials - * + * * @author Daniele Andreotti * @author Andrea Ceccanti - * */ public class CredentialsUtils { - /** - * - * The encoding used to serialize proxy credentials private key. - * - */ + /** The encoding used to serialize proxy credentials private key. */ public enum PrivateKeyEncoding { - PKCS_1, PKCS_8 + PKCS_1, + PKCS_8 } - /** - * The default encoding used when no encoding is specified by callers. - */ + /** The default encoding used when no encoding is specified by callers. */ public static final PrivateKeyEncoding DEFAULT_ENCONDING = PrivateKeyEncoding.PKCS_1; /** * Serializes a private key to an output stream according to an encoding. - * - * @param os - * the target output stream - * @param key - * the key to be serialized - * @param encoding - * the encoding - * - * @throws IllegalArgumentException - * for unsupported private key encodings - * @throws IOException - * if write fails for any reason on the output stream + * + * @param os the target output stream + * @param key the key to be serialized + * @param encoding the encoding + * @throws IllegalArgumentException for unsupported private key encodings + * @throws IOException if write fails for any reason on the output stream */ - public static void savePrivateKey(OutputStream os, PrivateKey key, - PrivateKeyEncoding encoding) throws IOException { + public static void savePrivateKey(OutputStream os, PrivateKey key, PrivateKeyEncoding encoding) + throws IOException { switch (encoding) { - case PKCS_1: - savePrivateKeyPKCS1(os, key); - break; - case PKCS_8: - savePrivateKeyPKCS8(os, key); - break; - default: - throw new IllegalArgumentException("Unsupported private key encoding: " - + encoding.name()); + case PKCS_1: + savePrivateKeyPKCS1(os, key); + break; + case PKCS_8: + savePrivateKeyPKCS8(os, key); + break; + default: + throw new IllegalArgumentException("Unsupported private key encoding: " + encoding.name()); } } /** * Serializes a private key to an output stream following the pkcs8 encoding. - * - * This method just delegates to canl, but provides a much more understandable - * signature. - * + * + *

This method just delegates to canl, but provides a much more understandable signature. + * * @param os * @param key * @throws IllegalArgumentException * @throws IOException */ private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key) - throws IllegalArgumentException, IOException { + throws IllegalArgumentException, IOException { CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null); - } /** * Serializes a private key to an output stream following the pkcs1 encoding. - * - * This method just delegates to canl, but provides a much more understandable - * signature. - * + * + *

This method just delegates to canl, but provides a much more understandable signature. + * * @param os * @param key * @throws IllegalArgumentException * @throws IOException */ private static void savePrivateKeyPKCS1(OutputStream os, PrivateKey key) - throws IllegalArgumentException, IOException { - - CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, new char[0], - true); + throws IllegalArgumentException, IOException { + CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, new char[0], true); } /** * Saves user credentials as a plain text PEM data.
* Writes the user certificate chain first, then the user key. - * - * @param os - * the output stream - * @param uc - * the user credential that must be serialized - * @param encoding - * the private key encoding - * - * - * @throws IOException - * in case of errors writing on the output stream + * + * @param os the output stream + * @param uc the user credential that must be serialized + * @param encoding the private key encoding + * @throws IOException in case of errors writing on the output stream */ - public static void saveProxyCredentials(OutputStream os, X509Credential uc, - PrivateKeyEncoding encoding) throws IOException { + public static void saveProxyCredentials( + OutputStream os, X509Credential uc, PrivateKeyEncoding encoding) throws IOException { - X509Certificate[] chain = CertificateHelpers.sortChain(Arrays.asList(uc - .getCertificateChain())); + X509Certificate[] chain = CertificateHelpers.sortChain(Arrays.asList(uc.getCertificateChain())); PrivateKey key = uc.getKey(); X509Certificate cert = uc.getCertificate(); CertificateUtils.saveCertificate(os, cert, Encoding.PEM); - if (key != null) - savePrivateKey(os, key, encoding); + if (key != null) savePrivateKey(os, key, encoding); X509Certificate c = null; for (int index = 1; index < chain.length; index++) { @@ -161,52 +134,39 @@ public static void saveProxyCredentials(OutputStream os, X509Credential uc, int basicConstraints = c.getBasicConstraints(); // Only save non-CA certs to proxy file - if (basicConstraints < 0){ + if (basicConstraints < 0) { CertificateUtils.saveCertificate(os, c, Encoding.PEM); } - } os.flush(); } /** - * * Saves user credentials as a plain text PEM data.
- * Writes the user certificate chain first, then the user key, using the - * default encoding specified in {@link #DEFAULT_ENCONDING}. + * Writes the user certificate chain first, then the user key, using the default encoding + * specified in {@link #DEFAULT_ENCONDING}. * - * @param os - * the output stream for the saved proxy - * - * @param uc - * the user credential - * - * @throws IOException - * in case of errors writing to the output stream - * + * @param os the output stream for the saved proxy + * @param uc the user credential + * @throws IOException in case of errors writing to the output stream */ - public static void saveProxyCredentials(OutputStream os, X509Credential uc) - throws IOException { + public static void saveProxyCredentials(OutputStream os, X509Credential uc) throws IOException { saveProxyCredentials(os, uc, DEFAULT_ENCONDING); } /** - * Saves proxy credentials to a file. This method ensures that the stored - * proxy is saved with the appropriate file permissions. - * - * @param proxyFileName - * the file where the proxy will be saved - * @param uc - * the credential to be saved - * @param encoding - * the private key encoding - * @throws IOException - * in case of errors writing to the proxy file + * Saves proxy credentials to a file. This method ensures that the stored proxy is saved with the + * appropriate file permissions. + * + * @param proxyFileName the file where the proxy will be saved + * @param uc the credential to be saved + * @param encoding the private key encoding + * @throws IOException in case of errors writing to the proxy file */ - public static void saveProxyCredentials(String proxyFileName, X509Credential uc, - PrivateKeyEncoding encoding) throws IOException { + public static void saveProxyCredentials( + String proxyFileName, X509Credential uc, PrivateKeyEncoding encoding) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); saveProxyCredentials(baos, uc, encoding); @@ -232,21 +192,16 @@ public static void saveProxyCredentials(String proxyFileName, X509Credential uc, } /** - * - * Saves proxy credentials to a file. This method ensures that the stored - * proxy is saved with the appropriate file permissions, using the default - * encoding specified in {@link #DEFAULT_ENCONDING}. - * - * @param proxyFileName - * the file where the proxy will be saved - * @param uc - * the credential to be saved - * - * @throws IOException - * in case of errors writing the credential to the proxy file + * Saves proxy credentials to a file. This method ensures that the stored proxy is saved with the + * appropriate file permissions, using the default encoding specified in {@link + * #DEFAULT_ENCONDING}. + * + * @param proxyFileName the file where the proxy will be saved + * @param uc the credential to be saved + * @throws IOException in case of errors writing the credential to the proxy file */ - public static void saveProxyCredentials(String proxyFileName, - X509Credential uc) throws IOException { + public static void saveProxyCredentials(String proxyFileName, X509Credential uc) + throws IOException { saveProxyCredentials(proxyFileName, uc, DEFAULT_ENCONDING); } diff --git a/src/main/java/org/italiangrid/voms/util/FilePermissionHelper.java b/src/main/java/org/italiangrid/voms/util/FilePermissionHelper.java index 60fce65..78514de 100644 --- a/src/main/java/org/italiangrid/voms/util/FilePermissionHelper.java +++ b/src/main/java/org/italiangrid/voms/util/FilePermissionHelper.java @@ -9,41 +9,33 @@ import java.io.IOException; import java.io.InputStreamReader; import java.util.EnumSet; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.credential.FilePermissionError; /** * A helper class for performing basic Unix file permission checks. * - *

- * This class is intended to provide simple permission validation and modification for specific + *

This class is intended to provide simple permission validation and modification for specific * files, such as private keys and proxy certificates. It relies on executing system commands to * fetch and update file permissions. - *

* - *

- * Note: This implementation is a workaround until proper support for POSIX file permissions is + *

Note: This implementation is a workaround until proper support for POSIX file permissions is * available in Java. - *

- * */ public class FilePermissionHelper { - /** - * Enumeration representing POSIX file permissions. - */ + /** Enumeration representing POSIX file permissions. */ public static enum PosixFilePermission { // @formatter:off /** Read-only permission for the user (chmod 400, stat -r--------). */ - USER_RO ("400", "-r--------"), + USER_RO("400", "-r--------"), /** Read and write permission for the user (chmod 600, stat -rw-------). */ - USER_RW ("600", "-rw-------"), + USER_RW("600", "-rw-------"), /** Full permissions for the user (chmod 700, stat -rwx------). */ - USER_ALL ("700", "-rwx------"), + USER_ALL("700", "-rwx------"), /** Full permissions for all users (chmod 777, stat -rwxrwxrwx). */ - ALL_PERMS ("777", "-rwxrwxrwx"); + ALL_PERMS("777", "-rwxrwxrwx"); // @formatter:off private String chmodForm; @@ -82,33 +74,24 @@ public String chmodForm() { } } - /** - * Required file permissions for the private key file - */ + /** Required file permissions for the private key file */ public static final EnumSet PRIVATE_KEY_PERMS = EnumSet.of(PosixFilePermission.USER_RO, PosixFilePermission.USER_RW); - /** - * String representation of private key required permissions. - */ + /** String representation of private key required permissions. */ public static final String PRIVATE_KEY_PERMS_STR = PosixFilePermission.USER_RO.chmodForm() + ", " + PosixFilePermission.USER_RW.chmodForm(); - /** - * The command used to retrieve file permissions for a given file - */ + /** The command used to retrieve file permissions for a given file */ public static final String LS_CMD_TEMPLATE = "ls -al %s"; - /** - * The command used to set file permissions on a given file - */ + /** The command used to set file permissions on a given file */ public static final String CHMOD_CMD_TEMPLATE = "chmod %s %s"; /** * Checks whether a proxy file has the right permissions * * @param proxyFile the file to be checked - * * @throws IOException if an error occurs checking file attributes * @throws FilePermissionError if permissions are not as expected */ @@ -135,7 +118,8 @@ public static void checkPrivateKeyPermissions(String privateKeyFile) throws IOEx } final String errorMessage = - String.format("Wrong file permissions on file %s. Required permissions are: %s ", + String.format( + "Wrong file permissions on file %s. Required permissions are: %s ", privateKeyFile, PRIVATE_KEY_PERMS_STR); throw new FilePermissionError(errorMessage); @@ -158,7 +142,7 @@ public static void checkPKCS12Permissions(String pkcs12File) throws IOException * fetches the output of ls -al on a given file and matches the resulting string with the * permissionString passed as argument. * - * So the permissionString must be something like: + *

So the permissionString must be something like: * *

    * -rw-------
@@ -182,7 +166,8 @@ public static void matchesFilePermissions(String filename, PosixFilePermission e
 
     if (!filePerms.startsWith(expectedPerm.statForm())) {
       throw new FilePermissionError(
-          String.format("Wrong file permissions on file %s. Expected: %s",
+          String.format(
+              "Wrong file permissions on file %s. Expected: %s",
               filename, expectedPerm.chmodForm()));
     }
   }
@@ -280,5 +265,4 @@ public static void setFilePermissions(String filename, PosixFilePermission perm)
       throw new VOMSError("Error setting file permissions for " + filename, e);
     }
   }
-
 }
diff --git a/src/main/java/org/italiangrid/voms/util/FingerprintHelper.java b/src/main/java/org/italiangrid/voms/util/FingerprintHelper.java
index ceaac81..5f6627d 100644
--- a/src/main/java/org/italiangrid/voms/util/FingerprintHelper.java
+++ b/src/main/java/org/italiangrid/voms/util/FingerprintHelper.java
@@ -11,15 +11,11 @@
 
 /**
  * A utility class for computing fingerprints of X.509 certificates.
- * 

- * This class provides methods to generate a cryptographic fingerprint (hash) of an X.509 - * certificate using a specified digest algorithm. - *

* - *

- * The default digest algorithm used is SHA-1. - *

+ *

This class provides methods to generate a cryptographic fingerprint (hash) of an X.509 + * certificate using a specified digest algorithm. * + *

The default digest algorithm used is SHA-1. */ public class FingerprintHelper { @@ -34,8 +30,9 @@ public class FingerprintHelper { */ private static String hexify(byte[] bytes) { - char[] hexDigits = - {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + char[] hexDigits = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; StringBuffer buf = new StringBuffer(bytes.length * 2); @@ -66,5 +63,4 @@ public static String getFingerprint(X509Certificate cert) return hexify(digest); } - } diff --git a/src/main/java/org/italiangrid/voms/util/GaParser.java b/src/main/java/org/italiangrid/voms/util/GaParser.java index 577a143..c1cddf7 100644 --- a/src/main/java/org/italiangrid/voms/util/GaParser.java +++ b/src/main/java/org/italiangrid/voms/util/GaParser.java @@ -11,38 +11,37 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.italiangrid.voms.VOMSGenericAttribute; import org.italiangrid.voms.ac.impl.VOMSGenericAttributeImpl; - - public class GaParser { - + private static final String GA_TOKEN_REGEXP = "\\s*([a-zA-Z][a-zA-Z0-9_-]*)\\s*=\\s*(\\S+)\\s*"; private static final Pattern GA_TOKEN_PATTERN = Pattern.compile(GA_TOKEN_REGEXP); - + private GaParser() { + // empty constructor } - + public static List parseGaString(String gaString) { + if (isNull(gaString)) { throw new NullPointerException("Cannot parse a null gaString"); } - + if (gaString.isEmpty()) { return emptyList(); } - + List result = new ArrayList<>(); - + String[] gaTokens = gaString.split(","); - - for (String token: gaTokens) { - + + for (String token : gaTokens) { + Matcher m = GA_TOKEN_PATTERN.matcher(token); - + if (m.matches()) { String key = m.group(1); String value = m.group(2); @@ -50,11 +49,9 @@ public static List parseGaString(String gaString) { ga.setName(key); ga.setValue(value); result.add(ga); - } + } } - + return result; - } - } diff --git a/src/main/java/org/italiangrid/voms/util/NullListener.java b/src/main/java/org/italiangrid/voms/util/NullListener.java index 99559ae..40b052f 100644 --- a/src/main/java/org/italiangrid/voms/util/NullListener.java +++ b/src/main/java/org/italiangrid/voms/util/NullListener.java @@ -8,7 +8,6 @@ import java.lang.Thread.UncaughtExceptionHandler; import java.security.cert.X509Certificate; import java.util.List; - import org.italiangrid.voms.ac.ACLookupListener; import org.italiangrid.voms.ac.VOMSValidationResult; import org.italiangrid.voms.ac.ValidationResultListener; @@ -26,114 +25,63 @@ import org.italiangrid.voms.store.VOMSTrustStoreStatusListener; /** - * * A Singleton Listener which swallows notification. - * - * @author andreaceccanti * + * @author andreaceccanti */ -public enum NullListener implements ACLookupListener, ValidationResultListener, - VOMSServerInfoStoreListener, LoadCredentialsEventListener, - VOMSTrustStoreStatusListener, UncaughtExceptionHandler, VOMSRequestListener, - VOMSProtocolListener { - +public enum NullListener + implements + ACLookupListener, ValidationResultListener, VOMSServerInfoStoreListener, + LoadCredentialsEventListener, VOMSTrustStoreStatusListener, UncaughtExceptionHandler, + VOMSRequestListener, VOMSProtocolListener { INSTANCE; - public void notifyVOMSRequestStart(VOMSACRequest request, VOMSServerInfo si) { - - } - - public void notifyVOMSRequestSuccess(VOMSACRequest request, - VOMSServerInfo endpoint) { - - } - - public void notifyVOMSRequestFailure(VOMSACRequest request, - VOMSServerInfo endpoint, Throwable error) { - - } - - public void notifyErrorsInVOMSReponse(VOMSACRequest request, - VOMSServerInfo si, VOMSErrorMessage[] errors) { - - } - - public void notifyWarningsInVOMSResponse(VOMSACRequest request, - VOMSServerInfo si, VOMSWarningMessage[] warnings) { - - } - - public void uncaughtException(Thread t, Throwable e) { - - } - - public void notifyTrustStoreUpdate(VOMSTrustStore store) { - - } - - public void notifyCertficateLookupEvent(String dir) { - - } - - public void notifyLSCLookupEvent(String dir) { - - } - - public void notifyCertificateLoadEvent(X509Certificate cert, File f) { - - } - - public void notifyLSCLoadEvent(LSCInfo lsc, File f) { - - } - - public void notifyCredentialLookup(String... locations) { - - } - - public void notifyLoadCredentialSuccess(String... locations) { + public void notifyVOMSRequestStart(VOMSACRequest request, VOMSServerInfo si) {} - } + public void notifyVOMSRequestSuccess(VOMSACRequest request, VOMSServerInfo endpoint) {} - public void notifyLoadCredentialFailure(Throwable error, String... locations) { + public void notifyVOMSRequestFailure( + VOMSACRequest request, VOMSServerInfo endpoint, Throwable error) {} - } + public void notifyErrorsInVOMSReponse( + VOMSACRequest request, VOMSServerInfo si, VOMSErrorMessage[] errors) {} - public void notifyNoValidVOMSESError(List searchedPaths) { + public void notifyWarningsInVOMSResponse( + VOMSACRequest request, VOMSServerInfo si, VOMSWarningMessage[] warnings) {} - } + public void uncaughtException(Thread t, Throwable e) {} - public void notifyVOMSESlookup(String vomsesPath) { + public void notifyTrustStoreUpdate(VOMSTrustStore store) {} - } + public void notifyCertficateLookupEvent(String dir) {} - public void notifyVOMSESInformationLoaded(String vomsesPath, - VOMSServerInfo info) { + public void notifyLSCLookupEvent(String dir) {} - } + public void notifyCertificateLoadEvent(X509Certificate cert, File f) {} - public void notifyValidationResult(VOMSValidationResult result) { + public void notifyLSCLoadEvent(LSCInfo lsc, File f) {} - } + public void notifyCredentialLookup(String... locations) {} - public void notifyACLookupEvent(X509Certificate[] chain, int chainLevel) { + public void notifyLoadCredentialSuccess(String... locations) {} - } + public void notifyLoadCredentialFailure(Throwable error, String... locations) {} - public void notifyACParseEvent(X509Certificate[] chain, int chainLevel) { + public void notifyNoValidVOMSESError(List searchedPaths) {} - } + public void notifyVOMSESlookup(String vomsesPath) {} - public void notifyHTTPRequest(String url) { + public void notifyVOMSESInformationLoaded(String vomsesPath, VOMSServerInfo info) {} - } + public void notifyValidationResult(VOMSValidationResult result) {} - public void notifyLegacyRequest(String xmlLegacyRequest) { + public void notifyACLookupEvent(X509Certificate[] chain, int chainLevel) {} - } + public void notifyACParseEvent(X509Certificate[] chain, int chainLevel) {} - public void notifyReceivedResponse(VOMSResponse r) { + public void notifyHTTPRequest(String url) {} - } + public void notifyLegacyRequest(String xmlLegacyRequest) {} + public void notifyReceivedResponse(VOMSResponse r) {} } diff --git a/src/main/java/org/italiangrid/voms/util/TimeUtils.java b/src/main/java/org/italiangrid/voms/util/TimeUtils.java index 57c652c..b99ac1e 100644 --- a/src/main/java/org/italiangrid/voms/util/TimeUtils.java +++ b/src/main/java/org/italiangrid/voms/util/TimeUtils.java @@ -15,39 +15,36 @@ /** * Time utilities. - * - * @author cecco * + * @author cecco */ public class TimeUtils { public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_DATE_TIME.withResolverStyle(ResolverStyle.LENIENT); - private TimeUtils() { - - } + private TimeUtils() {} /** * Checks that a date falls in the interval allowing for a certain clock skew expressed in * minutes. The interval defined by (startDate, endDate) is modified to be (startDate - * skewInMinutes, endDate + skewInMinutes). - * + * * @param timeToCheck the time to be checked * @param startDate the start date of the time range * @param endDate the end date of the time range * @param skewInMinutes the clock skew in minutes to take into account - * * @throws IllegalArgumentException if passed an illegal time range * @return true, if the time is in the given range, false otherwise */ - public static boolean checkTimeInRangeWithSkew(Date timeToCheck, Date startDate, Date endDate, - int skewInMinutes) { + public static boolean checkTimeInRangeWithSkew( + Date timeToCheck, Date startDate, Date endDate, int skewInMinutes) { if (startDate.after(endDate) || startDate.equals(endDate)) { - String msg = String.format( - "Illegal time interval: start date must be before end date. [start date: %s, end date: %s]", - startDate, endDate); + String msg = + String.format( + "Illegal time interval: start date must be before end date. [start date: %s, end date: %s]", + startDate, endDate); throw new IllegalArgumentException(msg); } @@ -64,19 +61,18 @@ public static boolean checkTimeInRangeWithSkew(Date timeToCheck, Date startDate, Date skewedEndDate = cal.getTime(); return skewedEndDate.after(timeToCheck) && skewedStartDate.before(timeToCheck); - } - /** * Parses a date from string - * + * * @param date the date string representation; * @return the parsed date * @throws NullPointerException if date is null * @throws java.time.format.DateTimeParseException if the date is in the wrong format */ public static Date parseDate(String date) { + if (isNull(date)) { throw new NullPointerException("Cannot parse a null date"); } @@ -84,5 +80,4 @@ public static Date parseDate(String date) { LocalDateTime dateTime = LocalDateTime.parse(date, DATE_FORMATTER); return Date.from(dateTime.atZone(ZoneOffset.UTC).toInstant()); } - } diff --git a/src/main/java/org/italiangrid/voms/util/VOMSBase64Decoder.java b/src/main/java/org/italiangrid/voms/util/VOMSBase64Decoder.java index 624593c..3fddd2f 100644 --- a/src/main/java/org/italiangrid/voms/util/VOMSBase64Decoder.java +++ b/src/main/java/org/italiangrid/voms/util/VOMSBase64Decoder.java @@ -1,98 +1,89 @@ -// SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare -// -// SPDX-License-Identifier: Apache-2.0 - -package org.italiangrid.voms.util; - -// Gidon Moont -// Imperial College London -// Copyright (C) April 2006 - -// Voms uses a non-standard Base-64 algorithm. Hmmm... - -import org.bouncycastle.util.encoders.Base64; - -/** - * - * This class implements a decoder for the non-standard Base-64 algorithm used - * by voms. - * - * - * @author Gidon Moont - * @author Vincenzo Ciaschini - * - */ -public class VOMSBase64Decoder { - - // matrix out of src/common/xml.c - private static int[] decodemapint = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 53, 54, 55, 56, 57, 58, 59, 60, - 61, 0, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 62, 0, 63, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 0, 0, 0, 0, 0 }; - - private static byte[] decodemapbyte = new byte[128]; - static { - for (int i = 0; i < 128; i++) { - decodemapbyte[i] = (byte) decodemapint[i]; - } - } - - public static byte[] decode(String s) { - - if (s.indexOf('\n') != -1) { - return Base64.decode(s.trim().replaceAll("\n", "")); - } else - return mydecode(s); - } - - private static byte[] mydecode(String s) { - - char[] in = s.toCharArray(); - - int iLen = in.length; - - // cuts off end - do I need this? - // while (iLen > 0 && in[iLen-1] == '=') iLen--; - - int oLen = (iLen * 3) / 4; - byte[] out = new byte[oLen]; - int ip = 0; - int op = 0; - while (ip < iLen) { - int i0 = in[ip++]; - int i1 = in[ip++]; - int i2 = ip < iLen ? in[ip++] : 'A'; - int i3 = ip < iLen ? in[ip++] : 'A'; - - if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); - - int b0 = decodemapbyte[i0]; - int b1 = decodemapbyte[i1]; - int b2 = decodemapbyte[i2]; - int b3 = decodemapbyte[i3]; - if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); - - // ???????????? - int o0 = (b0 << 2) | (b1 >>> 4); - int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); - int o2 = ((b2 & 3) << 6) | b3; - - out[op++] = (byte) o0; - if (op < oLen) - out[op++] = (byte) o1; - if (op < oLen) - out[op++] = (byte) o2; - - } - - return out; - - } -} +// SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare +// +// SPDX-License-Identifier: Apache-2.0 + +package org.italiangrid.voms.util; + +// Gidon Moont +// Imperial College London +// Copyright (C) April 2006 + +// Voms uses a non-standard Base-64 algorithm. Hmmm... + +import org.bouncycastle.util.encoders.Base64; + +/** + * This class implements a decoder for the non-standard Base-64 algorithm used by voms. + * + * @author Gidon Moont + * @author Vincenzo Ciaschini + */ +public class VOMSBase64Decoder { + + // matrix out of src/common/xml.c + private static int[] decodemapint = + new int[] { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + 0, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 62, 0, 63, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0 + }; + + private static byte[] decodemapbyte = new byte[128]; + + static { + for (int i = 0; i < 128; i++) { + decodemapbyte[i] = (byte) decodemapint[i]; + } + } + + public static byte[] decode(String s) { + + if (s.indexOf('\n') != -1) { + return Base64.decode(s.trim().replaceAll("\n", "")); + } else return mydecode(s); + } + + private static byte[] mydecode(String s) { + + char[] in = s.toCharArray(); + + int iLen = in.length; + + // cuts off end - do I need this? + // while (iLen > 0 && in[iLen-1] == '=') iLen--; + + int oLen = (iLen * 3) / 4; + byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iLen ? in[ip++] : 'A'; + int i3 = ip < iLen ? in[ip++] : 'A'; + + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + + int b0 = decodemapbyte[i0]; + int b1 = decodemapbyte[i1]; + int b2 = decodemapbyte[i2]; + int b3 = decodemapbyte[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + + // ???????????? + int o0 = (b0 << 2) | (b1 >>> 4); + int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); + int o2 = ((b2 & 3) << 6) | b3; + + out[op++] = (byte) o0; + if (op < oLen) out[op++] = (byte) o1; + if (op < oLen) out[op++] = (byte) o2; + } + + return out; + } +} diff --git a/src/main/java/org/italiangrid/voms/util/VOMSFQANNamingScheme.java b/src/main/java/org/italiangrid/voms/util/VOMSFQANNamingScheme.java index 11c8a52..ea541c7 100644 --- a/src/main/java/org/italiangrid/voms/util/VOMSFQANNamingScheme.java +++ b/src/main/java/org/italiangrid/voms/util/VOMSFQANNamingScheme.java @@ -6,21 +6,19 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; - import org.italiangrid.voms.VOMSError; /** - * This class provides utility methods that are used for parsing, matching voms - * FQANs (Fully Qualified Attribute Names). - * + * This class provides utility methods that are used for parsing, matching voms FQANs (Fully + * Qualified Attribute Names). + * * @author Karoly Lorentey * @author Andrea Ceccanti - * - * */ public class VOMSFQANNamingScheme { - public static final String fqanSyntax = "^(/[\\w.-]+)+|((/[\\w.-]+)+/)?(Role=[\\w.-]+)|(Capability=[\\w\\s.-]+)$"; + public static final String fqanSyntax = + "^(/[\\w.-]+)+|((/[\\w.-]+)+/)?(Role=[\\w.-]+)|(Capability=[\\w\\s.-]+)$"; public static final String groupSyntax = "^(/[\\w.-]+)+$"; @@ -36,41 +34,29 @@ public class VOMSFQANNamingScheme { public static final Pattern rolePattern = Pattern.compile(roleSyntax); - public static final Pattern qualifiedRolePattern = Pattern - .compile(qualifiedRoleSyntax); + public static final Pattern qualifiedRolePattern = Pattern.compile(qualifiedRoleSyntax); - public static final Pattern capabilityPattern = Pattern - .compile(capabilitySyntax); + public static final Pattern capabilityPattern = Pattern.compile(capabilitySyntax); /** - * This methods checks that the string passed as argument complies with the - * voms FQAN syntax. - * - * @param fqan - * the string that must be checked for compatibility with FQAN - * syntax. - * @throws VOMSError - * If there's an error in the FQAN syntax. + * This methods checks that the string passed as argument complies with the voms FQAN syntax. + * + * @param fqan the string that must be checked for compatibility with FQAN syntax. + * @throws VOMSError If there's an error in the FQAN syntax. */ public static void checkSyntax(String fqan) { - if (fqan.length() > 255) - throw new VOMSError("fqan.length() > 255"); + if (fqan.length() > 255) throw new VOMSError("fqan.length() > 255"); - if (!fqanPattern.matcher(fqan).matches()) - throw new VOMSError("Syntax error in fqan: " + fqan); + if (!fqanPattern.matcher(fqan).matches()) throw new VOMSError("Syntax error in fqan: " + fqan); } /** - * - * This methods checks that the fqan passed as argument complies with the - * syntax used by voms to identify groups. - * - * @param fqan - * the string that has to be checked. - * @throws VOMSError - * If the string passed as argument doens not comply with the voms - * sytax. + * This methods checks that the fqan passed as argument complies with the syntax used by voms to + * identify groups. + * + * @param fqan the string that has to be checked. + * @throws VOMSError If the string passed as argument doens not comply with the voms sytax. */ public static void checkGroup(String fqan) { @@ -81,35 +67,29 @@ public static void checkGroup(String fqan) { } /** - * This methods checks that the string passed as argument complies with the - * syntax used by voms to identify roles. - * - * - * @param roleName - * the name of the role - * @throws VOMSError - * If the string passed as argument doens not comply with the voms - * sytax. + * This methods checks that the string passed as argument complies with the syntax used by voms to + * identify roles. + * + * @param roleName the name of the role + * @throws VOMSError If the string passed as argument doens not comply with the voms sytax. */ public static void checkRole(String roleName) { - if (roleName.length() > 255) - throw new VOMSError("roleName.length()>255"); + if (roleName.length() > 255) throw new VOMSError("roleName.length()>255"); if (!rolePattern.matcher(roleName).matches()) throw new VOMSError("Syntax error in role name: " + roleName); } /** - * This methods checks that the FQAN passed as argument identifies a voms - * group. - * - * @param groupName - * the string to check. - * @return

    - *
  • true, if the string passed as argument identifies a voms group. - *
  • false, otherwise. - *
+ * This methods checks that the FQAN passed as argument identifies a voms group. + * + * @param groupName the string to check. + * @return + *
    + *
  • true, if the string passed as argument identifies a voms group. + *
  • false, otherwise. + *
*/ public static boolean isGroup(String groupName) { @@ -119,15 +99,14 @@ public static boolean isGroup(String groupName) { } /** - * This methods checks that the FQAN passed as argument identifies a voms - * role. - * - * @param roleName - * the string to check. - * @return
    - *
  • true, if the string passed as argument identifies a voms role. - *
  • false, otherwise. - *
+ * This methods checks that the FQAN passed as argument identifies a voms role. + * + * @param roleName the string to check. + * @return + *
    + *
  • true, if the string passed as argument identifies a voms role. + *
  • false, otherwise. + *
*/ public static boolean isRole(String roleName) { @@ -136,16 +115,15 @@ public static boolean isRole(String roleName) { } /** - * This methods checks that the FQAN passed as argument identifies a qualified - * voms role, i.e., a role defined in the context of a voms group. - * - * @param fqan - * the string to check. - * @return
    - *
  • true, if the string passed as argument identifies a qualified - * voms role. - *
  • false, otherwise. - *
+ * This methods checks that the FQAN passed as argument identifies a qualified voms role, i.e., a + * role defined in the context of a voms group. + * + * @param fqan the string to check. + * @return + *
    + *
  • true, if the string passed as argument identifies a qualified voms role. + *
  • false, otherwise. + *
*/ public static boolean isQualifiedRole(String fqan) { @@ -154,47 +132,40 @@ public static boolean isQualifiedRole(String fqan) { } /** - * This method extracts the role name information from the FQAN passed as - * argument. - * - * @param containerName - * the FQAN - * @return
    - *
  • A string containing the role name, if found
  • - *
  • null, if no role information is contained in the FQAN passed as - * argument - *
+ * This method extracts the role name information from the FQAN passed as argument. + * + * @param containerName the FQAN + * @return + *
    + *
  • A string containing the role name, if found + *
  • null, if no role information is contained in the FQAN passed as argument + *
*/ public static String getRoleName(String containerName) { if (!isRole(containerName) && !isQualifiedRole(containerName)) - throw new VOMSError("No role specified in \"" + containerName - + "\" voms syntax."); + throw new VOMSError("No role specified in \"" + containerName + "\" voms syntax."); Matcher m = fqanPattern.matcher(containerName); if (m.matches()) { String roleGroup = m.group(4); - return roleGroup - .substring(roleGroup.indexOf('=') + 1, roleGroup.length()); - + return roleGroup.substring(roleGroup.indexOf('=') + 1, roleGroup.length()); } return null; } /** - * This method extracts group name information from the FQAN passed as - * argument. - * - * @param containerName - * the FQAN - * @return
    - *
  • A string containing the group name, if found
  • - *
  • null, if no group information is contained in the FQAN passed - * as argument - *
+ * This method extracts group name information from the FQAN passed as argument. + * + * @param containerName the FQAN + * @return + *
    + *
  • A string containing the group name, if found + *
  • null, if no group information is contained in the FQAN passed as argument + *
*/ public static String getGroupName(String containerName) { @@ -203,18 +174,15 @@ public static String getGroupName(String containerName) { // If it's a container and it's not a role or a qualified role, then // it's a group! - if (!isRole(containerName) && !isQualifiedRole(containerName)) - return containerName; + if (!isRole(containerName) && !isQualifiedRole(containerName)) return containerName; Matcher m = fqanPattern.matcher(containerName); if (m.matches()) { String groupName = m.group(2); - if (groupName.endsWith("/")) - return groupName.substring(0, groupName.length() - 1); - else - return groupName; + if (groupName.endsWith("/")) return groupName.substring(0, groupName.length() - 1); + else return groupName; } return null; @@ -228,6 +196,5 @@ public static String toOldQualifiedRoleSyntax(String qualifiedRole) { throw new VOMSError("String passed as argument is not a qualified role!"); return getGroupName(qualifiedRole) + ":" + getRoleName(qualifiedRole); - } } diff --git a/src/main/java/org/italiangrid/voms/util/XMLUtils.java b/src/main/java/org/italiangrid/voms/util/XMLUtils.java index c08330e..9374f61 100644 --- a/src/main/java/org/italiangrid/voms/util/XMLUtils.java +++ b/src/main/java/org/italiangrid/voms/util/XMLUtils.java @@ -5,13 +5,11 @@ package org.italiangrid.voms.util; import java.io.StringWriter; - import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - import org.italiangrid.voms.VOMSError; import org.w3c.dom.Document; @@ -20,8 +18,7 @@ public class XMLUtils { public static String documentAsString(Document doc) { try { - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); @@ -31,6 +28,5 @@ public static String documentAsString(Document doc) { } catch (Throwable e) { throw new VOMSError(e.getMessage(), e); } - } } diff --git a/src/main/java/org/italiangrid/voms/util/package-info.java b/src/main/java/org/italiangrid/voms/util/package-info.java index 3de2284..3d2be3f 100644 --- a/src/main/java/org/italiangrid/voms/util/package-info.java +++ b/src/main/java/org/italiangrid/voms/util/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package provides utility classes used in other packages. - */ +/** This package provides utility classes used in other packages. */ package org.italiangrid.voms.util; - diff --git a/src/test/java/org/italiangrid/voms/test/TestDefaultVOMSTrustStore.java b/src/test/java/org/italiangrid/voms/test/TestDefaultVOMSTrustStore.java index 3483d0d..a5fab1c 100644 --- a/src/test/java/org/italiangrid/voms/test/TestDefaultVOMSTrustStore.java +++ b/src/test/java/org/italiangrid/voms/test/TestDefaultVOMSTrustStore.java @@ -2,9 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * - */ +/** */ package org.italiangrid.voms.test; import static org.junit.Assert.assertEquals; @@ -12,6 +10,8 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import eu.emi.security.authn.x509.impl.CertificateUtils; +import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -19,18 +19,13 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.impl.DefaultVOMSTrustStore; import org.italiangrid.voms.util.NullListener; import org.junit.Test; -import eu.emi.security.authn.x509.impl.CertificateUtils; -import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding; - /** * @author Andrea Ceccanti - * */ public class TestDefaultVOMSTrustStore { @@ -39,7 +34,6 @@ public void testEmptyTrustDirsFailure() { @SuppressWarnings({"unused", "unchecked"}) DefaultVOMSTrustStore store = new DefaultVOMSTrustStore(Collections.EMPTY_LIST); - } @Test(expected = VOMSError.class) @@ -63,7 +57,6 @@ public void testDefaultTrustDir() { assertEquals(1, trustDirs.size()); assertEquals(DefaultVOMSTrustStore.DEFAULT_VOMS_DIR, trustDirs.get(0)); - } @Test @@ -73,7 +66,6 @@ public void testEmptyTrustDir() { @SuppressWarnings("unused") DefaultVOMSTrustStore store = new DefaultVOMSTrustStore(trustDirs); - } @Test @@ -90,8 +82,9 @@ public void testCertificateParsing() throws FileNotFoundException, IOException { assertEquals(1, store.getLocalAACertificates().size()); - assertTrue(cert.getSubjectX500Principal() - .equals(store.getLocalAACertificates().get(0).getSubjectX500Principal())); + assertTrue( + cert.getSubjectX500Principal() + .equals(store.getLocalAACertificates().get(0).getSubjectX500Principal())); } @Test @@ -104,7 +97,6 @@ public void testAllLSCInStore() { assertNotNull(store.getLSC("test.vo", "test-host.cnaf.infn.it")); assertNotNull(store.getLSC("test.vo", "test-multichain.cnaf.infn.it")); assertNotNull(store.getLSC("test.vo.1", "wilco.cnaf.infn.it")); - } @Test @@ -118,10 +110,7 @@ public void testLSCForVoInStore() { assertNotNull(store.getLSC("test.vo", "test-host.cnaf.infn.it")); assertNotNull(store.getLSC("test.vo", "test-multichain.cnaf.infn.it")); assertNull(store.getLSC("test.vo.1", "wilco.cnaf.infn.it")); - } - public void testUpdatingVOMSTrustStore() { - - } + public void testUpdatingVOMSTrustStore() {} } diff --git a/src/test/java/org/italiangrid/voms/test/TestFilePermissionHelper.java b/src/test/java/org/italiangrid/voms/test/TestFilePermissionHelper.java index 38b25f3..f8288c5 100644 --- a/src/test/java/org/italiangrid/voms/test/TestFilePermissionHelper.java +++ b/src/test/java/org/italiangrid/voms/test/TestFilePermissionHelper.java @@ -5,7 +5,6 @@ package org.italiangrid.voms.test; import java.io.IOException; - import org.italiangrid.voms.credential.FilePermissionError; import org.italiangrid.voms.util.FilePermissionHelper; import org.italiangrid.voms.util.FilePermissionHelper.PosixFilePermission; @@ -28,14 +27,10 @@ public static void setupPermissions() { FilePermissionHelper.setPrivateKeyPermissions(keyWithRightPerms); FilePermissionHelper.setPKCS12Permissions(p12WithRightPerms); - FilePermissionHelper.setFilePermissions(keyWithWrongPerms, - PosixFilePermission.ALL_PERMS); - FilePermissionHelper.setFilePermissions(p12WithWrongPerms, - PosixFilePermission.ALL_PERMS); - - FilePermissionHelper.setFilePermissions(keyWith600Perms, - PosixFilePermission.USER_RW); + FilePermissionHelper.setFilePermissions(keyWithWrongPerms, PosixFilePermission.ALL_PERMS); + FilePermissionHelper.setFilePermissions(p12WithWrongPerms, PosixFilePermission.ALL_PERMS); + FilePermissionHelper.setFilePermissions(keyWith600Perms, PosixFilePermission.USER_RW); } @Test @@ -44,7 +39,6 @@ public void testFilePermissions() throws IOException { FilePermissionHelper.checkPrivateKeyPermissions(keyWithRightPerms); FilePermissionHelper.checkPrivateKeyPermissions(keyWith600Perms); FilePermissionHelper.checkPKCS12Permissions(p12WithRightPerms); - } @Test(expected = FilePermissionError.class) @@ -58,5 +52,4 @@ public void testFilePermissionsFailureP12() throws IOException { FilePermissionHelper.checkPKCS12Permissions(p12WithWrongPerms); } - } diff --git a/src/test/java/org/italiangrid/voms/test/TestFingerprint.java b/src/test/java/org/italiangrid/voms/test/TestFingerprint.java index 9d6c0b1..0143098 100644 --- a/src/test/java/org/italiangrid/voms/test/TestFingerprint.java +++ b/src/test/java/org/italiangrid/voms/test/TestFingerprint.java @@ -4,18 +4,16 @@ package org.italiangrid.voms.test; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; - import org.italiangrid.voms.util.FingerprintHelper; import org.junit.Test; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class TestFingerprint { public static final String keyPassword = "pass"; @@ -24,18 +22,19 @@ public class TestFingerprint { public static final String pemKey = "src/test/resources/certs/test0.key.pem"; @Test - public void testGetFingerprint() throws KeyStoreException, - CertificateException, FileNotFoundException, IOException, - NoSuchAlgorithmException { + public void testGetFingerprint() + throws KeyStoreException, + CertificateException, + FileNotFoundException, + IOException, + NoSuchAlgorithmException { - PEMCredential cred = new PEMCredential(new FileInputStream(pemKey), - new FileInputStream(pemCert), keyPassword.toCharArray()); + PEMCredential cred = + new PEMCredential( + new FileInputStream(pemKey), new FileInputStream(pemCert), keyPassword.toCharArray()); - String fingerprint = FingerprintHelper - .getFingerprint(cred.getCertificate()); + String fingerprint = FingerprintHelper.getFingerprint(cred.getCertificate()); System.out.println(fingerprint); - } - } diff --git a/src/test/java/org/italiangrid/voms/test/TestLSCParser.java b/src/test/java/org/italiangrid/voms/test/TestLSCParser.java index 2aa9d42..6ec52cb 100644 --- a/src/test/java/org/italiangrid/voms/test/TestLSCParser.java +++ b/src/test/java/org/italiangrid/voms/test/TestLSCParser.java @@ -11,7 +11,6 @@ import java.io.ByteArrayInputStream; import java.io.File; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.store.impl.DefaultLSCFileParser; import org.italiangrid.voms.store.impl.LSCFile; @@ -24,12 +23,14 @@ public void testParse() { DefaultLSCFileParser parser = new DefaultLSCFileParser(); - String lscContent = "# First line is a comment \n" - + "--- second line should skipped \n" + "/C=it/O=org/CN=commonName\n" - + " \t\n" + "/C=it/O=org/CN=CA\n"; + String lscContent = + "# First line is a comment \n" + + "--- second line should skipped \n" + + "/C=it/O=org/CN=commonName\n" + + " \t\n" + + "/C=it/O=org/CN=CA\n"; - LSCFile f = parser.parse("vo", "host", - new ByteArrayInputStream(lscContent.getBytes())); + LSCFile f = parser.parse("vo", "host", new ByteArrayInputStream(lscContent.getBytes())); assertNull(f.getFilename()); @@ -43,36 +44,33 @@ public void testParse() { assertEquals("/C=it/O=org/CN=commonName", f.getCertificateChainDescription().get(0)); assertEquals("/C=it/O=org/CN=CA", f.getCertificateChainDescription().get(1)); - } @Test public void testOddLSCFileParseError() { - String singleEntryLSCFile = "# This is a comment \n" - + "/C=it/O=org/CN=commonName\n"; + String singleEntryLSCFile = "# This is a comment \n" + "/C=it/O=org/CN=commonName\n"; - String errorMessage = "LSC file parsing error: " - + "Malformed LSC file (vo=vo, host=host): " - + "Odd number of distinguished name entries."; + String errorMessage = + "LSC file parsing error: " + + "Malformed LSC file (vo=vo, host=host): " + + "Odd number of distinguished name entries."; DefaultLSCFileParser parser = new DefaultLSCFileParser(); try { @SuppressWarnings("unused") - LSCFile f = parser.parse("vo", "host", new ByteArrayInputStream( - singleEntryLSCFile.getBytes())); + LSCFile f = + parser.parse("vo", "host", new ByteArrayInputStream(singleEntryLSCFile.getBytes())); } catch (VOMSError e) { assertEquals(errorMessage, e.getMessage()); return; - } fail("No error caught for malformed, single line LSC file parsing."); - } @Test @@ -82,15 +80,15 @@ public void testEmptyLSCFileParseError() { String emptyLSCContent = "# This is a comment"; - String errorMessage = "LSC file parsing error: " - + "Malformed LSC file (vo=vo, host=host): " - + "No distinguished name entries found."; + String errorMessage = + "LSC file parsing error: " + + "Malformed LSC file (vo=vo, host=host): " + + "No distinguished name entries found."; try { @SuppressWarnings("unused") - LSCFile f = parser.parse("vo", "host", new ByteArrayInputStream( - emptyLSCContent.getBytes())); + LSCFile f = parser.parse("vo", "host", new ByteArrayInputStream(emptyLSCContent.getBytes())); } catch (VOMSError e) { assertEquals(errorMessage, e.getMessage()); @@ -118,16 +116,20 @@ public void testUnsupportedMultichainLSCFileParseSuccess() { DefaultLSCFileParser parser = new DefaultLSCFileParser(); - String multichainLSCContent = "/C=IT/O=IGI/CN=test-host.cnaf.infn.it\n" - + "/C=IT/O=IGI/CN=Test CA\n" + "------NEXT CHAIN------\n" - + "/C=IT/O=IGI/CN=test-host2.cnaf.infn.it\n" + "/C=IT/O=IGI/CN=Test CA"; + String multichainLSCContent = + "/C=IT/O=IGI/CN=test-host.cnaf.infn.it\n" + + "/C=IT/O=IGI/CN=Test CA\n" + + "------NEXT CHAIN------\n" + + "/C=IT/O=IGI/CN=test-host2.cnaf.infn.it\n" + + "/C=IT/O=IGI/CN=Test CA"; try { LSCFile f = parser.parse("vo", "host", new ByteArrayInputStream(multichainLSCContent.getBytes())); assertEquals(2, f.getCertificateChainDescription().size()); - assertEquals("/C=IT/O=IGI/CN=test-host.cnaf.infn.it", f.getCertificateChainDescription().get(0)); + assertEquals( + "/C=IT/O=IGI/CN=test-host.cnaf.infn.it", f.getCertificateChainDescription().get(0)); assertEquals("/C=IT/O=IGI/CN=Test CA", f.getCertificateChainDescription().get(1)); } catch (VOMSError e) { @@ -136,7 +138,6 @@ public void testUnsupportedMultichainLSCFileParseSuccess() { } } - @Test public void testNonExistingFileParse() { @@ -151,14 +152,11 @@ public void testNonExistingFileParse() { } catch (VOMSError e) { - assertEquals("LSC file does not exist: " + nonExistentFile, - e.getMessage()); + assertEquals("LSC file does not exist: " + nonExistentFile, e.getMessage()); return; - } fail("VOMS error not thrown for non existing LSC file parsing attempt."); - } } diff --git a/src/test/java/org/italiangrid/voms/test/TestOpensslHashFunction.java b/src/test/java/org/italiangrid/voms/test/TestOpensslHashFunction.java index 97b9d79..63c52d6 100644 --- a/src/test/java/org/italiangrid/voms/test/TestOpensslHashFunction.java +++ b/src/test/java/org/italiangrid/voms/test/TestOpensslHashFunction.java @@ -4,19 +4,17 @@ package org.italiangrid.voms.test; +import eu.emi.security.authn.x509.ValidationResult; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.IOException; import java.security.KeyStoreException; import java.security.cert.CertificateException; - import org.italiangrid.voms.util.CertificateValidatorBuilder; import org.italiangrid.voms.util.CertificateValidatorBuilder.OpensslHashFunction; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.ValidationResult; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class TestOpensslHashFunction { static final String trustAnchorsDir = "src/test/resources/trust-anchors"; @@ -30,8 +28,7 @@ public class TestOpensslHashFunction { static PEMCredential cred; @BeforeClass - public static void init() - throws KeyStoreException, CertificateException, IOException { + public static void init() throws KeyStoreException, CertificateException, IOException { cred = new PEMCredential(userKey, userCert, keyPassword.toCharArray()); } @@ -42,22 +39,18 @@ public void testDefaultHashIsMD5() { CertificateValidatorBuilder builder = new CertificateValidatorBuilder(); builder.trustAnchorsDir(md5TrustAnchorsDir); - ValidationResult result = builder.build() - .validate(cred.getCertificateChain()); + ValidationResult result = builder.build().validate(cred.getCertificateChain()); Assert.assertTrue(result.isValid()); - } @Test public void testSHA1Hash() { CertificateValidatorBuilder builder = new CertificateValidatorBuilder(); - builder.trustAnchorsDir(sha1TrustAnchorsDir) - .opensslHashFunction(OpensslHashFunction.SHA1); + builder.trustAnchorsDir(sha1TrustAnchorsDir).opensslHashFunction(OpensslHashFunction.SHA1); - ValidationResult result = builder.build() - .validate(cred.getCertificateChain()); + ValidationResult result = builder.build().validate(cred.getCertificateChain()); Assert.assertTrue(result.isValid()); } @@ -68,47 +61,43 @@ public void testMD5HashFailsOnSHA1Dir() { CertificateValidatorBuilder builder = new CertificateValidatorBuilder(); builder.trustAnchorsDir(sha1TrustAnchorsDir); - ValidationResult result = builder.build() - .validate(cred.getCertificateChain()); + ValidationResult result = builder.build().validate(cred.getCertificateChain()); Assert.assertFalse(result.isValid()); Assert.assertEquals(2, result.getErrors().size()); Assert.assertEquals( - "No trusted CA certificate was found for the certificate chain", - result.getErrors().get(0).getMessage()); + "No trusted CA certificate was found for the certificate chain", + result.getErrors().get(0).getMessage()); Assert.assertEquals( - "Trusted issuer of this certificate was not established", - result.getErrors().get(1).getMessage()); - - Assert.assertEquals(cred.getCertificate().getSubjectX500Principal(), - result.getErrors().get(1).getChain()[0].getSubjectX500Principal()); + "Trusted issuer of this certificate was not established", + result.getErrors().get(1).getMessage()); + Assert.assertEquals( + cred.getCertificate().getSubjectX500Principal(), + result.getErrors().get(1).getChain()[0].getSubjectX500Principal()); } @Test public void testSHA1FailsOnMD5Dir() { CertificateValidatorBuilder builder = new CertificateValidatorBuilder(); - builder.trustAnchorsDir(md5TrustAnchorsDir) - .opensslHashFunction(OpensslHashFunction.SHA1); + builder.trustAnchorsDir(md5TrustAnchorsDir).opensslHashFunction(OpensslHashFunction.SHA1); - ValidationResult result = builder.build() - .validate(cred.getCertificateChain()); + ValidationResult result = builder.build().validate(cred.getCertificateChain()); Assert.assertFalse(result.isValid()); Assert.assertEquals(2, result.getErrors().size()); Assert.assertEquals( - "No trusted CA certificate was found for the certificate chain", - result.getErrors().get(0).getMessage()); + "No trusted CA certificate was found for the certificate chain", + result.getErrors().get(0).getMessage()); Assert.assertEquals( - "Trusted issuer of this certificate was not established", - result.getErrors().get(1).getMessage()); - - Assert.assertEquals(cred.getCertificate().getSubjectX500Principal(), - result.getErrors().get(1).getChain()[0].getSubjectX500Principal()); + "Trusted issuer of this certificate was not established", + result.getErrors().get(1).getMessage()); + Assert.assertEquals( + cred.getCertificate().getSubjectX500Principal(), + result.getErrors().get(1).getChain()[0].getSubjectX500Principal()); } - } diff --git a/src/test/java/org/italiangrid/voms/test/TestTimeUtils.java b/src/test/java/org/italiangrid/voms/test/TestTimeUtils.java index 25e9c44..77a24ce 100644 --- a/src/test/java/org/italiangrid/voms/test/TestTimeUtils.java +++ b/src/test/java/org/italiangrid/voms/test/TestTimeUtils.java @@ -6,10 +6,8 @@ import java.util.Calendar; import java.util.Date; - -import org.junit.Assert; - import org.italiangrid.voms.util.TimeUtils; +import org.junit.Assert; import org.junit.Test; public class TestTimeUtils { @@ -23,9 +21,7 @@ public void testSuccessfulCompute() { Date nowPlus1Minute = cal.getTime(); - Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, now, - nowPlus1Minute, 1)); - + Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, now, nowPlus1Minute, 1)); } @Test(expected = IllegalArgumentException.class) @@ -62,11 +58,8 @@ public void testLowerBound() { Date inOneYear = cal.getTime(); - Assert.assertFalse(TimeUtils.checkTimeInRangeWithSkew(now, nowPlus2minute, - inOneYear, 2)); - Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, nowPlus2minute, - inOneYear, 3)); - + Assert.assertFalse(TimeUtils.checkTimeInRangeWithSkew(now, nowPlus2minute, inOneYear, 2)); + Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, nowPlus2minute, inOneYear, 3)); } @Test @@ -79,11 +72,7 @@ public void testUpperBound() { Date oneYearAgo = cal.getTime(); - Assert.assertFalse(TimeUtils.checkTimeInRangeWithSkew(now, oneYearAgo, now, - 0)); - Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, oneYearAgo, now, - 1)); - + Assert.assertFalse(TimeUtils.checkTimeInRangeWithSkew(now, oneYearAgo, now, 0)); + Assert.assertTrue(TimeUtils.checkTimeInRangeWithSkew(now, oneYearAgo, now, 1)); } - } diff --git a/src/test/java/org/italiangrid/voms/test/TestVOMSESLineParser.java b/src/test/java/org/italiangrid/voms/test/TestVOMSESLineParser.java index 37cb530..1ac6f90 100644 --- a/src/test/java/org/italiangrid/voms/test/TestVOMSESLineParser.java +++ b/src/test/java/org/italiangrid/voms/test/TestVOMSESLineParser.java @@ -11,7 +11,6 @@ import static org.junit.Assert.fail; import java.net.URISyntaxException; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSServerInfo; import org.italiangrid.voms.request.impl.VOMSESLineParser; @@ -43,7 +42,6 @@ public void emptyLineReturnsNull() throws URISyntaxException { VOMSESLineParser p = new VOMSESLineParser(); VOMSServerInfo i = p.parse(line); assertNull(i); - } @Test @@ -149,7 +147,8 @@ public void whitespaceHandling() { @Test public void tooManyFields() { - String line = "\t\"a\" \"voms.cern.ch\" \t \"15000\" \"DN=Illo\" \"alice\" \"24\" \"Too much\""; + String line = + "\t\"a\" \"voms.cern.ch\" \t \"15000\" \"DN=Illo\" \"alice\" \"24\" \"Too much\""; try { VOMSESLineParser p = new VOMSESLineParser(); @@ -159,7 +158,6 @@ public void tooManyFields() { assertNotNull("Got a null error message", e.getMessage()); assertTrue(e.getMessage().contains("Invalid VOMSES line: too many fields!")); } - } @Test @@ -175,7 +173,6 @@ public void invalidPort() { assertNotNull("Got a null error message", e.getMessage()); assertTrue(e.getMessage().contains("Invalid VOMSES line: invalid port number.")); } - } @Test diff --git a/src/test/java/org/italiangrid/voms/test/TestVOMSESLookupStrategy.java b/src/test/java/org/italiangrid/voms/test/TestVOMSESLookupStrategy.java index dfba329..62efa6f 100644 --- a/src/test/java/org/italiangrid/voms/test/TestVOMSESLookupStrategy.java +++ b/src/test/java/org/italiangrid/voms/test/TestVOMSESLookupStrategy.java @@ -7,11 +7,9 @@ import java.io.File; import java.util.Arrays; import java.util.List; - -import org.junit.Assert; - import org.italiangrid.voms.request.VOMSESLookupStrategy; import org.italiangrid.voms.request.impl.BaseVOMSESLookupStrategy; +import org.junit.Assert; import org.junit.Test; public class TestVOMSESLookupStrategy { @@ -19,14 +17,13 @@ public class TestVOMSESLookupStrategy { @Test public void testLookupVomsesInfo() { - VOMSESLookupStrategy strategy = new BaseVOMSESLookupStrategy(Arrays.asList( - "src/test/resources/vomses", "/non/existent/path")); + VOMSESLookupStrategy strategy = + new BaseVOMSESLookupStrategy( + Arrays.asList("src/test/resources/vomses", "/non/existent/path")); List paths = strategy.lookupVomsesInfo(); Assert.assertEquals(1, paths.size()); Assert.assertTrue(paths.contains(new File("src/test/resources/vomses"))); - } - } diff --git a/src/test/java/org/italiangrid/voms/test/TestVOMSESParser.java b/src/test/java/org/italiangrid/voms/test/TestVOMSESParser.java index 105ff5d..96c2c1e 100644 --- a/src/test/java/org/italiangrid/voms/test/TestVOMSESParser.java +++ b/src/test/java/org/italiangrid/voms/test/TestVOMSESParser.java @@ -9,7 +9,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.List; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSESParser; import org.italiangrid.voms.request.VOMSESParserFactory; @@ -29,8 +28,7 @@ public void testNonExistingFileParser() { @SuppressWarnings("unused") List info = parser.parse(new File(nonExistentFile)); } catch (VOMSError e) { - Assert.assertEquals("VOMSES file does not exist: " + nonExistentFile, - e.getMessage()); + Assert.assertEquals("VOMSES file does not exist: " + nonExistentFile, e.getMessage()); return; } @@ -40,21 +38,20 @@ public void testNonExistingFileParser() { @Test public void testValidStringParsing() throws URISyntaxException { - String validVomsesString = "\"alice\" \"lcg-voms.cern.ch\" \"15000\" \"/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch\" \"alice\" \"24\""; + String validVomsesString = + "\"alice\" \"lcg-voms.cern.ch\" \"15000\" \"/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch\" \"alice\" \"24\""; VOMSESParser parser = VOMSESParserFactory.newVOMSESParser(); - List info = parser - .parse(new StringReader(validVomsesString)); + List info = parser.parse(new StringReader(validVomsesString)); Assert.assertEquals(1, info.size()); VOMSServerInfo aliceInfo = info.get(0); Assert.assertEquals("alice", aliceInfo.getAlias()); Assert.assertEquals("alice", aliceInfo.getVoName()); - Assert.assertEquals(new URI("voms://lcg-voms.cern.ch:15000"), - aliceInfo.getURL()); - Assert.assertEquals("/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch", - aliceInfo.getVOMSServerDN()); + Assert.assertEquals(new URI("voms://lcg-voms.cern.ch:15000"), aliceInfo.getURL()); + Assert.assertEquals( + "/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch", aliceInfo.getVOMSServerDN()); } @Test @@ -68,18 +65,16 @@ public void testValidFileParsing() throws URISyntaxException { VOMSServerInfo pdVoms = info.get(0); Assert.assertEquals("eumed", pdVoms.getAlias()); Assert.assertEquals("eumed", pdVoms.getVoName()); - Assert.assertEquals(new URI("voms://voms-02.pd.infn.it:15016"), - pdVoms.getURL()); - Assert.assertEquals("/C=IT/O=INFN/OU=Host/L=Padova/CN=voms-02.pd.infn.it", - pdVoms.getVOMSServerDN()); + Assert.assertEquals(new URI("voms://voms-02.pd.infn.it:15016"), pdVoms.getURL()); + Assert.assertEquals( + "/C=IT/O=INFN/OU=Host/L=Padova/CN=voms-02.pd.infn.it", pdVoms.getVOMSServerDN()); VOMSServerInfo cnafVoms = info.get(1); Assert.assertEquals("eumed", cnafVoms.getAlias()); Assert.assertEquals("eumed", cnafVoms.getVoName()); - Assert.assertEquals(new URI("voms://voms2.cnaf.infn.it:15016"), - cnafVoms.getURL()); - Assert.assertEquals("/C=IT/O=INFN/OU=Host/L=CNAF/CN=voms2.cnaf.infn.it", - cnafVoms.getVOMSServerDN()); + Assert.assertEquals(new URI("voms://voms2.cnaf.infn.it:15016"), cnafVoms.getURL()); + Assert.assertEquals( + "/C=IT/O=INFN/OU=Host/L=CNAF/CN=voms2.cnaf.infn.it", cnafVoms.getVOMSServerDN()); } @Test @@ -94,20 +89,19 @@ public void testValidDirectoryParsing() throws URISyntaxException { @Test public void testSingleCharAliasParsing() throws URISyntaxException { - String validVomsesString = "\"a\" \"lcg-voms.cern.ch\" \"15000\" \"/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch\" \"alice\" \"24\""; + String validVomsesString = + "\"a\" \"lcg-voms.cern.ch\" \"15000\" \"/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch\" \"alice\" \"24\""; VOMSESParser parser = VOMSESParserFactory.newVOMSESParser(); - List info = parser - .parse(new StringReader(validVomsesString)); + List info = parser.parse(new StringReader(validVomsesString)); Assert.assertEquals(1, info.size()); VOMSServerInfo aliceInfo = info.get(0); Assert.assertEquals("a", aliceInfo.getAlias()); Assert.assertEquals("alice", aliceInfo.getVoName()); - Assert.assertEquals(new URI("voms://lcg-voms.cern.ch:15000"), - aliceInfo.getURL()); - Assert.assertEquals("/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch", - aliceInfo.getVOMSServerDN()); + Assert.assertEquals(new URI("voms://lcg-voms.cern.ch:15000"), aliceInfo.getURL()); + Assert.assertEquals( + "/DC=ch/DC=cern/OU=computers/CN=lcg-voms.cern.ch", aliceInfo.getVOMSServerDN()); } } diff --git a/src/test/java/org/italiangrid/voms/test/TestVOMSServerInfoStore.java b/src/test/java/org/italiangrid/voms/test/TestVOMSServerInfoStore.java index 755de1e..2c6f765 100644 --- a/src/test/java/org/italiangrid/voms/test/TestVOMSServerInfoStore.java +++ b/src/test/java/org/italiangrid/voms/test/TestVOMSServerInfoStore.java @@ -8,7 +8,6 @@ import java.util.Arrays; import java.util.Set; - import org.italiangrid.voms.request.VOMSESLookupStrategy; import org.italiangrid.voms.request.VOMSServerInfo; import org.italiangrid.voms.request.impl.BaseVOMSESLookupStrategy; @@ -21,11 +20,11 @@ public class TestVOMSServerInfoStore { @Test public void testExistingVOMSESParsingSuccess() { - VOMSESLookupStrategy strategy = new BaseVOMSESLookupStrategy( - Arrays.asList("src/test/resources/vomses")); + VOMSESLookupStrategy strategy = + new BaseVOMSESLookupStrategy(Arrays.asList("src/test/resources/vomses")); - DefaultVOMSServerInfoStore store = new DefaultVOMSServerInfoStore.Builder() - .lookupStrategy(strategy).build(); + DefaultVOMSServerInfoStore store = + new DefaultVOMSServerInfoStore.Builder().lookupStrategy(strategy).build(); assertEquals(3, store.getVOMSServerInfo("atlas").size()); assertEquals(2, store.getVOMSServerInfo("eumed").size()); @@ -37,11 +36,11 @@ public void testExistingVOMSESParsingSuccess() { @Test public void testVOMSESAliasLookup() { - VOMSESLookupStrategy strategy = new BaseVOMSESLookupStrategy( - Arrays.asList("src/test/resources/vomses-alias")); + VOMSESLookupStrategy strategy = + new BaseVOMSESLookupStrategy(Arrays.asList("src/test/resources/vomses-alias")); - DefaultVOMSServerInfoStore store = new DefaultVOMSServerInfoStore.Builder() - .lookupStrategy(strategy).build(); + DefaultVOMSServerInfoStore store = + new DefaultVOMSServerInfoStore.Builder().lookupStrategy(strategy).build(); assertEquals(3, store.getVOMSServerInfo("atlas").size()); assertEquals(2, store.getVOMSServerInfo("eumed").size()); @@ -53,17 +52,16 @@ public void testVOMSESAliasLookup() { Assert.assertFalse(infos.isEmpty()); Assert.assertEquals(2, infos.size()); - } @Test public void testVOMSESSingleCharAliasLookup() { - VOMSESLookupStrategy strategy = new BaseVOMSESLookupStrategy( - Arrays.asList("src/test/resources/vomses-alias-singlechar")); + VOMSESLookupStrategy strategy = + new BaseVOMSESLookupStrategy(Arrays.asList("src/test/resources/vomses-alias-singlechar")); - DefaultVOMSServerInfoStore store = new DefaultVOMSServerInfoStore.Builder() - .lookupStrategy(strategy).build(); + DefaultVOMSServerInfoStore store = + new DefaultVOMSServerInfoStore.Builder().lookupStrategy(strategy).build(); assertEquals(1, store.getVOMSServerInfo("atlas").size()); @@ -74,6 +72,5 @@ public void testVOMSESSingleCharAliasLookup() { Assert.assertFalse(infos.isEmpty()); Assert.assertEquals(1, infos.size()); - } } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACGeneration.java b/src/test/java/org/italiangrid/voms/test/ac/TestACGeneration.java index 5546095..d8d5cb4 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACGeneration.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACGeneration.java @@ -12,6 +12,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import eu.emi.security.authn.x509.impl.OpensslCertChainValidator; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; +import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; +import eu.emi.security.authn.x509.proxy.ProxyGenerator; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -22,11 +27,11 @@ import java.security.SignatureException; import java.security.cert.CRLException; import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; -import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -34,7 +39,6 @@ import java.util.List; import java.util.Set; import java.util.function.Supplier; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.operator.OperatorCreationException; @@ -55,12 +59,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.impl.OpensslCertChainValidator; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; -import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; -import eu.emi.security.authn.x509.proxy.ProxyGenerator; - public class TestACGeneration { static final String keyPassword = "pass"; @@ -89,11 +87,10 @@ public class TestACGeneration { static final String testCaCrl = "src/test/resources/trust-anchors/igi_test_ca.crl"; - static final List defaultFQANs = Arrays.asList("/test.vo", - "/test.vo/G1", "/test.vo/G2"); + static final List defaultFQANs = Arrays.asList("/test.vo", "/test.vo/G1", "/test.vo/G2"); - final List defaultGAs = Arrays.asList( - buildGA("test", "value", defaultVO), buildGA("test2", "value", defaultVO)); + final List defaultGAs = + Arrays.asList(buildGA("test", "value", defaultVO), buildGA("test2", "value", defaultVO)); static PEMCredential aaCredential = null; static PEMCredential aaCredential2 = null; @@ -111,52 +108,70 @@ public class TestACGeneration { static VOMSACGenerator defaultGenerator; @BeforeClass - static public void classTestSetup() throws KeyStoreException, - CertificateException, FileNotFoundException, IOException, CRLException { - - aaCredential = new PEMCredential(new FileInputStream(aaKey), - new FileInputStream(aaCert), (char[]) null); - - aaCredential2 = new PEMCredential(new FileInputStream(aaKey2), - new FileInputStream(aaCert2), (char[]) null); - - expiredCredential = new PEMCredential(new FileInputStream(expiredKey), - new FileInputStream(expiredCert), keyPassword.toCharArray()); - - revokedCredential = new PEMCredential(new FileInputStream(revokedKey), - new FileInputStream(revokedCert), keyPassword.toCharArray()); - - holderCredential = new PEMCredential(new FileInputStream(holderKey), - new FileInputStream(holderCert), keyPassword.toCharArray()); + public static void classTestSetup() + throws KeyStoreException, + CertificateException, + FileNotFoundException, + IOException, + CRLException { + + aaCredential = + new PEMCredential(new FileInputStream(aaKey), new FileInputStream(aaCert), (char[]) null); + + aaCredential2 = + new PEMCredential(new FileInputStream(aaKey2), new FileInputStream(aaCert2), (char[]) null); + + expiredCredential = + new PEMCredential( + new FileInputStream(expiredKey), + new FileInputStream(expiredCert), + keyPassword.toCharArray()); + + revokedCredential = + new PEMCredential( + new FileInputStream(revokedKey), + new FileInputStream(revokedCert), + keyPassword.toCharArray()); + + holderCredential = + new PEMCredential( + new FileInputStream(holderKey), + new FileInputStream(holderCert), + keyPassword.toCharArray()); trustStore = new DefaultVOMSTrustStore(Arrays.asList(vomsdir)); certValidator = new OpensslCertChainValidator(trustAnchorsDir); - final String expirationMessage = String.format( - "Certificate has expired on: %s", expiredCredential.getCertificate() - .getNotAfter()); + final String expirationMessage = + String.format( + "Certificate has expired on: %s", expiredCredential.getCertificate().getNotAfter()); expiredCertErrorMessage = newErrorMessage(canlError, expirationMessage); - expiredCertCRLErrorMessage = newErrorMessage( - canlError, - "CRL for an expired certificate was not resolved Cause: No CRLs found for issuer \"cn=Test CA,o=IGI,c=IT\""); - - final Date revocationDate = ((Supplier) () -> { - try (FileInputStream fis = new FileInputStream(testCaCrl)) { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509CRL crl = (X509CRL) cf.generateCRL(fis); - Set revokedCertificates = crl.getRevokedCertificates(); - X509CRLEntry entry = revokedCertificates.iterator().next(); - return entry.getRevocationDate(); - } catch (CertificateException | CRLException | IOException e) { - throw new RuntimeException(e.getMessage()); - } - }).get(); - - final String revocationMessage = String.format( - "Certificate was revoked at: " - + "%s, the reason reported is: unspecified", revocationDate); + expiredCertCRLErrorMessage = + newErrorMessage( + canlError, + "CRL for an expired certificate was not resolved Cause: No CRLs found for issuer \"cn=Test CA,o=IGI,c=IT\""); + + final Date revocationDate = + ((Supplier) + () -> { + try (FileInputStream fis = new FileInputStream(testCaCrl)) { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509CRL crl = (X509CRL) cf.generateCRL(fis); + Set revokedCertificates = crl.getRevokedCertificates(); + X509CRLEntry entry = revokedCertificates.iterator().next(); + return entry.getRevocationDate(); + } catch (CertificateException | CRLException | IOException e) { + throw new RuntimeException(e.getMessage()); + } + }) + .get(); + + final String revocationMessage = + String.format( + "Certificate was revoked at: " + "%s, the reason reported is: unspecified", + revocationDate); revokedCertErrorMessage = newErrorMessage(canlError, revocationMessage); @@ -164,13 +179,17 @@ static public void classTestSetup() throws KeyStoreException, } @AfterClass - static public void classTestShutdown() { + public static void classTestShutdown() { certValidator.dispose(); } - private AttributeCertificate createAC(PEMCredential aaCredential, - List fqans, List gas, String vo, String host) { + private AttributeCertificate createAC( + PEMCredential aaCredential, + List fqans, + List gas, + String vo, + String host) { VOMSACGenerator gen = new VOMSACGenerator(aaCredential); @@ -180,9 +199,18 @@ private AttributeCertificate createAC(PEMCredential aaCredential, cal.add(Calendar.HOUR, 12); Date expiration = cal.getTime(); - X509AttributeCertificateHolder ac = gen.generateVOMSAttributeCertificate( - fqans, gas, null, holderCredential.getCertificate(), BigInteger.ONE, now, - expiration, vo, host, port); + X509AttributeCertificateHolder ac = + gen.generateVOMSAttributeCertificate( + fqans, + gas, + null, + holderCredential.getCertificate(), + BigInteger.ONE, + now, + expiration, + vo, + host, + port); return ac.toASN1Structure(); } @@ -199,25 +227,26 @@ private VOMSGenericAttribute buildGA(String name, String value, String context) } @Test - public void testGeneratedACParsing() throws KeyStoreException, - CertificateException, FileNotFoundException, IOException, - OperatorCreationException { - - AttributeCertificate ac = createAC(aaCredential, defaultFQANs, defaultGAs, - defaultVO, defaultHost); + public void testGeneratedACParsing() + throws KeyStoreException, + CertificateException, + FileNotFoundException, + IOException, + OperatorCreationException { + + AttributeCertificate ac = + createAC(aaCredential, defaultFQANs, defaultGAs, defaultVO, defaultHost); VOMSAttribute attrs = VOMSACUtils.deserializeVOMSAttributes(ac); // Check holder - assertEquals(holderCredential.getCertificate().getSubjectX500Principal(), - attrs.getHolder()); + assertEquals(holderCredential.getCertificate().getSubjectX500Principal(), attrs.getHolder()); // Check holder serial number - assertEquals(holderCredential.getCertificate().getSerialNumber(), - attrs.getHolderSerialNumber()); + assertEquals( + holderCredential.getCertificate().getSerialNumber(), attrs.getHolderSerialNumber()); // Check issuer - assertEquals(aaCredential.getCertificate().getSubjectX500Principal(), - attrs.getIssuer()); + assertEquals(aaCredential.getCertificate().getSubjectX500Principal(), attrs.getIssuer()); // Check policyAuthority assertEquals(defaultVO, attrs.getVO()); @@ -234,7 +263,6 @@ public void testGeneratedACParsing() throws KeyStoreException, // Check targets assertTrue(attrs.getTargets().isEmpty()); - } @Test @@ -242,69 +270,80 @@ public void testACValidation() { ValidationResultChecker c = new ValidationResultChecker(true); - VOMSACValidator validator = VOMSValidators.newValidator(trustStore, - certValidator, c); + VOMSACValidator validator = VOMSValidators.newValidator(trustStore, certValidator, c); - AttributeCertificate ac = createAC(aaCredential, defaultFQANs, defaultGAs, - defaultVO, defaultHost); - List validatedAttrs = validator.validateACs(Arrays - .asList(ac)); + AttributeCertificate ac = + createAC(aaCredential, defaultFQANs, defaultGAs, defaultVO, defaultHost); + List validatedAttrs = validator.validateACs(Arrays.asList(ac)); assertEquals(validatedAttrs.size(), 1); - } @Test public void testLSCValidationFailure() { - ValidationResultChecker c = new ValidationResultChecker(false, - newErrorMessage(lscDescriptionDoesntMatchAcCert), - newErrorMessage(aaCertNotFound)); - - VOMSACValidator validator = VOMSValidators.newValidator(trustStore, - certValidator, c); - AttributeCertificate ac = createAC(aaCredential2, - Arrays.asList("/test.vo.1"), defaultGAs, "test.vo.1", - "wilco.cnaf.infn.it"); - List validatedAttrs = validator.validateACs(Arrays - .asList(ac)); + ValidationResultChecker c = + new ValidationResultChecker( + false, + newErrorMessage(lscDescriptionDoesntMatchAcCert), + newErrorMessage(aaCertNotFound)); + + VOMSACValidator validator = VOMSValidators.newValidator(trustStore, certValidator, c); + AttributeCertificate ac = + createAC( + aaCredential2, + Arrays.asList("/test.vo.1"), + defaultGAs, + "test.vo.1", + "wilco.cnaf.infn.it"); + List validatedAttrs = validator.validateACs(Arrays.asList(ac)); assertEquals(validatedAttrs.size(), 0); } @Test - public void testExpiredAACertValidationFailure() - throws OperatorCreationException { - - ValidationResultChecker c = new ValidationResultChecker(false, - expiredCertErrorMessage, expiredCertCRLErrorMessage, - newErrorMessage(invalidAcCert), newErrorMessage(aaCertNotFound)); - - VOMSACValidator validator = VOMSValidators.newValidator(trustStore, - certValidator, c); - - AttributeCertificate ac = createAC(expiredCredential, - Arrays.asList("/test.vo"), defaultGAs, defaultVO, - "test-expired.cnaf.infn.it"); - - List validatedAttrs = validator.validateACs(Arrays - .asList(ac)); + public void testExpiredAACertValidationFailure() throws OperatorCreationException { + + ValidationResultChecker c = + new ValidationResultChecker( + false, + expiredCertErrorMessage, + expiredCertCRLErrorMessage, + newErrorMessage(invalidAcCert), + newErrorMessage(aaCertNotFound)); + + VOMSACValidator validator = VOMSValidators.newValidator(trustStore, certValidator, c); + + AttributeCertificate ac = + createAC( + expiredCredential, + Arrays.asList("/test.vo"), + defaultGAs, + defaultVO, + "test-expired.cnaf.infn.it"); + + List validatedAttrs = validator.validateACs(Arrays.asList(ac)); assertEquals(validatedAttrs.size(), 0); } @Test public void testRevokedAACertValidationFailure() { - ValidationResultChecker c = new ValidationResultChecker(false, - revokedCertErrorMessage, newErrorMessage(invalidAcCert), - newErrorMessage(aaCertNotFound)); - - VOMSACValidator validator = VOMSValidators.newValidator(trustStore, - certValidator, c); - AttributeCertificate ac = createAC(revokedCredential, - Arrays.asList("/test.vo"), defaultGAs, defaultVO, - "test-revoked.cnaf.infn.it"); - List validatedAttrs = validator.validateACs(Arrays - .asList(ac)); + ValidationResultChecker c = + new ValidationResultChecker( + false, + revokedCertErrorMessage, + newErrorMessage(invalidAcCert), + newErrorMessage(aaCertNotFound)); + + VOMSACValidator validator = VOMSValidators.newValidator(trustStore, certValidator, c); + AttributeCertificate ac = + createAC( + revokedCredential, + Arrays.asList("/test.vo"), + defaultGAs, + defaultVO, + "test-revoked.cnaf.infn.it"); + List validatedAttrs = validator.validateACs(Arrays.asList(ac)); assertEquals(validatedAttrs.size(), 0); } @@ -313,17 +352,15 @@ public void testSuccesfullACExtractionFromProxy() { ValidationResultChecker c = new ValidationResultChecker(true); - VOMSACValidator validator = VOMSValidators.newValidator(trustStore, - certValidator, c); + VOMSACValidator validator = VOMSValidators.newValidator(trustStore, certValidator, c); - AttributeCertificate ac = createAC(aaCredential, defaultFQANs, defaultGAs, - defaultVO, defaultHost); + AttributeCertificate ac = + createAC(aaCredential, defaultFQANs, defaultGAs, defaultVO, defaultHost); X509Certificate[] chain; try { - chain = createVOMSProxy(holderCredential, - new AttributeCertificate[] { ac }); + chain = createVOMSProxy(holderCredential, new AttributeCertificate[] {ac}); } catch (Exception e) { throw new VOMSError("Error generating VOMS proxy:" + e.getMessage(), e); } @@ -332,17 +369,18 @@ public void testSuccesfullACExtractionFromProxy() { assertEquals(1, attrs.size()); } - private X509Certificate[] createVOMSProxy(PEMCredential holder, - AttributeCertificate[] acs) throws InvalidKeyException, - CertificateParsingException, SignatureException, NoSuchAlgorithmException, - IOException { + private X509Certificate[] createVOMSProxy(PEMCredential holder, AttributeCertificate[] acs) + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { - ProxyCertificateOptions proxyOptions = new ProxyCertificateOptions( - holder.getCertificateChain()); + ProxyCertificateOptions proxyOptions = + new ProxyCertificateOptions(holder.getCertificateChain()); proxyOptions.setAttributeCertificates(acs); - ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, - holder.getKey()); + ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, holder.getKey()); return proxy.getCertificateChain(); } @@ -353,12 +391,10 @@ class ValidationResultChecker implements ValidationResultListener { final List expectedErrorMessages; boolean expectedValidationResult; - public ValidationResultChecker(boolean valid, - VOMSValidationErrorMessage... expectedMessages) { + public ValidationResultChecker(boolean valid, VOMSValidationErrorMessage... expectedMessages) { expectedValidationResult = valid; expectedErrorMessages = Arrays.asList(expectedMessages); - } private String errorMessage(String message, VOMSValidationResult result) { @@ -369,33 +405,37 @@ private String errorMessage(String message, VOMSValidationResult result) { public void notifyValidationResult(VOMSValidationResult result) { assertEquals( - errorMessage("ValidationResult validity check failed.", result), - expectedValidationResult, result.isValid()); + errorMessage("ValidationResult validity check failed.", result), + expectedValidationResult, + result.isValid()); - assertEquals(errorMessage("ValidationResult error message size check " - + "failed.", result), expectedErrorMessages.size(), result - .getValidationErrors().size()); + assertEquals( + errorMessage("ValidationResult error message size check " + "failed.", result), + expectedErrorMessages.size(), + result.getValidationErrors().size()); - List errorMessages = new ArrayList( - result.getValidationErrors()); + List errorMessages = + new ArrayList(result.getValidationErrors()); for (VOMSValidationErrorMessage expectedMessage : expectedErrorMessages) { - String failureMessage = errorMessage(String.format( - "<%s> was not found in error messages. Error messages: <%s>", - expectedMessage, result.getValidationErrors()), result); + String failureMessage = + errorMessage( + String.format( + "<%s> was not found in error messages. Error messages: <%s>", + expectedMessage, result.getValidationErrors()), + result); - assertTrue(failureMessage, - result.getValidationErrors().contains(expectedMessage)); + assertTrue(failureMessage, result.getValidationErrors().contains(expectedMessage)); } if (errorMessages.size() > 0) { errorMessages.removeAll(expectedErrorMessages); - assertTrue(errorMessage("ValidationResult check failed. " - + "Got more error messages than expected.", result), - errorMessages.isEmpty()); + assertTrue( + errorMessage( + "ValidationResult check failed. " + "Got more error messages than expected.", result), + errorMessages.isEmpty()); } - } -} \ No newline at end of file +} diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACGenerationParams.java b/src/test/java/org/italiangrid/voms/test/ac/TestACGenerationParams.java index 0b542ed..7350973 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACGenerationParams.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACGenerationParams.java @@ -14,7 +14,6 @@ import java.time.ZoneOffset; import java.time.format.DateTimeParseException; import java.util.Date; - import org.italiangrid.voms.request.impl.ACGenerationParams; import org.italiangrid.voms.request.impl.FakeVOMSACServiceProperties; import org.italiangrid.voms.util.TimeUtils; @@ -27,48 +26,49 @@ public class TestACGenerationParams { public static final String JAN_FIRST_2020_00_00_10_S = "2020-01-01T00:00:10"; public static final Date JAN_FIRST_2020_00_00_00 = - Date.from(LocalDateTime.parse(JAN_FIRST_2020_00_00_00_S, TimeUtils.DATE_FORMATTER) - .toInstant(ZoneOffset.UTC)); + Date.from( + LocalDateTime.parse(JAN_FIRST_2020_00_00_00_S, TimeUtils.DATE_FORMATTER) + .toInstant(ZoneOffset.UTC)); public static final Date JAN_FIRST_2020_00_00_10 = - Date.from(LocalDateTime.parse(JAN_FIRST_2020_00_00_10_S, TimeUtils.DATE_FORMATTER) - .toInstant(ZoneOffset.UTC)); + Date.from( + LocalDateTime.parse(JAN_FIRST_2020_00_00_10_S, TimeUtils.DATE_FORMATTER) + .toInstant(ZoneOffset.UTC)); @After public void after() { + // Cleanup system properties for (FakeVOMSACServiceProperties p : FakeVOMSACServiceProperties.values()) { System.getProperties().remove(p.getPropertyName()); } } - @Test public void testNoPropertySetsSucceeds() { ACGenerationParams.fromSystemProperties(); - } @Test(expected = NullPointerException.class) public void testNotAfterNullDateRaisesNullPointerException() { + System.setProperty(NOT_AFTER.getPropertyName(), null); ACGenerationParams.fromSystemProperties(); } @Test(expected = NullPointerException.class) public void testNotBeforeNullDateRaisesNullPointerException() { + System.setProperty(NOT_BEFORE.getPropertyName(), null); ACGenerationParams.fromSystemProperties(); } - @Test(expected = DateTimeParseException.class) public void testNotAfterDateParsingError() { System.setProperty(NOT_AFTER.getPropertyName(), "ciccio"); ACGenerationParams.fromSystemProperties(); - } @Test(expected = DateTimeParseException.class) @@ -78,9 +78,9 @@ public void testNotBeforeDateParsingError() { ACGenerationParams.fromSystemProperties(); } - @Test public void testDateParsing() { + System.setProperty(NOT_BEFORE.getPropertyName(), JAN_FIRST_2020_00_00_00_S); System.setProperty(NOT_AFTER.getPropertyName(), JAN_FIRST_2020_00_00_10_S); ACGenerationParams params = ACGenerationParams.fromSystemProperties(); @@ -90,13 +90,14 @@ public void testDateParsing() { @Test public void testGaParsing() { + System.setProperty(GAS.getPropertyName(), "one = uno, two = due, three = tre"); ACGenerationParams params = ACGenerationParams.fromSystemProperties(); assertThat(params.getGas().size(), equalTo(3)); assertThat(params.getGas().get(0).getName(), equalTo("one")); assertThat(params.getGas().get(0).getValue(), equalTo("uno")); assertThat(params.getGas().get(0).getContext(), equalTo("test")); - + assertThat(params.getGas().get(1).getName(), equalTo("two")); assertThat(params.getGas().get(1).getValue(), equalTo("due")); assertThat(params.getGas().get(1).getContext(), equalTo("test")); @@ -105,7 +106,4 @@ public void testGaParsing() { assertThat(params.getGas().get(2).getValue(), equalTo("tre")); assertThat(params.getGas().get(2).getContext(), equalTo("test")); } - - - } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACParser.java b/src/test/java/org/italiangrid/voms/test/ac/TestACParser.java index 62a1294..06b539f 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACParser.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACParser.java @@ -4,37 +4,32 @@ package org.italiangrid.voms.test.ac; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; import java.io.IOException; import java.security.KeyStoreException; import java.security.cert.CertificateException; import java.util.Collections; import java.util.List; - -import org.junit.Assert; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.ac.impl.DefaultVOMSACParser; import org.italiangrid.voms.test.utils.Fixture; import org.italiangrid.voms.test.utils.Utils; import org.italiangrid.voms.test.utils.VOMSAA; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; - public class TestACParser implements Fixture { static VOMSAA aa; static PEMCredential holder; @BeforeClass - public static void setup() throws KeyStoreException, CertificateException, - IOException { + public static void setup() throws KeyStoreException, CertificateException, IOException { aa = Utils.getVOMSAA(); - } @Test @@ -69,8 +64,7 @@ public void testEmptyFqansParsing() throws Exception { try { parser.parse(proxy.getCertificateChain()); } catch (VOMSError e) { - Assert - .assertEquals( + Assert.assertEquals( "Non conformant VOMS Attribute certificate: unsupported attribute values encoding.", e.getMessage()); return; diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACParsingContext.java b/src/test/java/org/italiangrid/voms/test/ac/TestACParsingContext.java index 1a3084e..4e043a4 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACParsingContext.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACParsingContext.java @@ -11,7 +11,6 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.ac.ACParsingContext; import org.italiangrid.voms.test.utils.Fixture; @@ -39,7 +38,5 @@ public void testGettersAndSetters() { assertNull(ctxt.getCertChain()); assertEquals(emptyAttrs, ctxt.getACs()); assertEquals(2, ctxt.getCertChainPostion()); - } - } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACSupport.java b/src/test/java/org/italiangrid/voms/test/ac/TestACSupport.java index cc43ba6..cd6a33a 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACSupport.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACSupport.java @@ -4,14 +4,13 @@ package org.italiangrid.voms.test.ac; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyStoreException; import java.security.cert.CertificateException; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class TestACSupport { static final String keyPassword = "pass"; @@ -37,15 +36,19 @@ public class TestACSupport { static final String vomsdir = "src/test/resources/vomsdir"; static final String trustAnchorsDir = "src/test/resources/trust-anchors"; - + static PEMCredential aaCredential; static PEMCredential holderCredential; - - static void initializeCredentials() throws KeyStoreException, CertificateException, FileNotFoundException, IOException { - aaCredential = new PEMCredential(new FileInputStream(aaKey), - new FileInputStream(aaCert), (char[]) null); - holderCredential = new PEMCredential(new FileInputStream(holderKey), - new FileInputStream(holderCert), keyPassword.toCharArray()); - } + static void initializeCredentials() + throws KeyStoreException, CertificateException, FileNotFoundException, IOException { + + aaCredential = + new PEMCredential(new FileInputStream(aaKey), new FileInputStream(aaCert), (char[]) null); + holderCredential = + new PEMCredential( + new FileInputStream(holderKey), + new FileInputStream(holderCert), + keyPassword.toCharArray()); + } } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestACValidator.java b/src/test/java/org/italiangrid/voms/test/ac/TestACValidator.java index a0f7a87..2c7c369 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestACValidator.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestACValidator.java @@ -7,6 +7,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; @@ -16,7 +19,6 @@ import java.util.Date; import java.util.EnumSet; import java.util.List; - import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.VOMSValidators; import org.italiangrid.voms.ac.VOMSACValidator; @@ -33,10 +35,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; - public class TestACValidator implements Fixture { static PEMCredential holder, holder2; @@ -48,7 +46,6 @@ public static void setup() throws KeyStoreException, CertificateException, IOExc holder = Utils.getTestUserCredential(); holder2 = Utils.getTest1UserCredential(); validator = Utils.getVOMSValidator(); - } @Test @@ -59,7 +56,6 @@ public void testValidityCheckSuccess() throws Exception { assertTrue(results.size() == 1); assertTrue(results.get(0).isValid()); assertEquals(defaultVOFqans, results.get(0).getAttributes().getFQANs()); - } @Test @@ -68,10 +64,11 @@ public void testTimeValidityFailure() throws Exception { Date start = Utils.getDate(1975, 12, 1); Date end = Utils.getDate(1975, 12, 2); - ProxyCertificate proxy = Utils.getVOMSAA() - .setAcNotBefore(start) - .setAcNotAfter(end) - .createVOMSProxy(holder, defaultVOFqans); + ProxyCertificate proxy = + Utils.getVOMSAA() + .setAcNotBefore(start) + .setAcNotAfter(end) + .createVOMSProxy(holder, defaultVOFqans); List results = validator.validateWithResult(proxy.getCertificateChain()); @@ -112,29 +109,31 @@ public void testSignatureCheckFailure() throws Exception { Assert.assertFalse(result.isValid()); Assert.assertTrue(result.getValidationErrors().size() == 2); - Assert.assertEquals(VOMSValidationErrorCode.lscFileNotFound, + Assert.assertEquals( + VOMSValidationErrorCode.lscFileNotFound, result.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals(VOMSValidationErrorCode.other, - result.getValidationErrors().get(1).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.other, result.getValidationErrors().get(1).getErrorCode()); Assert.assertEquals( "Validation error: AuthorityKeyIdentifier in the AC does not match AA certificate subject key identifier!", result.getValidationErrors().get(1).getMessage()); - } @Test public void testExpiredAACredFailure() throws Exception { - ProxyCertificate proxy = Utils.getVOMSAA() - .setCredential(Utils.getExpiredCredential()) - .createVOMSProxy(holder, defaultVOFqans); + ProxyCertificate proxy = + Utils.getVOMSAA() + .setCredential(Utils.getExpiredCredential()) + .createVOMSProxy(holder, defaultVOFqans); X509CertChainValidatorExt certValidator = Utils.getCertificateValidator(); - VOMSACValidator validator = VOMSValidators.newValidator( - new DefaultVOMSTrustStore(Arrays.asList(vomsdir_expired_aa_cert)), certValidator); + VOMSACValidator validator = + VOMSValidators.newValidator( + new DefaultVOMSTrustStore(Arrays.asList(vomsdir_expired_aa_cert)), certValidator); List results = validator.validateWithResult(proxy.getCertificateChain()); @@ -144,21 +143,21 @@ public void testExpiredAACredFailure() throws Exception { Assert.assertEquals(4, result.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.lscFileNotFound, + Assert.assertEquals( + VOMSValidationErrorCode.lscFileNotFound, result.getValidationErrors().get(0).getErrorCode()); // Certificate expired notification from CAnL - Assert.assertEquals(VOMSValidationErrorCode.canlError, - result.getValidationErrors().get(1).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.canlError, result.getValidationErrors().get(1).getErrorCode()); // This is probably a bug in CAnL: No valid CRL was found for the CA which // issued the chain. But this happens only when validating the expired cert. - Assert.assertEquals(VOMSValidationErrorCode.canlError, - result.getValidationErrors().get(2).getErrorCode()); - - Assert.assertEquals(VOMSValidationErrorCode.invalidAaCert, - result.getValidationErrors().get(3).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.canlError, result.getValidationErrors().get(2).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.invalidAaCert, result.getValidationErrors().get(3).getErrorCode()); } @Test @@ -177,7 +176,8 @@ public void testEmptyACCertsExtensionSuccess() throws Exception { Assert.assertTrue(r.isValid()); Assert.assertEquals(1, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.emptyAcCertsExtension, + Assert.assertEquals( + VOMSValidationErrorCode.emptyAcCertsExtension, r.getValidationErrors().get(0).getErrorCode()); } @@ -205,12 +205,12 @@ public void testMissingACCertsExtensionFailure() throws Exception { Assert.assertEquals(2, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.emptyAcCertsExtension, + Assert.assertEquals( + VOMSValidationErrorCode.emptyAcCertsExtension, r.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals(VOMSValidationErrorCode.aaCertNotFound, - r.getValidationErrors().get(1).getErrorCode()); - + Assert.assertEquals( + VOMSValidationErrorCode.aaCertNotFound, r.getValidationErrors().get(1).getErrorCode()); } @Test @@ -235,11 +235,12 @@ public void testInvalidLSCSignatureFailure() throws Exception { Assert.assertFalse(r.isValid()); Assert.assertEquals(2, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.acCertFailsSignatureVerification, + Assert.assertEquals( + VOMSValidationErrorCode.acCertFailsSignatureVerification, r.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals(VOMSValidationErrorCode.aaCertNotFound, - r.getValidationErrors().get(1).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.aaCertNotFound, r.getValidationErrors().get(1).getErrorCode()); } @Test @@ -259,8 +260,8 @@ public void testUnknownCriticalExtensionFailure() throws Exception { Assert.assertFalse(r.isValid()); Assert.assertEquals(1, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.other, - r.getValidationErrors().get(0).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.other, r.getValidationErrors().get(0).getErrorCode()); Assert.assertEquals( "Validation error: unknown critical extension found in VOMS AC: 1.3.6.1.4.1.8005.100.120.82", @@ -283,10 +284,11 @@ public void testCriticalAKIDFailure() throws Exception { Assert.assertFalse(r.isValid()); - Assert.assertEquals(VOMSValidationErrorCode.other, - r.getValidationErrors().get(0).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.other, r.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals("Validation error: AuthorityKeyIdentifier AC extension cannot be critical!", + Assert.assertEquals( + "Validation error: AuthorityKeyIdentifier AC extension cannot be critical!", r.getValidationErrors().get(0).getMessage()); } @@ -308,10 +310,11 @@ public void testCriticalNoRevAvailFailure() throws Exception { Assert.assertFalse(r.isValid()); - Assert.assertEquals(VOMSValidationErrorCode.other, - r.getValidationErrors().get(0).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.other, r.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals("Validation error: NoRevAvail AC extension cannot be critical!", + Assert.assertEquals( + "Validation error: NoRevAvail AC extension cannot be critical!", r.getValidationErrors().get(0).getMessage()); } @@ -331,8 +334,12 @@ public void testTargetValidationSuccess() throws Exception { } VOMSACValidator validator = Utils.getVOMSValidator(); - ProxyCertificate proxy = aa.createVOMSProxy(Utils.getTestUserCredential(), - Arrays.asList("/test.vo"), null, Arrays.asList(localhostName)); + ProxyCertificate proxy = + aa.createVOMSProxy( + Utils.getTestUserCredential(), + Arrays.asList("/test.vo"), + null, + Arrays.asList(localhostName)); List results = validator.validateWithResult(proxy.getCertificateChain()); Assert.assertEquals(1, results.size()); @@ -347,8 +354,12 @@ public void testTargetValidationFailure() throws Exception { VOMSAA aa = Utils.getVOMSAA(); VOMSACValidator validator = Utils.getVOMSValidator(); - ProxyCertificate proxy = aa.createVOMSProxy(Utils.getTestUserCredential(), - Arrays.asList("/test.vo"), null, Arrays.asList("camaghe.cnaf.infn.it")); + ProxyCertificate proxy = + aa.createVOMSProxy( + Utils.getTestUserCredential(), + Arrays.asList("/test.vo"), + null, + Arrays.asList("camaghe.cnaf.infn.it")); List results = validator.validateWithResult(proxy.getCertificateChain()); Assert.assertEquals(1, results.size()); @@ -356,9 +367,9 @@ public void testTargetValidationFailure() throws Exception { Assert.assertFalse(r.isValid()); Assert.assertEquals(1, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.localhostDoesntMatchAcTarget, + Assert.assertEquals( + VOMSValidationErrorCode.localhostDoesntMatchAcTarget, r.getValidationErrors().get(0).getErrorCode()); - } @Test @@ -366,16 +377,22 @@ public void testResolveHostnameException() throws Exception { VOMSAA aa = Utils.getVOMSAA(); - VOMSACValidator validator = Utils.getVOMSValidator(new LocalHostnameResolver() { + VOMSACValidator validator = + Utils.getVOMSValidator( + new LocalHostnameResolver() { - public String resolveLocalHostname() throws UnknownHostException { + public String resolveLocalHostname() throws UnknownHostException { - throw new UnknownHostException("misconfigured machine!"); - } - }); + throw new UnknownHostException("misconfigured machine!"); + } + }); - ProxyCertificate proxy = aa.createVOMSProxy(Utils.getTestUserCredential(), - Arrays.asList("/test.vo"), null, Arrays.asList("camaghe.cnaf.infn.it")); + ProxyCertificate proxy = + aa.createVOMSProxy( + Utils.getTestUserCredential(), + Arrays.asList("/test.vo"), + null, + Arrays.asList("camaghe.cnaf.infn.it")); List results = validator.validateWithResult(proxy.getCertificateChain()); Assert.assertEquals(1, results.size()); @@ -383,10 +400,11 @@ public String resolveLocalHostname() throws UnknownHostException { Assert.assertFalse(r.isValid()); Assert.assertEquals(1, r.getValidationErrors().size()); - Assert.assertEquals(VOMSValidationErrorCode.other, - r.getValidationErrors().get(0).getErrorCode()); + Assert.assertEquals( + VOMSValidationErrorCode.other, r.getValidationErrors().get(0).getErrorCode()); - Assert.assertEquals("Validation error: Error resolving localhost name: misconfigured machine!", + Assert.assertEquals( + "Validation error: Error resolving localhost name: misconfigured machine!", r.getValidationErrors().get(0).getMessage()); } } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestFakeVOMSACService.java b/src/test/java/org/italiangrid/voms/test/ac/TestFakeVOMSACService.java index 72d0f65..db8bd19 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestFakeVOMSACService.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestFakeVOMSACService.java @@ -16,7 +16,6 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.asn1.VOMSACUtils; @@ -31,31 +30,35 @@ public class TestFakeVOMSACService extends TestACSupport { public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_DATE; - public static final Date JAN_FIRST_2010 = Date - .from(LocalDate.parse("2010-01-01", DATE_FORMATTER).atStartOfDay().toInstant(ZoneOffset.UTC)); + public static final Date JAN_FIRST_2010 = + Date.from( + LocalDate.parse("2010-01-01", DATE_FORMATTER).atStartOfDay().toInstant(ZoneOffset.UTC)); - public static final Date JAN_TEN_2010 = Date - .from(LocalDate.parse("2010-01-10", DATE_FORMATTER).atStartOfDay().toInstant(ZoneOffset.UTC)); + public static final Date JAN_TEN_2010 = + Date.from( + LocalDate.parse("2010-01-10", DATE_FORMATTER).atStartOfDay().toInstant(ZoneOffset.UTC)); @BeforeClass public static void suiteInit() throws KeyStoreException, CertificateException, FileNotFoundException, IOException { + initializeCredentials(); } @Test public void testFakeAcServiceCreation() { - ACGenerationParams params = ACGenerationParams.builder() - .vo("fake") - .fqan("/fake") - .notBefore(JAN_FIRST_2010) - .notAfter(JAN_TEN_2010) - .serialNo(189) - .build(); + ACGenerationParams params = + ACGenerationParams.builder() + .vo("fake") + .fqan("/fake") + .notBefore(JAN_FIRST_2010) + .notAfter(JAN_TEN_2010) + .serialNo(189) + .build(); - FakeVOMSACService acService = FakeVOMSACService.newInstance(aaCredential, params, - NullListener.INSTANCE); + FakeVOMSACService acService = + FakeVOMSACService.newInstance(aaCredential, params, NullListener.INSTANCE); VOMSACRequest req = new DefaultVOMSACRequest.Builder("test").build(); AttributeCertificate ac = acService.getVOMSAttributeCertificate(holderCredential, req); @@ -68,5 +71,4 @@ public void testFakeAcServiceCreation() { assertThat(attrs.getPrimaryFQAN(), equalTo("/fake")); assertThat(attrs.getVOMSAC().getSerialNumber(), equalTo(BigInteger.valueOf(189))); } - } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestGaParser.java b/src/test/java/org/italiangrid/voms/test/ac/TestGaParser.java index 0db7037..d0666f2 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestGaParser.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestGaParser.java @@ -10,55 +10,52 @@ import static org.italiangrid.voms.util.GaParser.parseGaString; import java.util.List; - import org.italiangrid.voms.VOMSGenericAttribute; import org.junit.Test; public class TestGaParser { - - @Test public void testEmptyString() { - + List result = parseGaString(""); assertThat(result.isEmpty(), equalTo(true)); - } - - @Test(expected=NullPointerException.class) + + @Test(expected = NullPointerException.class) public void testNullString() { - + parseGaString(null); } - + @Test public void testInvalidStrings() { - + assertThat(parseGaString("dsa").isEmpty(), equalTo(true)); assertThat(parseGaString("=, a == d").isEmpty(), equalTo(true)); } - + @Test public void testValidStrings() { + List gas = parseGaString("ciccio = paglia"); - + assertThat(gas.size(), equalTo(1)); - + assertThat(gas.get(0).getName(), equalTo("ciccio")); assertThat(gas.get(0).getValue(), equalTo("paglia")); assertThat(gas.get(0).getContext(), nullValue()); - - gas =parseGaString(" c= p , pippo =franco,a8_d2=789"); - + + gas = parseGaString(" c= p , pippo =franco,a8_d2=789"); + assertThat(gas.size(), equalTo(3)); - + assertThat(gas.get(0).getName(), equalTo("c")); assertThat(gas.get(0).getValue(), equalTo("p")); - + assertThat(gas.get(1).getName(), equalTo("pippo")); assertThat(gas.get(1).getValue(), equalTo("franco")); - + assertThat(gas.get(2).getName(), equalTo("a8_d2")); assertThat(gas.get(2).getValue(), equalTo("789")); } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestNoExtensionValidation.java b/src/test/java/org/italiangrid/voms/test/ac/TestNoExtensionValidation.java index 12eb0d5..bc6514c 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestNoExtensionValidation.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestNoExtensionValidation.java @@ -4,57 +4,59 @@ package org.italiangrid.voms.test.ac; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; +import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; +import eu.emi.security.authn.x509.proxy.ProxyGenerator; +import eu.emi.security.authn.x509.proxy.ProxyType; +import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.security.cert.CertificateParsingException; import java.util.List; - -import org.junit.Assert; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.ac.VOMSACValidator; import org.italiangrid.voms.test.utils.Fixture; import org.italiangrid.voms.test.utils.Utils; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; -import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; -import eu.emi.security.authn.x509.proxy.ProxyGenerator; -import eu.emi.security.authn.x509.proxy.ProxyType; -import java.io.IOException; +public class TestNoExtensionValidation implements Fixture { -public class TestNoExtensionValidation implements Fixture{ + PEMCredential cred; - PEMCredential cred; + @Before + public void setUp() throws Exception { - @Before - public void setUp() throws Exception { - cred = new PEMCredential(holderKey, holderCert, keyPassword.toCharArray()); - } + cred = new PEMCredential(holderKey, holderCert, keyPassword.toCharArray()); + } - @After - public void tearDown() throws Exception { - cred = null; - } + @After + public void tearDown() throws Exception { - @Test - public void testNoExtensionValidation() throws InvalidKeyException, CertificateParsingException, - SignatureException, NoSuchAlgorithmException, IOException { + cred = null; + } - ProxyCertificateOptions options = new ProxyCertificateOptions(cred.getCertificateChain()); - options.setType(ProxyType.LEGACY); + @Test + public void testNoExtensionValidation() + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { - ProxyCertificate proxy = ProxyGenerator.generate(options, cred.getKey()); + ProxyCertificateOptions options = new ProxyCertificateOptions(cred.getCertificateChain()); + options.setType(ProxyType.LEGACY); - VOMSACValidator validator = Utils.getVOMSValidator(); - List attrs = validator.validate(proxy.getCertificateChain()); + ProxyCertificate proxy = ProxyGenerator.generate(options, cred.getKey()); - Assert.assertNotNull(attrs); - Assert.assertTrue(attrs.isEmpty()); + VOMSACValidator validator = Utils.getVOMSValidator(); + List attrs = validator.validate(proxy.getCertificateChain()); - } + Assert.assertNotNull(attrs); + Assert.assertTrue(attrs.isEmpty()); + } } diff --git a/src/test/java/org/italiangrid/voms/test/ac/TestVOMSValidationResult.java b/src/test/java/org/italiangrid/voms/test/ac/TestVOMSValidationResult.java index 95aa8ee..ccedd4a 100644 --- a/src/test/java/org/italiangrid/voms/test/ac/TestVOMSValidationResult.java +++ b/src/test/java/org/italiangrid/voms/test/ac/TestVOMSValidationResult.java @@ -21,9 +21,6 @@ public void testGettersAndSetters() { assertTrue(r.getValidationErrors().isEmpty()); assertEquals( - "VOMSValidationResult [valid=false, validationErrors=[], attributes=null]", - r.toString()); - + "VOMSValidationResult [valid=false, validationErrors=[], attributes=null]", r.toString()); } - } diff --git a/src/test/java/org/italiangrid/voms/test/cred/TestLoadCredential.java b/src/test/java/org/italiangrid/voms/test/cred/TestLoadCredential.java index e229872..dde2577 100644 --- a/src/test/java/org/italiangrid/voms/test/cred/TestLoadCredential.java +++ b/src/test/java/org/italiangrid/voms/test/cred/TestLoadCredential.java @@ -4,7 +4,9 @@ package org.italiangrid.voms.test.cred; +import eu.emi.security.authn.x509.X509Credential; import eu.emi.security.authn.x509.helpers.PasswordSupplier; +import eu.emi.security.authn.x509.impl.X500NameUtils; import org.italiangrid.voms.credential.impl.AbstractLoadCredentialsStrategy; import org.italiangrid.voms.credential.impl.DefaultLoadCredentialsStrategy; import org.italiangrid.voms.util.FilePermissionHelper; @@ -12,9 +14,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.X500NameUtils; - public class TestLoadCredential { public static final String keyPassword = "pass"; @@ -34,10 +33,8 @@ public class TestLoadCredential { @BeforeClass public static void setupFilePermissions() { - FilePermissionHelper.setPrivateKeyPermissions(pemCredsHome - + "/.globus/userkey.pem"); - FilePermissionHelper.setPKCS12Permissions(pkcs12CredsHome - + "/.globus/usercred.p12"); + FilePermissionHelper.setPrivateKeyPermissions(pemCredsHome + "/.globus/userkey.pem"); + FilePermissionHelper.setPKCS12Permissions(pkcs12CredsHome + "/.globus/usercred.p12"); } static class TestPasswordFinder implements PasswordSupplier { @@ -59,8 +56,7 @@ public char[] getPassword() { @Test public void testNoCredentialsFoundSuccess() { - AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy( - emptyHome); + AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy(emptyHome); X509Credential cred = strategy.loadCredentials(new NullPasswordSupplier()); Assert.assertNull(cred); } @@ -68,8 +64,7 @@ public void testNoCredentialsFoundSuccess() { @Test public void testNoCredentialsFoundEmptyGlobusSuccess() { - AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy( - emptyGlobusHome); + AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy(emptyGlobusHome); X509Credential cred = strategy.loadCredentials(new NullPasswordSupplier()); Assert.assertNull(cred); } @@ -77,23 +72,20 @@ public void testNoCredentialsFoundEmptyGlobusSuccess() { @Test public void testPEMCredentialLoadingSuccess() { - AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy( - pemCredsHome); + AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy(pemCredsHome); X509Credential cred = strategy.loadCredentials(new TestPasswordFinder()); Assert.assertNotNull(cred); - Assert.assertTrue(X500NameUtils.equal(cred.getCertificate() - .getSubjectX500Principal(), TEST_CERT_SUBJECT)); + Assert.assertTrue( + X500NameUtils.equal(cred.getCertificate().getSubjectX500Principal(), TEST_CERT_SUBJECT)); } @Test public void testPKCS12CredentialLoadingSuccess() { - AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy( - pkcs12CredsHome); + AbstractLoadCredentialsStrategy strategy = new DefaultLoadCredentialsStrategy(pkcs12CredsHome); X509Credential cred = strategy.loadCredentials(new TestPasswordFinder()); Assert.assertNotNull(cred); - Assert.assertTrue(X500NameUtils.equal(cred.getCertificate() - .getSubjectX500Principal(), TEST_CERT_SUBJECT)); + Assert.assertTrue( + X500NameUtils.equal(cred.getCertificate().getSubjectX500Principal(), TEST_CERT_SUBJECT)); } - } diff --git a/src/test/java/org/italiangrid/voms/test/cred/package-info.java b/src/test/java/org/italiangrid/voms/test/cred/package-info.java index b02b45b..dfaa70d 100644 --- a/src/test/java/org/italiangrid/voms/test/cred/package-info.java +++ b/src/test/java/org/italiangrid/voms/test/cred/package-info.java @@ -2,11 +2,8 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * - */ +/** */ /** * @author andreaceccanti - * */ -package org.italiangrid.voms.test.cred; \ No newline at end of file +package org.italiangrid.voms.test.cred; diff --git a/src/test/java/org/italiangrid/voms/test/mt/TestConcurrentValidation.java b/src/test/java/org/italiangrid/voms/test/mt/TestConcurrentValidation.java index 349257d..c69bb5b 100644 --- a/src/test/java/org/italiangrid/voms/test/mt/TestConcurrentValidation.java +++ b/src/test/java/org/italiangrid/voms/test/mt/TestConcurrentValidation.java @@ -4,6 +4,11 @@ package org.italiangrid.voms.test.mt; +import eu.emi.security.authn.x509.NamespaceCheckingMode; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.impl.OpensslCertChainValidator; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -23,9 +28,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; - -import org.junit.Assert; - import org.italiangrid.voms.VOMSAttribute; import org.italiangrid.voms.VOMSValidators; import org.italiangrid.voms.ac.VOMSACValidator; @@ -33,15 +35,10 @@ import org.italiangrid.voms.store.impl.DefaultUpdatingVOMSTrustStore; import org.italiangrid.voms.test.utils.VOMSAA; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import eu.emi.security.authn.x509.NamespaceCheckingMode; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.impl.OpensslCertChainValidator; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; - public class TestConcurrentValidation { static X509CertChainValidatorExt sharedCertificateValidator; @@ -72,7 +69,7 @@ public class TestConcurrentValidation { static final ExecutorService pool = Executors.newCachedThreadPool(); - static final String[][] fqans = { { "/test.vo" }, { "/test.vo.2" } }; + static final String[][] fqans = {{"/test.vo"}, {"/test.vo.2"}}; static VOMSACValidator sharedValidator; @@ -80,37 +77,41 @@ public class TestConcurrentValidation { static final Random r = new Random(); - static void loadHolderCredentials() throws KeyStoreException, - CertificateException, FileNotFoundException, IOException { + static void loadHolderCredentials() + throws KeyStoreException, CertificateException, FileNotFoundException, IOException { holderCerts = new PEMCredential[numHolderCredentials]; for (int i = 0; i < numHolderCredentials; i++) { String baseFileName = String.format("src/test/resources/certs/test%d", i); - holderCerts[i] = new PEMCredential(new FileInputStream(baseFileName - + ".key.pem"), new FileInputStream(baseFileName + ".cert.pem"), - "pass".toCharArray()); + holderCerts[i] = + new PEMCredential( + new FileInputStream(baseFileName + ".key.pem"), + new FileInputStream(baseFileName + ".cert.pem"), + "pass".toCharArray()); } } - static void initVOs() throws KeyStoreException, CertificateException, - FileNotFoundException, IOException { + static void initVOs() + throws KeyStoreException, CertificateException, FileNotFoundException, IOException { - PEMCredential aaCred1 = new PEMCredential(new FileInputStream(aaKey), - new FileInputStream(aaCert), (char[]) null); + PEMCredential aaCred1 = + new PEMCredential(new FileInputStream(aaKey), new FileInputStream(aaCert), (char[]) null); - PEMCredential aaCred2 = new PEMCredential(new FileInputStream(aaKey2), - new FileInputStream(aaCert2), (char[]) null); + PEMCredential aaCred2 = + new PEMCredential(new FileInputStream(aaKey2), new FileInputStream(aaCert2), (char[]) null); testVO_1 = new VOMSAA(aaCred1, "test.vo", "test-host.cnaf.infn.it", 15000); testVO_2 = new VOMSAA(aaCred2, "test.vo.2", "wilco.cnaf.infn.it", 15001); - } - static void initVOMSProxies() throws InvalidKeyException, - CertificateParsingException, SignatureException, NoSuchAlgorithmException, - IOException { + static void initVOMSProxies() + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { testProxies = new ArrayList(); @@ -119,10 +120,8 @@ static void initVOMSProxies() throws InvalidKeyException, VOMSAA vo = (j == 0 ? testVO_1 : testVO_2); PEMCredential cert = holderCerts[i]; - ProxyCertificate proxy = vo.createVOMSProxy(cert, - Arrays.asList(fqans[j])); + ProxyCertificate proxy = vo.createVOMSProxy(cert, Arrays.asList(fqans[j])); testProxies.add(proxy); - } } @@ -133,39 +132,43 @@ static X509Certificate[] getRandomProxy() { } @BeforeClass - public static void setup() throws KeyStoreException, CertificateException, - FileNotFoundException, IOException, InvalidKeyException, - SignatureException, NoSuchAlgorithmException { - - sharedVOMSTrustStore = new DefaultUpdatingVOMSTrustStore( - Arrays.asList(vomsTrustStoreDir), trustStoreRefreshInterval); - - sharedCertificateValidator = new OpensslCertChainValidator(trustAnchorsDir, - NamespaceCheckingMode.EUGRIDPMA_AND_GLOBUS, trustAnchorsRefreshInterval); + public static void setup() + throws KeyStoreException, + CertificateException, + FileNotFoundException, + IOException, + InvalidKeyException, + SignatureException, + NoSuchAlgorithmException { + + sharedVOMSTrustStore = + new DefaultUpdatingVOMSTrustStore( + Arrays.asList(vomsTrustStoreDir), trustStoreRefreshInterval); + + sharedCertificateValidator = + new OpensslCertChainValidator( + trustAnchorsDir, + NamespaceCheckingMode.EUGRIDPMA_AND_GLOBUS, + trustAnchorsRefreshInterval); loadHolderCredentials(); initVOs(); initVOMSProxies(); - sharedValidator = VOMSValidators.newValidator(sharedVOMSTrustStore, - sharedCertificateValidator); + sharedValidator = VOMSValidators.newValidator(sharedVOMSTrustStore, sharedCertificateValidator); System.out.println("Setup done."); } @AfterClass - public static void tearDown() { - - } + public static void tearDown() {} @Test public void test() throws InterruptedException, BrokenBarrierException { long start = System.currentTimeMillis(); - System.out.format("Workers: %d. Iterations: %d\n", NUM_WORKERS, - NUM_ITERATIONS); + System.out.format("Workers: %d. Iterations: %d\n", NUM_WORKERS, NUM_ITERATIONS); - for (int i = 0; i < NUM_WORKERS; i++) - pool.execute(new ValidatorWorker()); + for (int i = 0; i < NUM_WORKERS; i++) pool.execute(new ValidatorWorker()); barrier.await(); barrier.await(); @@ -176,8 +179,7 @@ public void test() throws InterruptedException, BrokenBarrierException { long duration = System.currentTimeMillis() - start; - System.out - .format( + System.out.format( "Done. Test duration: %d milliseconds. Avg validation duration: %d milliseconds.\n", duration, duration / (NUM_WORKERS * NUM_ITERATIONS)); } @@ -204,11 +206,9 @@ public void run() { while (true) { - if (iterations++ > NUM_ITERATIONS) - break; + if (iterations++ > NUM_ITERATIONS) break; - if (shutdownRequested) - return; + if (shutdownRequested) return; VOMSACValidator validator = getValidator(); @@ -220,7 +220,6 @@ public void run() { } catch (Exception e) { System.err.println(e.getMessage()); - } } @@ -242,14 +241,16 @@ public synchronized void shutdown() { } static X509Certificate[] buildProxy(int credentialIndex, int voIndex) - throws InvalidKeyException, CertificateParsingException, - SignatureException, NoSuchAlgorithmException, IOException { + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { VOMSAA vo = (voIndex == 0 ? testVO_1 : testVO_2); PEMCredential cert = holderCerts[credentialIndex]; - ProxyCertificate proxy = vo.createVOMSProxy(cert, - Arrays.asList(fqans[voIndex])); + ProxyCertificate proxy = vo.createVOMSProxy(cert, Arrays.asList(fqans[voIndex])); return proxy.getCertificateChain(); } diff --git a/src/test/java/org/italiangrid/voms/test/package-info.java b/src/test/java/org/italiangrid/voms/test/package-info.java index 0e87376..9bfb7ba 100644 --- a/src/test/java/org/italiangrid/voms/test/package-info.java +++ b/src/test/java/org/italiangrid/voms/test/package-info.java @@ -2,8 +2,5 @@ // // SPDX-License-Identifier: Apache-2.0 -/** - * This package (and inner packages) provides unit tests for the VOMS - * Java API. - */ +/** This package (and inner packages) provides unit tests for the VOMS Java API. */ package org.italiangrid.voms.test; diff --git a/src/test/java/org/italiangrid/voms/test/req/TestRequests.java b/src/test/java/org/italiangrid/voms/test/req/TestRequests.java index 66d85db..6de9093 100644 --- a/src/test/java/org/italiangrid/voms/test/req/TestRequests.java +++ b/src/test/java/org/italiangrid/voms/test/req/TestRequests.java @@ -4,10 +4,11 @@ package org.italiangrid.voms.test.req; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.util.Arrays; import java.util.List; import java.util.Random; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.ac.VOMSACValidator; @@ -25,9 +26,6 @@ import org.junit.Test; import org.mockito.Mockito; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class TestRequests implements Fixture { @Test @@ -45,7 +43,6 @@ public void testEchoRequest() throws Exception { List acs = validator.validateACs(Arrays.asList(ac)); Assert.assertFalse(acs.isEmpty()); - } @Test @@ -74,16 +71,17 @@ public void testFailureIfVOIsNotKnown() throws Exception { @Test public void testNullACBytesHandling() throws Exception { - VOMSProtocol nullBytesProtocol = new VOMSProtocol() { + VOMSProtocol nullBytesProtocol = + new VOMSProtocol() { - public VOMSResponse doRequest(VOMSServerInfo endpoint, X509Credential credential, - VOMSACRequest request) { + public VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request) { - VOMSResponse r = Mockito.mock(VOMSResponse.class); + VOMSResponse r = Mockito.mock(VOMSResponse.class); - return r; - } - }; + return r; + } + }; VOMSACService acService = Utils.buildACService(nullBytesProtocol); @@ -98,22 +96,23 @@ public VOMSResponse doRequest(VOMSServerInfo endpoint, X509Credential credential @Test public void testRandomACBytesHandling() throws Exception { - VOMSProtocol nullBytesProtocol = new VOMSProtocol() { + VOMSProtocol nullBytesProtocol = + new VOMSProtocol() { - public VOMSResponse doRequest(VOMSServerInfo endpoint, X509Credential credential, - VOMSACRequest request) { + public VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request) { - Random r = new Random(); - byte[] acBytes = new byte[2048]; + Random r = new Random(); + byte[] acBytes = new byte[2048]; - r.nextBytes(acBytes); + r.nextBytes(acBytes); - VOMSResponse response = Mockito.mock(VOMSResponse.class); - Mockito.when(response.getAC()).thenReturn(acBytes); + VOMSResponse response = Mockito.mock(VOMSResponse.class); + Mockito.when(response.getAC()).thenReturn(acBytes); - return response; - } - }; + return response; + } + }; VOMSACService acService = Utils.buildACService(nullBytesProtocol); @@ -130,10 +129,12 @@ public void testProtocolFallback() throws Exception { VOMSProtocol exceptionProtocol = Mockito.mock(VOMSProtocol.class); - Mockito - .when(exceptionProtocol.doRequest(Mockito.any(VOMSServerInfo.class), - Mockito.any(X509Credential.class), Mockito.any(VOMSACRequest.class))) - .thenReturn(null); + Mockito.when( + exceptionProtocol.doRequest( + Mockito.any(VOMSServerInfo.class), + Mockito.any(X509Credential.class), + Mockito.any(VOMSACRequest.class))) + .thenReturn(null); VOMSProtocol fallBackProtocol = Mockito.mock(VOMSProtocol.class); @@ -144,8 +145,10 @@ public void testProtocolFallback() throws Exception { acService.getVOMSAttributeCertificate(Utils.getTestUserCredential(), req); Mockito.verify(fallBackProtocol, Mockito.atLeastOnce()) - .doRequest(Mockito.any(VOMSServerInfo.class), Mockito.any(X509Credential.class), - Mockito.any(VOMSACRequest.class)); + .doRequest( + Mockito.any(VOMSServerInfo.class), + Mockito.any(X509Credential.class), + Mockito.any(VOMSACRequest.class)); Assert.assertNull(ac); } @@ -155,10 +158,12 @@ public void testProtocolFallbackDisabled() throws Exception { VOMSProtocol exceptionProtocol = Mockito.mock(VOMSProtocol.class); - Mockito - .when(exceptionProtocol.doRequest(Mockito.any(VOMSServerInfo.class), - Mockito.any(X509Credential.class), Mockito.any(VOMSACRequest.class))) - .thenReturn(null); + Mockito.when( + exceptionProtocol.doRequest( + Mockito.any(VOMSServerInfo.class), + Mockito.any(X509Credential.class), + Mockito.any(VOMSACRequest.class))) + .thenReturn(null); VOMSProtocol fallBackProtocol = Mockito.mock(VOMSProtocol.class); @@ -178,10 +183,12 @@ public void testProtocolFallback2() throws Exception { VOMSProtocol exceptionProtocol = Mockito.mock(VOMSProtocol.class); - Mockito - .when(exceptionProtocol.doRequest(Mockito.any(VOMSServerInfo.class), - Mockito.any(X509Credential.class), Mockito.any(VOMSACRequest.class))) - .thenThrow(new VOMSProtocolError("protocol error", null, null, null, null)); + Mockito.when( + exceptionProtocol.doRequest( + Mockito.any(VOMSServerInfo.class), + Mockito.any(X509Credential.class), + Mockito.any(VOMSACRequest.class))) + .thenThrow(new VOMSProtocolError("protocol error", null, null, null, null)); VOMSProtocol fallBackProtocol = Mockito.mock(VOMSProtocol.class); @@ -192,10 +199,11 @@ public void testProtocolFallback2() throws Exception { acService.getVOMSAttributeCertificate(Utils.getTestUserCredential(), req); Mockito.verify(fallBackProtocol, Mockito.atLeastOnce()) - .doRequest(Mockito.any(VOMSServerInfo.class), Mockito.any(X509Credential.class), - Mockito.any(VOMSACRequest.class)); + .doRequest( + Mockito.any(VOMSServerInfo.class), + Mockito.any(X509Credential.class), + Mockito.any(VOMSACRequest.class)); Assert.assertNull(ac); } - } diff --git a/src/test/java/org/italiangrid/voms/test/utils/EchoVOMSProtocol.java b/src/test/java/org/italiangrid/voms/test/utils/EchoVOMSProtocol.java index 99d6f24..7cc8cd0 100644 --- a/src/test/java/org/italiangrid/voms/test/utils/EchoVOMSProtocol.java +++ b/src/test/java/org/italiangrid/voms/test/utils/EchoVOMSProtocol.java @@ -4,12 +4,13 @@ package org.italiangrid.voms.test.utils; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.italiangrid.voms.VOMSError; import org.italiangrid.voms.request.VOMSACRequest; @@ -18,9 +19,6 @@ import org.italiangrid.voms.request.VOMSServerInfo; import org.mockito.Mockito; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class EchoVOMSProtocol implements VOMSProtocol { PEMCredential aaCredential; @@ -30,11 +28,15 @@ public EchoVOMSProtocol(PEMCredential aaCredential) { this.aaCredential = aaCredential; } - public VOMSResponse doRequest(VOMSServerInfo endpoint, - X509Credential credential, VOMSACRequest request) { + public VOMSResponse doRequest( + VOMSServerInfo endpoint, X509Credential credential, VOMSACRequest request) { - VOMSAA aa = new VOMSAA(aaCredential, endpoint.getVoName(), endpoint - .getURL().getHost(), endpoint.getURL().getPort()); + VOMSAA aa = + new VOMSAA( + aaCredential, + endpoint.getVoName(), + endpoint.getURL().getHost(), + endpoint.getURL().getPort()); int lifetimeInSeconds = request.getLifetime(); @@ -49,11 +51,9 @@ public VOMSResponse doRequest(VOMSServerInfo endpoint, if (request.getRequestedFQANs().isEmpty()) { fqans = new ArrayList(); fqans.add("/" + request.getVoName()); - } else - fqans = request.getRequestedFQANs(); + } else fqans = request.getRequestedFQANs(); - AttributeCertificate ac = aa.getAC(credential, fqans, null, - request.getTargets(), now, endTime); + AttributeCertificate ac = aa.getAC(credential, fqans, null, request.getTargets(), now, endTime); VOMSResponse r = Mockito.mock(VOMSResponse.class); try { @@ -66,5 +66,4 @@ public VOMSResponse doRequest(VOMSServerInfo endpoint, return r; } - } diff --git a/src/test/java/org/italiangrid/voms/test/utils/Fixture.java b/src/test/java/org/italiangrid/voms/test/utils/Fixture.java index b5e5940..ec015d2 100644 --- a/src/test/java/org/italiangrid/voms/test/utils/Fixture.java +++ b/src/test/java/org/italiangrid/voms/test/utils/Fixture.java @@ -40,5 +40,4 @@ public interface Fixture { static final int defaultVOPort = 15000; static final List defaultVOFqans = Arrays.asList("/test.vo"); - } diff --git a/src/test/java/org/italiangrid/voms/test/utils/LogListener.java b/src/test/java/org/italiangrid/voms/test/utils/LogListener.java index afbbef6..770c77f 100644 --- a/src/test/java/org/italiangrid/voms/test/utils/LogListener.java +++ b/src/test/java/org/italiangrid/voms/test/utils/LogListener.java @@ -11,47 +11,37 @@ import org.italiangrid.voms.request.VOMSWarningMessage; public enum LogListener implements VOMSRequestListener { - INSTANCE; public void notifyVOMSRequestStart(VOMSACRequest request, VOMSServerInfo si) { - System.out - .format("Contacting %s for VO %s.\n", si.getURL(), si.getVoName()); - + System.out.format("Contacting %s for VO %s.\n", si.getURL(), si.getVoName()); } - public void notifyVOMSRequestSuccess(VOMSACRequest request, - VOMSServerInfo endpoint) { + public void notifyVOMSRequestSuccess(VOMSACRequest request, VOMSServerInfo endpoint) { System.out.format("Request for VO %s succeded.\n", endpoint.getVoName()); - } - public void notifyVOMSRequestFailure(VOMSACRequest request, - VOMSServerInfo endpoint, Throwable error) { - - System.out.format("Request for VO %s failed: %s.\n", request.getVoName(), - error); + public void notifyVOMSRequestFailure( + VOMSACRequest request, VOMSServerInfo endpoint, Throwable error) { + System.out.format("Request for VO %s failed: %s.\n", request.getVoName(), error); } - public void notifyErrorsInVOMSReponse(VOMSACRequest request, - VOMSServerInfo si, VOMSErrorMessage[] errors) { + public void notifyErrorsInVOMSReponse( + VOMSACRequest request, VOMSServerInfo si, VOMSErrorMessage[] errors) { System.out.format("Errors in voms response for VO %s.\n", si.getVoName()); - for (VOMSErrorMessage e : errors) - System.out.println(e.getMessage()); + for (VOMSErrorMessage e : errors) System.out.println(e.getMessage()); } - public void notifyWarningsInVOMSResponse(VOMSACRequest request, - VOMSServerInfo si, VOMSWarningMessage[] warnings) { + public void notifyWarningsInVOMSResponse( + VOMSACRequest request, VOMSServerInfo si, VOMSWarningMessage[] warnings) { System.out.format("Warnings in voms response for VO %s.\n", si.getVoName()); - for (VOMSWarningMessage m : warnings) - System.out.println(m.getMessage()); - - }; - + for (VOMSWarningMessage m : warnings) System.out.println(m.getMessage()); + } + ; } diff --git a/src/test/java/org/italiangrid/voms/test/utils/Utils.java b/src/test/java/org/italiangrid/voms/test/utils/Utils.java index f097fed..d4540ce 100644 --- a/src/test/java/org/italiangrid/voms/test/utils/Utils.java +++ b/src/test/java/org/italiangrid/voms/test/utils/Utils.java @@ -4,6 +4,8 @@ package org.italiangrid.voms.test.utils; +import eu.emi.security.authn.x509.X509CertChainValidatorExt; +import eu.emi.security.authn.x509.impl.PEMCredential; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -14,7 +16,6 @@ import java.util.Date; import java.util.HashSet; import java.util.Set; - import org.italiangrid.voms.VOMSValidators; import org.italiangrid.voms.ac.VOMSACValidator; import org.italiangrid.voms.ac.impl.DefaultVOMSValidationStrategy; @@ -31,45 +32,39 @@ import org.italiangrid.voms.util.CertificateValidatorBuilder; import org.mockito.Mockito; -import eu.emi.security.authn.x509.X509CertChainValidatorExt; -import eu.emi.security.authn.x509.impl.PEMCredential; - public class Utils implements Fixture { - private Utils() { - - } - + private Utils() {} - public static VOMSACService buildACService(VOMSProtocol main, - VOMSProtocol fallback, boolean legacyProtocolEnabled) throws Exception { + public static VOMSACService buildACService( + VOMSProtocol main, VOMSProtocol fallback, boolean legacyProtocolEnabled) throws Exception { VOMSServerInfoStore store = Mockito.mock(VOMSServerInfoStore.class); Set testVOEndpoints = new HashSet(); testVOEndpoints.add(getTestVOEndpoint()); - Mockito.when(store.getVOMSServerInfo("test.vo")) - .thenReturn(testVOEndpoints); + Mockito.when(store.getVOMSServerInfo("test.vo")).thenReturn(testVOEndpoints); - DefaultVOMSACService acService = new DefaultVOMSACService.Builder( - getCertificateValidator()).serverInfoStore(store) - .requestListener(LogListener.INSTANCE).httpProtocol(main) - .legacyProtocol(fallback) - .legacyProtocolEnabled(legacyProtocolEnabled) - .build(); + DefaultVOMSACService acService = + new DefaultVOMSACService.Builder(getCertificateValidator()) + .serverInfoStore(store) + .requestListener(LogListener.INSTANCE) + .httpProtocol(main) + .legacyProtocol(fallback) + .legacyProtocolEnabled(legacyProtocolEnabled) + .build(); return acService; - } public static VOMSACService buildACService(VOMSProtocol main, VOMSProtocol fallback) throws Exception { + return buildACService(main, fallback, true); } - public static VOMSACService buildACService(VOMSProtocol protocol) - throws Exception { + public static VOMSACService buildACService(VOMSProtocol protocol) throws Exception { return buildACService(protocol, null); } @@ -86,76 +81,71 @@ public static VOMSServerInfo getTestVOEndpoint() throws URISyntaxException { public static X509CertChainValidatorExt getCertificateValidator() { - return new CertificateValidatorBuilder().trustAnchorsDir(trustAnchorsDir) - .build(); + return new CertificateValidatorBuilder().trustAnchorsDir(trustAnchorsDir).build(); } public static VOMSACValidator getVOMSValidator(LocalHostnameResolver resolver) { - X509CertChainValidatorExt validator = new CertificateValidatorBuilder() - .trustAnchorsDir(trustAnchorsDir).build(); + X509CertChainValidatorExt validator = + new CertificateValidatorBuilder().trustAnchorsDir(trustAnchorsDir).build(); VOMSTrustStore ts = new DefaultVOMSTrustStore(Arrays.asList(vomsdir)); - return new DefaultVOMSValidator.Builder().validationStrategy( - new DefaultVOMSValidationStrategy(ts, validator, resolver)).build(); + return new DefaultVOMSValidator.Builder() + .validationStrategy(new DefaultVOMSValidationStrategy(ts, validator, resolver)) + .build(); } public static VOMSACValidator getVOMSValidator() { - X509CertChainValidatorExt validator = new CertificateValidatorBuilder() - .trustAnchorsDir(trustAnchorsDir).build(); + X509CertChainValidatorExt validator = + new CertificateValidatorBuilder().trustAnchorsDir(trustAnchorsDir).build(); return VOMSValidators.newValidator( - new DefaultVOMSTrustStore(Arrays.asList(vomsdir)), validator); - + new DefaultVOMSTrustStore(Arrays.asList(vomsdir)), validator); } public static VOMSACValidator getVOMSValidator(String vomsDir) { - X509CertChainValidatorExt validator = new CertificateValidatorBuilder() - .trustAnchorsDir(trustAnchorsDir).build(); + X509CertChainValidatorExt validator = + new CertificateValidatorBuilder().trustAnchorsDir(trustAnchorsDir).build(); return VOMSValidators.newValidator( - new DefaultVOMSTrustStore(Arrays.asList(vomsDir)), validator); - + new DefaultVOMSTrustStore(Arrays.asList(vomsDir)), validator); } - public static PEMCredential getAACredential() throws KeyStoreException, - CertificateException, IOException { + public static PEMCredential getAACredential() + throws KeyStoreException, CertificateException, IOException { return new PEMCredential(aaKey, aaCert, keyPassword.toCharArray()); } - public static PEMCredential getAACredential2() throws KeyStoreException, - CertificateException, IOException { + public static PEMCredential getAACredential2() + throws KeyStoreException, CertificateException, IOException { return new PEMCredential(aaKey2, aaCert2, keyPassword.toCharArray()); } - public static PEMCredential getTestUserCredential() throws KeyStoreException, - CertificateException, IOException { + public static PEMCredential getTestUserCredential() + throws KeyStoreException, CertificateException, IOException { return new PEMCredential(holderKey, holderCert, keyPassword.toCharArray()); } public static PEMCredential getTest1UserCredential() - throws KeyStoreException, CertificateException, IOException { + throws KeyStoreException, CertificateException, IOException { return new PEMCredential(holderKey2, holderCert2, keyPassword.toCharArray()); } - public static PEMCredential getExpiredCredential() throws KeyStoreException, - CertificateException, IOException { + public static PEMCredential getExpiredCredential() + throws KeyStoreException, CertificateException, IOException { return new PEMCredential(expiredKey, expiredCert, keyPassword.toCharArray()); } - public static VOMSAA getVOMSAA() throws KeyStoreException, - CertificateException, IOException { + public static VOMSAA getVOMSAA() throws KeyStoreException, CertificateException, IOException { - return new VOMSAA(getAACredential(), defaultVO, defaultVOHost, - defaultVOPort); + return new VOMSAA(getAACredential(), defaultVO, defaultVOHost, defaultVOPort); } - public static Date getDate(int year, int month, int day, int hour, - int minute, int second) { + public static Date getDate(int year, int month, int day, int hour, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day, hour, minute, second); @@ -168,5 +158,4 @@ public static Date getDate(int year, int month, int day) { cal.set(year, month, day); return cal.getTime(); } - } diff --git a/src/test/java/org/italiangrid/voms/test/utils/VOMSAA.java b/src/test/java/org/italiangrid/voms/test/utils/VOMSAA.java index ccf814b..685899a 100644 --- a/src/test/java/org/italiangrid/voms/test/utils/VOMSAA.java +++ b/src/test/java/org/italiangrid/voms/test/utils/VOMSAA.java @@ -4,6 +4,11 @@ package org.italiangrid.voms.test.utils; +import eu.emi.security.authn.x509.X509Credential; +import eu.emi.security.authn.x509.impl.PEMCredential; +import eu.emi.security.authn.x509.proxy.ProxyCertificate; +import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; +import eu.emi.security.authn.x509.proxy.ProxyGenerator; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; @@ -14,19 +19,12 @@ import java.util.Date; import java.util.EnumSet; import java.util.List; - import org.bouncycastle.asn1.x509.AttributeCertificate; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.italiangrid.voms.VOMSGenericAttribute; import org.italiangrid.voms.asn1.VOMSACGenerator; import org.italiangrid.voms.asn1.VOMSACGenerator.ACGenerationProperties; -import eu.emi.security.authn.x509.X509Credential; -import eu.emi.security.authn.x509.impl.PEMCredential; -import eu.emi.security.authn.x509.proxy.ProxyCertificate; -import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions; -import eu.emi.security.authn.x509.proxy.ProxyGenerator; - public class VOMSAA { X509Credential credential; @@ -37,7 +35,8 @@ public class VOMSAA { Date acNotBefore; Date acNotAfter; - EnumSet generationProperties = VOMSACGenerator.defaultGenerationProperties; + EnumSet generationProperties = + VOMSACGenerator.defaultGenerationProperties; private volatile long serial = 0L; @@ -47,7 +46,6 @@ public VOMSAA(X509Credential cred, String vo, String host, int port) { voName = vo; this.host = host; this.port = port; - } private synchronized BigInteger getAndIncrementSerial() { @@ -55,82 +53,115 @@ private synchronized BigInteger getAndIncrementSerial() { return BigInteger.valueOf(serial++); } - public ProxyCertificate createVOMSProxy(PEMCredential holder, - List fqans, List gas, List targets) - throws InvalidKeyException, CertificateParsingException, - SignatureException, NoSuchAlgorithmException, IOException { + public ProxyCertificate createVOMSProxy( + PEMCredential holder, + List fqans, + List gas, + List targets) + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { return createVOMSProxy(holder, holder, fqans, gas, targets); } - public ProxyCertificate createVOMSProxy(PEMCredential holder, - List fqans) throws InvalidKeyException, - CertificateParsingException, SignatureException, NoSuchAlgorithmException, - IOException { + public ProxyCertificate createVOMSProxy(PEMCredential holder, List fqans) + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { return createVOMSProxy(holder, holder, fqans, null, null); } - public AttributeCertificate getAC(X509Credential holder, List fqans, - List attrs, List targets, Date notBefore, - Date notAfter) { + public AttributeCertificate getAC( + X509Credential holder, + List fqans, + List attrs, + List targets, + Date notBefore, + Date notAfter) { - return getAC(credential, holder, voName, host, port, fqans, attrs, targets, - notBefore, notAfter); + return getAC( + credential, holder, voName, host, port, fqans, attrs, targets, notBefore, notAfter); } - public AttributeCertificate getAC(X509Credential aaCredential, - X509Credential holder, String voName, String host, int port, - List fqans, List attrs, List targets, - Date notBefore, Date notAfter) { + public AttributeCertificate getAC( + X509Credential aaCredential, + X509Credential holder, + String voName, + String host, + int port, + List fqans, + List attrs, + List targets, + Date notBefore, + Date notAfter) { VOMSACGenerator generator = new VOMSACGenerator(aaCredential); - X509AttributeCertificateHolder acHolder = generator - .generateVOMSAttributeCertificate(generationProperties, fqans, attrs, - targets, holder.getCertificate(), getAndIncrementSerial(), notBefore, - notAfter, voName, host, port); + X509AttributeCertificateHolder acHolder = + generator.generateVOMSAttributeCertificate( + generationProperties, + fqans, + attrs, + targets, + holder.getCertificate(), + getAndIncrementSerial(), + notBefore, + notAfter, + voName, + host, + port); return acHolder.toASN1Structure(); - } - public ProxyCertificate createVOMSProxy(PEMCredential holder, - PEMCredential proxyHolder, List fqans, - List attrs, List targets) - throws InvalidKeyException, CertificateParsingException, - SignatureException, NoSuchAlgorithmException, IOException { + public ProxyCertificate createVOMSProxy( + PEMCredential holder, + PEMCredential proxyHolder, + List fqans, + List attrs, + List targets) + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { Calendar cal = Calendar.getInstance(); Date startDate = acNotBefore; Date endDate = acNotAfter; - if (startDate == null) - startDate = cal.getTime(); + if (startDate == null) startDate = cal.getTime(); if (endDate == null) { cal.add(Calendar.HOUR, 12); endDate = cal.getTime(); } - AttributeCertificate ac = getAC(credential, holder, voName, host, port, - fqans, attrs, targets, startDate, endDate); + AttributeCertificate ac = + getAC(credential, holder, voName, host, port, fqans, attrs, targets, startDate, endDate); - return createVOMSProxy(proxyHolder, new AttributeCertificate[] { ac }); + return createVOMSProxy(proxyHolder, new AttributeCertificate[] {ac}); } - public ProxyCertificate createVOMSProxy(PEMCredential holder, - AttributeCertificate[] acs) throws InvalidKeyException, - CertificateParsingException, SignatureException, NoSuchAlgorithmException, - IOException { + public ProxyCertificate createVOMSProxy(PEMCredential holder, AttributeCertificate[] acs) + throws InvalidKeyException, + CertificateParsingException, + SignatureException, + NoSuchAlgorithmException, + IOException { - ProxyCertificateOptions proxyOptions = new ProxyCertificateOptions( - holder.getCertificateChain()); + ProxyCertificateOptions proxyOptions = + new ProxyCertificateOptions(holder.getCertificateChain()); proxyOptions.setAttributeCertificates(acs); - ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, - holder.getKey()); + ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, holder.getKey()); return proxy; } From 82d1a3594e8f1c7f2eb67beb643fc61c68612a1e Mon Sep 17 00:00:00 2001 From: Luca Bassi Date: Mon, 11 May 2026 09:47:21 +0200 Subject: [PATCH 3/3] Add .git-blame-ignore-revs to ignore format code commit in git blame --- .git-blame-ignore-revs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..cba37f4 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: 2006 Istituto Nazionale di Fisica Nucleare +# +# SPDX-License-Identifier: Apache-2.0 + +# Format code +97145e5e6cf3138e451975815a1bdb596f671e43