From 50648b98abbbcbd2367b21d4a527d594a91c14c0 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 23 Oct 2023 09:51:11 +0300 Subject: [PATCH 01/35] DD4J-928 Fix failing unit tests --- .../test/java/org/digidoc4j/AbstractTest.java | 57 +-- .../CertificateValidatorBuilderTest.java | 171 +++++---- .../java/org/digidoc4j/ConfigurationTest.java | 4 +- .../org/digidoc4j/ContainerBuilderTest.java | 1 + .../DetachedXadesSignatureBuilderTest.java | 1 + .../org/digidoc4j/SignatureBuilderTest.java | 324 +++++++++--------- .../digidoc4j/impl/CommonOCSPSourceTest.java | 11 + .../EmptyDataFilesSignatureFinalizerTest.java | 2 + .../impl/SimpleHttpGetDataLoaderTest.java | 15 +- .../AsicContainerParserZipBombingTest.java | 17 +- .../asic/EmptyDataFilesContainerTest.java | 12 + .../TslRefreshCallbackInteractionTest.java | 12 +- .../impl/bdoc/BDocContainerTest.java | 9 +- .../impl/bdoc/BDocSerializationTest.java | 1 + .../bdoc/ContainerParticlesRemovalTest.java | 1 + .../bdoc/EmptyDataFilesBdocContainerTest.java | 32 +- .../impl/bdoc/ExtendingBDocContainerTest.java | 1 + .../impl/bdoc/IncompleteSigningTest.java | 1 + .../digidoc4j/impl/bdoc/ValidationTest.java | 18 +- .../EmptyDataFilesAsicEContainerTest.java | 12 + .../bdoc/xades/XadesSigningDssFacadeTest.java | 24 +- .../org/digidoc4j/main/DigiDoc4JTest.java | 2 +- .../digidoc4j/utils/KeyStoreDocumentTest.java | 75 ++-- 23 files changed, 477 insertions(+), 326 deletions(-) diff --git a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java index 38921026b..892113c81 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java @@ -14,6 +14,7 @@ import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.Policy; +import eu.europa.esig.dss.model.x509.CertificateToken; import eu.europa.esig.dss.service.tsp.OnlineTSPSource; import eu.europa.esig.dss.spi.DSSUtils; import eu.europa.esig.dss.spi.client.http.DataLoader; @@ -66,6 +67,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.Duration; @@ -74,7 +76,6 @@ import java.util.Collections; import java.util.Date; import java.util.List; -import java.util.Objects; import java.util.function.Consumer; import static org.digidoc4j.Container.DocumentType.ASICE; @@ -503,17 +504,38 @@ protected boolean isTSLCacheEmpty() { return TestTSLUtil.isTslCacheEmpty(); } - protected X509Certificate openX509Certificate(Path path) { + protected static X509Certificate openX509Certificate(String path) { + return openX509Certificate(Paths.get(path)); + } + + protected static X509Certificate openX509Certificate(Path path) { + try (InputStream in = Files.newInputStream(path)) { + return openX509Certificate(in); + } catch (IOException e) { + throw new IllegalStateException("Failed to load certificate from: " + path, e); + } + } + + protected static X509Certificate openX509Certificate(InputStream in) { try { - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - try (FileInputStream stream = new FileInputStream(path.toFile())) { - return (X509Certificate) certificateFactory.generateCertificate(stream); - } - } catch (Exception e) { - throw new RuntimeException(e); + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in); + } catch (CertificateException e) { + throw new IllegalStateException("Failed to load certificate", e); } } + protected static CertificateToken openCertificateToken(String path) { + return new CertificateToken(openX509Certificate(path)); + } + + protected static CertificateToken openCertificateToken(Path path) { + return new CertificateToken(openX509Certificate(path)); + } + + protected static CertificateToken openCertificateToken(InputStream in) { + return new CertificateToken(openX509Certificate(in)); + } + protected XadesSigningDssFacade createSigningFacade() { XadesSigningDssFacade facade = new XadesSigningDssFacade(); facade.setAiaSource(new AiaSourceFactory(configuration).create()); @@ -537,25 +559,6 @@ private OnlineTSPSource createTSPSource() { return source; } - @FunctionalInterface - protected interface PotentiallyThrowing { - void run() throws T; - } - - @SuppressWarnings("unchecked") - protected static T assertThrows(Class type, PotentiallyThrowing toTest) { - try { - toTest.run(); - } catch (Throwable t) { - if (type.isInstance(t)) { - return Objects.requireNonNull((T) t, "Caught exception cannot be null"); - } - Assert.fail(String.format("Expected %s, but an %s was thrown: %s", type.getSimpleName(), t.getClass().getSimpleName(), t.getMessage())); - } - Assert.fail(String.format("Expected %s, but nothing was thrown", type.getSimpleName())); - throw new IllegalStateException("Should have not reached here!"); // For compiler - } - protected void assertBDocContainer(Container container) { Assert.assertNotNull(container); Assert.assertTrue(container instanceof BDocContainer); diff --git a/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java index a5cb4d9c2..ebf9eca53 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java @@ -1,12 +1,28 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j; -import eu.europa.esig.dss.model.x509.CertificateToken; import org.digidoc4j.exceptions.CertificateValidationException; import org.digidoc4j.impl.asic.tsl.TSLCertificateSourceImpl; -import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; import java.nio.file.Paths; +import java.security.cert.X509Certificate; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.Assert.assertThrows; /** * Created by Janar Rahumeel (CGI Estonia) @@ -14,91 +30,130 @@ public class CertificateValidatorBuilderTest extends AbstractTest { @Test - public void findOnlyOneIssuerWhenCNAreSame() throws Exception { + public void validate_WhenCnOfIssuerCertificatesAreSame_OnlyOneIssuerIsFound() { CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/sameCN_first.crt")))); - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/sameCN_second.crt")))); - try { - validator.validate(this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/sameCN_first_child.crt"))); - } catch (CertificateValidationException e) { - Assert.assertEquals("Not equals", CertificateValidationException.CertificateValidationStatus.UNKNOWN, e - .getCertificateStatus()); - } + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/sameCN_first.crt")); + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/sameCN_second.crt")); + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/sameCN_first_child.crt"); + + CertificateValidationException caughtException = assertThrows( + CertificateValidationException.class, + () -> validator.validate(certificateToTest) + ); + + assertThat( + caughtException.getCertificateStatus(), + equalTo(CertificateValidationException.CertificateValidationStatus.UNKNOWN) + ); + assertThat( + caughtException.getMessage(), + equalTo("Certificate is unknown") + ); } @Test - public void testCertificateStatusGood() { + public void validate_WhenCertificateStatusIsGood_NothingIsThrown() { CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/TESTofEECertificationCentreRootCA.crt")))); - validator.validate( - this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt"))); + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/TESTofEECertificationCentreRootCA.crt")); + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TEST_of_ESTEID-SK_2015.pem.crt"); + + validator.validate(certificateToTest); } @Test - public void testCertificateStatusUntrusted() { + @Ignore("DD4J-931") + public void validate_WhenCertificateIsNotTrusted_ValidationExceptionWithUntrustedStatusIsThrown() { CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - try { - validator.validate( - this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt"))); - } catch (CertificateValidationException e) { - Assert.assertEquals("Not equals", CertificateValidationException.CertificateValidationStatus.UNTRUSTED, e - .getCertificateStatus()); - } + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TEST_of_ESTEID-SK_2015.pem.crt"); + + CertificateValidationException caughtException = assertThrows( + CertificateValidationException.class, + () -> validator.validate(certificateToTest) + ); + + assertThat( + caughtException.getCertificateStatus(), + equalTo(CertificateValidationException.CertificateValidationStatus.UNTRUSTED) + ); + assertThat( + caughtException.getMessage(), + equalTo("Failed to parse issuer certificate token. Not all intermediate certificates added into OCSP.") + ); } @Test - public void testCertificateStatusRevoked() { + public void validate_WhenCertificateIsRevoked_ValidationExceptionWithRevokedStatusIsThrown() { CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")))); - try { - validator.validate( - this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"))); - } catch (CertificateValidationException e) { - Assert.assertEquals("Not equals", CertificateValidationException.CertificateValidationStatus.REVOKED, e - .getCertificateStatus()); - } + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")); + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"); + + CertificateValidationException caughtException = assertThrows( + CertificateValidationException.class, + () -> validator.validate(certificateToTest) + ); + + assertThat( + caughtException.getCertificateStatus(), + equalTo(CertificateValidationException.CertificateValidationStatus.REVOKED) + ); + assertThat( + caughtException.getMessage(), + equalTo("Certificate status is revoked") + ); } @Test - public void testProductionCertificateStatusUntrustedWithMissingOCSPResponseCertificate() { + public void validate_WhenOcspResponderCertificateIsNotTrusted_ValidationExceptionWithUntrustedStatusIsThrown() { this.configuration = Configuration.of(Configuration.Mode.PROD); this.configuration.setTSL(new TSLCertificateSourceImpl()); CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - try { - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")))); - validator.validate( - this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"))); - } catch (CertificateValidationException e) { - Assert.assertEquals("Not equals", CertificateValidationException.CertificateValidationStatus.UNTRUSTED, e - .getCertificateStatus()); - } + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")); + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"); + + CertificateValidationException caughtException = assertThrows( + CertificateValidationException.class, + () -> validator.validate(certificateToTest) + ); + + assertThat( + caughtException.getCertificateStatus(), + equalTo(CertificateValidationException.CertificateValidationStatus.UNTRUSTED) + ); + assertThat( + caughtException.getMessage(), + matchesPattern("OCSP response certificate match is not found in TSL") + ); } @Test - public void testProductionCertificateStatusUnknownWithOCSPResponseVerificationCertificate() { + public void validate_WhenOcspResponseStatusIsUnknown_ValidationExceptionWithUnknownStatusIsThrown() { this.configuration = Configuration.of(Configuration.Mode.PROD); CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); - try { - validator.getCertificateSource().addCertificate(new CertificateToken(this.openX509Certificate(Paths.get - ("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")))); - validator.validate( - this.openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"))); - } catch (CertificateValidationException e) { - Assert.assertEquals("Not equals", CertificateValidationException.CertificateValidationStatus.UNKNOWN, e - .getCertificateStatus()); - } + validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")); + X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"); + + CertificateValidationException caughtException = assertThrows( + CertificateValidationException.class, + () -> validator.validate(certificateToTest) + ); + + assertThat( + caughtException.getCertificateStatus(), + equalTo(CertificateValidationException.CertificateValidationStatus.UNKNOWN) + ); + assertThat( + caughtException.getMessage(), + equalTo("Certificate is unknown") + ); } @Test - public void testLoadingOCSPIntermediateCertificatesFromCustomLocation() { + public void importFromPath_WhenLoadingCertificatesFromCustomLocation_SourceContainsExpectedNumberOfCertificates() { ExtendedCertificateSource source = CertificateValidatorBuilder.getDefaultCertificateSource(); + source.importFromPath(Paths.get("src/test/resources/testFiles/certs")); - Assert.assertEquals("Not equals", 13, source.getCertificates().size()); + + assertThat(source.getCertificates(), hasSize(13)); } /* diff --git a/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java b/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java index b8b0fe66d..a409c7e2a 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java @@ -274,12 +274,12 @@ public void policyFileIsReadFromNonDefaultFileLocation() { } @Test - public void TSLIsLoadedAfterSettingNewLOTLLocation() throws Exception { + public void tslIsLoadedAfterSettingNewLotlLocation() throws Exception { this.configuration.setLotlLocation("https://open-eid.github.io/test-TL/tl-mp-test-EE.xml"); BDocContainer container = (BDocContainer) ContainerBuilder.aContainer(Container.DocumentType.BDOC) .withConfiguration(this.configuration).build(); container.getConfiguration().getTSL(); - Assert.assertEquals(25, container.getConfiguration().getTSL().getCertificates().size()); + Assert.assertEquals(27, container.getConfiguration().getTSL().getCertificates().size()); int tenSeconds = 10000; String lotlHost = "10.0.25.57"; diff --git a/digidoc4j/src/test/java/org/digidoc4j/ContainerBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/ContainerBuilderTest.java index 8789de29a..4465feb3f 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/ContainerBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/ContainerBuilderTest.java @@ -40,6 +40,7 @@ import static org.digidoc4j.Container.DocumentType.ASICS; import static org.digidoc4j.Container.DocumentType.BDOC; import static org.digidoc4j.Container.DocumentType.DDOC; +import static org.junit.Assert.assertThrows; public class ContainerBuilderTest extends AbstractTest { diff --git a/digidoc4j/src/test/java/org/digidoc4j/DetachedXadesSignatureBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/DetachedXadesSignatureBuilderTest.java index d9a679540..b2e803267 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/DetachedXadesSignatureBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/DetachedXadesSignatureBuilderTest.java @@ -30,6 +30,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertThrows; public class DetachedXadesSignatureBuilderTest extends AbstractTest { diff --git a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java index 8635c30e3..c92f7a012 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java @@ -22,7 +22,6 @@ import org.digidoc4j.test.util.TestDataBuilderUtil; import org.digidoc4j.test.util.TestSigningUtil; import org.digidoc4j.utils.TokenAlgorithmSupport; -import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; @@ -47,6 +46,13 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class SignatureBuilderTest extends AbstractTest { @@ -84,10 +90,10 @@ public void buildDataToSign_WhenContainerTypeIsASiCE_ReturnsDataToSign() { DataToSign dataToSign = signatureBuilder.buildDataToSign(); - Assert.assertNotNull(dataToSign); - Assert.assertNotNull(dataToSign.getDataToSign()); - Assert.assertNotNull(dataToSign.getSignatureParameters()); - Assert.assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); + assertNotNull(dataToSign); + assertNotNull(dataToSign.getDataToSign()); + assertNotNull(dataToSign.getSignatureParameters()); + assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); } @Test @@ -98,10 +104,10 @@ public void buildDataToSign_WhenContainerTypeIsBDOC_ReturnsDataToSign() { DataToSign dataToSign = signatureBuilder.buildDataToSign(); - Assert.assertNotNull(dataToSign); - Assert.assertNotNull(dataToSign.getDataToSign()); - Assert.assertNotNull(dataToSign.getSignatureParameters()); - Assert.assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); + assertNotNull(dataToSign); + assertNotNull(dataToSign.getDataToSign()); + assertNotNull(dataToSign.getSignatureParameters()); + assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); } @Test @@ -112,10 +118,10 @@ public void buildDataToSign_WhenContainerTypeIsASiCS_ReturnsDataToSign() { DataToSign dataToSign = signatureBuilder.buildDataToSign(); - Assert.assertNotNull(dataToSign); - Assert.assertNotNull(dataToSign.getDataToSign()); - Assert.assertNotNull(dataToSign.getSignatureParameters()); - Assert.assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); + assertNotNull(dataToSign); + assertNotNull(dataToSign.getDataToSign()); + assertNotNull(dataToSign.getSignatureParameters()); + assertEquals(DigestAlgorithm.SHA256, dataToSign.getDigestAlgorithm()); } @Test @@ -136,18 +142,18 @@ public void buildDataToSign_WhenSignatureParametersAreProvided_ReturnsDataToSign DataToSign dataToSign = signatureBuilder.buildDataToSign(); SignatureParameters parameters = dataToSign.getSignatureParameters(); - Assert.assertEquals("San Pedro", parameters.getCity()); - Assert.assertEquals("Puerto Vallarta", parameters.getStateOrProvince()); - Assert.assertEquals("13456", parameters.getPostalCode()); - Assert.assertEquals("Val Verde", parameters.getCountry()); - Assert.assertEquals("Manager", parameters.getRoles().get(0)); - Assert.assertEquals(DigestAlgorithm.SHA512, parameters.getDataFileDigestAlgorithm()); - Assert.assertEquals(DigestAlgorithm.SHA384, parameters.getSignatureDigestAlgorithm()); - Assert.assertEquals(SignatureProfile.LTA, parameters.getSignatureProfile()); - Assert.assertEquals("S0", parameters.getSignatureId()); - Assert.assertSame(pkcs12SignatureToken.getCertificate(), parameters.getSigningCertificate()); + assertEquals("San Pedro", parameters.getCity()); + assertEquals("Puerto Vallarta", parameters.getStateOrProvince()); + assertEquals("13456", parameters.getPostalCode()); + assertEquals("Val Verde", parameters.getCountry()); + assertEquals("Manager", parameters.getRoles().get(0)); + assertEquals(DigestAlgorithm.SHA512, parameters.getDataFileDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA384, parameters.getSignatureDigestAlgorithm()); + assertEquals(SignatureProfile.LTA, parameters.getSignatureProfile()); + assertEquals("S0", parameters.getSignatureId()); + assertSame(pkcs12SignatureToken.getCertificate(), parameters.getSigningCertificate()); byte[] bytesToSign = dataToSign.getDataToSign(); - Assert.assertNotNull(bytesToSign); + assertNotNull(bytesToSign); assertThat(bytesToSign.length, greaterThan(1)); } @@ -179,7 +185,7 @@ public void invokeSigning_WhenContainerTypeIsASiCE_Signature() { Signature signature = signatureBuilder.invokeSigning(); - Assert.assertNotNull(signature); + assertNotNull(signature); assertSignatureIsValid(signature, SignatureProfile.LT); } @@ -191,7 +197,7 @@ public void invokeSigning_WhenContainerTypeIsBDOC_Signature() { Signature signature = signatureBuilder.invokeSigning(); - Assert.assertNotNull(signature); + assertNotNull(signature); assertSignatureIsValid(signature, SignatureProfile.LT); } @@ -203,7 +209,7 @@ public void invokeSigning_WhenContainerTypeIsASiCS_Signature() { Signature signature = signatureBuilder.invokeSigning(); - Assert.assertNotNull(signature); + assertNotNull(signature); assertSignatureIsValid(signature, SignatureProfile.LT); } @@ -223,7 +229,7 @@ public void invokeSigning_WhenSignatureParametersAreProvided_ReturnsDataToSignCo Signature signature = signatureBuilder.invokeSigning(); - Assert.assertNotNull(signature); + assertNotNull(signature); assertSignatureIsValid(signature, SignatureProfile.LTA); assertThat(signature.getCity(), equalTo("Tallinn")); assertThat(signature.getStateOrProvince(), equalTo("Harjumaa")); @@ -248,16 +254,16 @@ public void signContainerWithSignatureToken() { .withSignatureToken(pkcs12SignatureToken) .invokeSigning(); container.addSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.saveAsFile(getFileBy("asice")); assertSignatureIsValid(signature, SignatureProfile.LT); - Assert.assertEquals("Tallinn", signature.getCity()); - Assert.assertEquals("Harjumaa", signature.getStateOrProvince()); - Assert.assertEquals("13456", signature.getPostalCode()); - Assert.assertEquals("Estonia", signature.getCountryName()); - Assert.assertEquals(2, signature.getSignerRoles().size()); - Assert.assertEquals("Manager", signature.getSignerRoles().get(0)); - Assert.assertEquals("Suspicious Fisherman", signature.getSignerRoles().get(1)); + assertEquals("Tallinn", signature.getCity()); + assertEquals("Harjumaa", signature.getStateOrProvince()); + assertEquals("13456", signature.getPostalCode()); + assertEquals("Estonia", signature.getCountryName()); + assertEquals(2, signature.getSignerRoles().size()); + assertEquals("Manager", signature.getSignerRoles().get(0)); + assertEquals("Suspicious Fisherman", signature.getSignerRoles().get(1)); } @Test @@ -298,11 +304,11 @@ public void signWithEccCertificate() { Container container = createNonEmptyContainer(); Signature signature = SignatureBuilder.aSignature(container).withSignatureToken(pkcs12EccSignatureToken) .withEncryptionAlgorithm(EncryptionAlgorithm.ECDSA).invokeSigning(); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); - Assert.assertEquals(SignatureProfile.LT, signature.getProfile()); + assertEquals(SignatureProfile.LT, signature.getProfile()); container.addSignature(signature); - Assert.assertTrue(container.validate().isValid()); + assertTrue(container.validate().isValid()); } @Test @@ -311,24 +317,24 @@ public void signWith2EccCertificate() { Signature signature = SignatureBuilder.aSignature(container).withSignatureToken(pkcs12EccSignatureToken) .withEncryptionAlgorithm(EncryptionAlgorithm.ECDSA).withSignatureDigestAlgorithm(DigestAlgorithm.SHA256) .withSignatureProfile(SignatureProfile.LT).invokeSigning(); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); container.addSignature(signature); signature = SignatureBuilder.aSignature(container) .withSignatureToken(pkcs12Esteid2018SignatureToken) .withEncryptionAlgorithm(EncryptionAlgorithm.RSA).withSignatureProfile(SignatureProfile.LT).invokeSigning(); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); container.addSignature(signature); - Assert.assertTrue(container.validate().isValid()); + assertTrue(container.validate().isValid()); } @Test public void signWithEccCertificate_determiningEncryptionAlgorithmAutomatically() { Container container = createNonEmptyContainer(); Signature signature = createSignatureBy(container, pkcs12EccSignatureToken); - Assert.assertNotNull(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertNotNull(signature); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); } @@ -340,10 +346,10 @@ public void signWithDeterminedSignatureDigestAlgorithm() throws Exception { withSignatureDigestAlgorithm(digestAlgorithm).withSigningCertificate(pkcs12SignatureToken.getCertificate()). buildDataToSign(); SignatureParameters signatureParameters = dataToSign.getSignatureParameters(); - Assert.assertEquals(DigestAlgorithm.SHA256, signatureParameters.getSignatureDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA256, signatureParameters.getSignatureDigestAlgorithm()); Signature signature = TestDataBuilderUtil.makeSignature(container, dataToSign); - Assert.assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", signature.getSignatureMethod()); - Assert.assertTrue(container.validate().isValid()); + assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", signature.getSignatureMethod()); + assertTrue(container.validate().isValid()); } @Test @@ -363,7 +369,7 @@ public void openSignatureFromNull_shouldThrowException() { public void openSignatureFromExistingSignatureDocument() throws Exception { Container container = createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/test.txt")); Signature signature = openSignatureFromExistingSignatureDocument(container); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); } @Test @@ -385,7 +391,7 @@ public void openSignature_withDataFilesMismatch_shouldBeInvalid() throws Excepti Container container = createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/word_file.docx")); Signature signature = openAdESSignature(container); ValidationResult result = signature.validateSignature(); - Assert.assertFalse(result.isValid()); + assertFalse(result.isValid()); TestAssert.assertContainsErrors(result.getErrors(), "The reference data object has not been found!" ); @@ -408,7 +414,7 @@ public void openXadesSignature_andSavingContainer_shouldNotChangeSignature() thr container = ContainerOpener.open(file); byte[] originalSignatureBytes = FileUtils.readFileToByteArray(new File("src/test/resources/testFiles/xades/valid-bdoc-tm.xml")); byte[] signatureBytes = container.getSignatures().get(0).getAdESSignature(); - Assert.assertArrayEquals(originalSignatureBytes, signatureBytes); + assertArrayEquals(originalSignatureBytes, signatureBytes); } @Test @@ -430,10 +436,10 @@ public void signCustomContainer() throws Exception { SignatureBuilder.setSignatureBuilderForContainerType("TEST-FORMAT", MockSignatureBuilder.class); Container container = TestDataBuilderUtil.createContainerWithFile(testFolder, "TEST-FORMAT"); DataToSign dataToSign = TestDataBuilderUtil.buildDataToSign(container); - Assert.assertNotNull(dataToSign); + assertNotNull(dataToSign); byte[] signatureValue = TestSigningUtil.sign(dataToSign.getDataToSign(), dataToSign.getDigestAlgorithm()); Signature signature = dataToSign.finalize(signatureValue); - Assert.assertNotNull(signature); + assertNotNull(signature); } @Test @@ -442,15 +448,15 @@ public void signAsiceContainerWithExtRsaLt() { DataToSign dataToSign = SignatureBuilder.aSignature(container).withSignatureDigestAlgorithm(DigestAlgorithm.SHA256). withSignatureProfile(SignatureProfile.LT).withSigningCertificate(pkcs12SignatureToken.getCertificate()). buildDataToSign(); - Assert.assertNotNull(dataToSign); + assertNotNull(dataToSign); // This call mocks the using of external signing functionality with hashcode byte[] signatureValue = pkcs12SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign()); Signature signature = dataToSign.finalize(signatureValue); - Assert.assertNotNull(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertNotNull(signature); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("rsa")); container.addSignature(signature); - Assert.assertTrue(container.validate().isValid()); + assertTrue(container.validate().isValid()); container.saveAsFile(getFileBy("asice")); } @@ -460,7 +466,7 @@ public void signAsiceContainerWithExtEccLt() { DataToSign dataToSign = SignatureBuilder.aSignature(container).withSignatureDigestAlgorithm(DigestAlgorithm.SHA256). withSignatureProfile(SignatureProfile.LT).withSigningCertificate(pkcs12EccSignatureToken.getCertificate()). withEncryptionAlgorithm(EncryptionAlgorithm.ECDSA).buildDataToSign(); - Assert.assertNotNull(dataToSign); + assertNotNull(dataToSign); // This call mocks the using of external signing functionality with hashcode byte[] signatureValue = new byte[1]; int counter = 5; @@ -470,11 +476,11 @@ public void signAsiceContainerWithExtEccLt() { } while (signatureValue.length == 72 && counter > 0); // Somehow the signature with length 72 is not correct Signature signature = dataToSign.finalize(signatureValue); - Assert.assertNotNull(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertNotNull(signature); + assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); container.addSignature(signature); - Assert.assertTrue(container.validate().isValid()); + assertTrue(container.validate().isValid()); container.saveAsFile(getFileBy("asice")); } @@ -485,7 +491,7 @@ public void invokeSigningForCustomContainer() throws Exception { Container container = TestDataBuilderUtil.createContainerWithFile(testFolder, "TEST-FORMAT"); Signature signature = SignatureBuilder.aSignature(container).withSignatureToken(pkcs12SignatureToken). invokeSigning(); - Assert.assertNotNull(signature); + assertNotNull(signature); } @Test @@ -508,7 +514,7 @@ public void invokeSigning_whenOverridingBDocContainerFormat() { SignatureBuilder.setSignatureBuilderForContainerType("BDOC", MockSignatureBuilder.class); Container container = createNonEmptyContainer(); Signature signature = createSignatureBy(container, pkcs12SignatureToken); - Assert.assertNotNull(signature); + assertNotNull(signature); CustomContainer.resetType(); } @@ -516,16 +522,16 @@ public void invokeSigning_whenOverridingBDocContainerFormat() { public void bDocContainerWithTMSignature_signWithBesSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.B_BES); assertBBesSignature(signature); - Assert.assertFalse(signature.validateSignature().isValid()); + assertFalse(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertBBesSignature(container.getSignatures().get(1)); } @@ -534,16 +540,16 @@ public void bDocContainerWithTMSignature_signWithBesSignature_shouldSucceed() { public void bDocContainerWithTMSignature_signWithTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.LT); assertTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); } @@ -552,16 +558,16 @@ public void bDocContainerWithTMSignature_signWithTimestampSignature_shouldSuccee public void bDocContainerWithTMSignature_signWithArchiveTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.LTA); assertArchiveTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertArchiveTimestampSignature(container.getSignatures().get(1)); } @@ -570,7 +576,7 @@ public void bDocContainerWithTMSignature_signWithArchiveTimestampSignature_shoul public void bDocContainerWithTMSignature_withSignatureProfileB_EPES_shouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -586,7 +592,7 @@ public void bDocContainerWithTMSignature_withSignatureProfileB_EPES_shouldFail() public void bDocContainerWithTMSignature_withSignatureProfileLT_TM_shouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -602,7 +608,7 @@ public void bDocContainerWithTMSignature_withSignatureProfileLT_TM_shouldFail() public void bDocContainerWithTMSignature_withOwnSignaturePolicy_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -618,7 +624,7 @@ public void bDocContainerWithTMSignature_withOwnSignaturePolicy_ShouldFail() { public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithB_BES_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.B_BES); @@ -635,7 +641,7 @@ public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithB_BES_ShouldF public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithLT_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LT); @@ -652,7 +658,7 @@ public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithLT_ShouldFail public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithLTA_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_SIG); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LTA); @@ -669,17 +675,17 @@ public void bDocContainerWithTMSignature_withOwnSignaturePolicyWithLTA_ShouldFai public void bDocContainerWithTMAndTSSignature_signWithBesSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); Signature signature = signContainerWithSignature(container, SignatureProfile.B_BES); assertBBesSignature(signature); - Assert.assertFalse(signature.validateSignature().isValid()); + assertFalse(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(3, container.getSignatures().size()); + assertSame(3, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); assertBBesSignature(container.getSignatures().get(2)); @@ -689,17 +695,17 @@ public void bDocContainerWithTMAndTSSignature_signWithBesSignature_shouldSucceed public void bDocContainerWithTMAndTSSignature_signWithTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); Signature signature = signContainerWithSignature(container, SignatureProfile.LT); assertTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(3, container.getSignatures().size()); + assertSame(3, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); assertTimestampSignature(container.getSignatures().get(2)); @@ -709,17 +715,17 @@ public void bDocContainerWithTMAndTSSignature_signWithTimestampSignature_shouldS public void bDocContainerWithTMAndTSSignature_signWithArchiveTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); Signature signature = signContainerWithSignature(container, SignatureProfile.LTA); assertArchiveTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(3, container.getSignatures().size()); + assertSame(3, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); assertArchiveTimestampSignature(container.getSignatures().get(2)); @@ -729,7 +735,7 @@ public void bDocContainerWithTMAndTSSignature_signWithArchiveTimestampSignature_ public void bDocContainerWithTMAndTSSignature_withSignatureProfileB_EPES_shouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -746,7 +752,7 @@ public void bDocContainerWithTMAndTSSignature_withSignatureProfileB_EPES_shouldF public void bDocContainerWithTMAndTSSignature_withSignatureProfileLT_TM_shouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -763,7 +769,7 @@ public void bDocContainerWithTMAndTSSignature_withSignatureProfileLT_TM_shouldFa public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicy_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -780,7 +786,7 @@ public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicy_ShouldFail( public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithB_BES_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) @@ -798,7 +804,7 @@ public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithB_BES_Sh public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithLT_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) @@ -816,7 +822,7 @@ public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithLT_Shoul public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithLTA_ShouldFail() { Container container = buildContainer(BDOC, BDOC_WITH_TM_AND_TS_SIG); assertBDocContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimemarkSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) @@ -834,7 +840,7 @@ public void bDocContainerWithTMAndTSSignature_withOwnSignaturePolicyWithLTA_Shou public void bDocContainerWithoutSignatures_signWithoutAssignedProfile_defaultProfileIsUsed_shouldSucceedWithTimestampSignature() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); DataToSign dataToSign = SignatureBuilder.aSignature(container) .withSigningCertificate(pkcs12SignatureToken.getCertificate()) @@ -842,13 +848,13 @@ public void bDocContainerWithoutSignatures_signWithoutAssignedProfile_defaultPro .buildDataToSign(); Signature signature = dataToSign.finalize(pkcs12SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); - Assert.assertSame(Constant.Default.SIGNATURE_PROFILE, signature.getProfile()); + assertSame(Constant.Default.SIGNATURE_PROFILE, signature.getProfile()); assertTimestampSignature(signature); assertValidSignature(signature); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); } @@ -856,15 +862,15 @@ public void bDocContainerWithoutSignatures_signWithoutAssignedProfile_defaultPro public void bDocContainerWithoutSignatures_signWithBesSignature_shouldSucceed() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.B_BES); assertBBesSignature(signature); - Assert.assertFalse(signature.validateSignature().isValid()); + assertFalse(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertBBesSignature(container.getSignatures().get(0)); } @@ -872,15 +878,15 @@ public void bDocContainerWithoutSignatures_signWithBesSignature_shouldSucceed() public void bDocContainerWithoutSignatures_signWithTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.LT); assertTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); } @@ -888,15 +894,15 @@ public void bDocContainerWithoutSignatures_signWithTimestampSignature_shouldSucc public void bDocContainerWithoutSignatures_signWithArchiveTimestampSignature_shouldSucceed() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.LTA); assertArchiveTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertBDocContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertArchiveTimestampSignature(container.getSignatures().get(0)); } @@ -904,7 +910,7 @@ public void bDocContainerWithoutSignatures_signWithArchiveTimestampSignature_sho public void bDocContainerWithoutSignatures_withSignatureProfileB_EPES_shouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -919,7 +925,7 @@ public void bDocContainerWithoutSignatures_withSignatureProfileB_EPES_shouldFail public void bDocContainerWithoutSignatures_withSignatureProfileLT_TM_shouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -934,7 +940,7 @@ public void bDocContainerWithoutSignatures_withSignatureProfileLT_TM_shouldFail( public void bDocContainerWithoutSignatures_withOwnSignaturePolicy_ShouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -949,7 +955,7 @@ public void bDocContainerWithoutSignatures_withOwnSignaturePolicy_ShouldFail() { public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithB_BES_ShouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.B_BES); @@ -965,7 +971,7 @@ public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithB_BES_Shoul public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithLT_ShouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LT); @@ -981,7 +987,7 @@ public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithLT_ShouldFa public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithLTA_ShouldFail() { Container container = buildContainer(BDOC, ASIC_WITH_NO_SIG); assertBDocContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LTA); @@ -997,7 +1003,7 @@ public void bDocContainerWithoutSignatures_withOwnSignaturePolicyWithLTA_ShouldF public void asiceContainerWithoutSignatures_signWithoutAssignedProfile_defaultPofileIsUsed_shouldSucceedWithTimestampSignature() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); DataToSign dataToSign = SignatureBuilder.aSignature(container) .withSigningCertificate(pkcs12SignatureToken.getCertificate()) @@ -1005,13 +1011,13 @@ public void asiceContainerWithoutSignatures_signWithoutAssignedProfile_defaultPo .buildDataToSign(); Signature signature = dataToSign.finalize(pkcs12SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); - Assert.assertSame(Constant.Default.SIGNATURE_PROFILE, signature.getProfile()); + assertSame(Constant.Default.SIGNATURE_PROFILE, signature.getProfile()); assertTimestampSignature(signature); assertValidSignature(signature); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); } @@ -1019,14 +1025,14 @@ public void asiceContainerWithoutSignatures_signWithoutAssignedProfile_defaultPo public void signWith256EcKey_withoutAssigningSignatureDigestAlgo_sha256SignatureDigestAlgoIsUsed() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); DataToSign dataToSign = SignatureBuilder.aSignature(container) .withSigningCertificate(pkcs12EccSignatureToken.getCertificate()) .buildDataToSign(); Signature signature = dataToSign.finalize(pkcs12EccSignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); - Assert.assertEquals(DigestAlgorithm.SHA256, dataToSign.getSignatureParameters().getSignatureDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA256, dataToSign.getSignatureParameters().getSignatureDigestAlgorithm()); assertValidSignature(signature); } @@ -1034,14 +1040,14 @@ public void signWith256EcKey_withoutAssigningSignatureDigestAlgo_sha256Signature public void signWith384EcKey_withoutAssigningSignatureDigestAlgo_sha384SignatureDigestAlgoIsUsed() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); DataToSign dataToSign = SignatureBuilder.aSignature(container) .withSigningCertificate(pkcs12Esteid2018SignatureToken.getCertificate()) .buildDataToSign(); Signature signature = dataToSign.finalize(pkcs12Esteid2018SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); - Assert.assertEquals(DigestAlgorithm.SHA384, dataToSign.getSignatureParameters().getSignatureDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA384, dataToSign.getSignatureParameters().getSignatureDigestAlgorithm()); assertValidSignature(signature); } @@ -1054,26 +1060,26 @@ public void signWithDifferentDataFileAndSignatureDigestAlgorithm() { .withSigningCertificate(pkcs12SignatureToken.getCertificate()) .buildDataToSign(); SignatureParameters signatureParameters = dataToSign.getSignatureParameters(); - Assert.assertEquals(DigestAlgorithm.SHA384, signatureParameters.getSignatureDigestAlgorithm()); - Assert.assertEquals(DigestAlgorithm.SHA512, signatureParameters.getDataFileDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA384, signatureParameters.getSignatureDigestAlgorithm()); + assertEquals(DigestAlgorithm.SHA512, signatureParameters.getDataFileDigestAlgorithm()); Signature signature = dataToSign.finalize(pkcs12SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); - Assert.assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", signature.getSignatureMethod()); - Assert.assertTrue(container.validate().isValid()); + assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", signature.getSignatureMethod()); + assertTrue(container.validate().isValid()); } @Test public void asiceContainerWithoutSignatures_signWithBesSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.B_BES); assertBBesSignature(signature); - Assert.assertFalse(signature.validateSignature().isValid()); + assertFalse(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertBBesSignature(container.getSignatures().get(0)); } @@ -1081,15 +1087,15 @@ public void asiceContainerWithoutSignatures_signWithBesSignature_shouldSucceed() public void asiceContainerWithoutSignatures_signWithTimestampSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.LT); assertTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); } @@ -1097,15 +1103,15 @@ public void asiceContainerWithoutSignatures_signWithTimestampSignature_shouldSuc public void asiceContainerWithoutSignatures_signWithArchiveTimestampSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); Signature signature = signContainerWithSignature(container, SignatureProfile.LTA); assertArchiveTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertArchiveTimestampSignature(container.getSignatures().get(0)); } @@ -1113,7 +1119,7 @@ public void asiceContainerWithoutSignatures_signWithArchiveTimestampSignature_sh public void asiceContainerWithoutSignatures_withSignatureProfileB_EPES_shouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -1128,7 +1134,7 @@ public void asiceContainerWithoutSignatures_withSignatureProfileB_EPES_shouldFai public void asiceContainerWithoutSignatures_withSignatureProfileLT_TM_shouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -1143,7 +1149,7 @@ public void asiceContainerWithoutSignatures_withSignatureProfileLT_TM_shouldFail public void asiceContainerWithoutSignatures_withOwnSignaturePolicy_ShouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); NotSupportedException caughtException = assertThrows( @@ -1158,7 +1164,7 @@ public void asiceContainerWithoutSignatures_withOwnSignaturePolicy_ShouldFail() public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithB_BES_ShouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.B_BES); @@ -1174,7 +1180,7 @@ public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithB_BES_Shou public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithLT_ShouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LT); @@ -1190,7 +1196,7 @@ public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithLT_ShouldF public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithLTA_ShouldFail() { Container container = buildContainer(ASICE, ASIC_WITH_NO_SIG); assertAsicEContainer(container); - Assert.assertTrue(container.getSignatures().isEmpty()); + assertTrue(container.getSignatures().isEmpty()); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LTA); @@ -1206,16 +1212,16 @@ public void asiceContainerWithoutSignatures_withOwnSignaturePolicyWithLTA_Should public void asicEContainerWithTSSignature_signWithBesSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.B_BES); assertBBesSignature(signature); - Assert.assertFalse(signature.validateSignature().isValid()); + assertFalse(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); assertBBesSignature(container.getSignatures().get(1)); } @@ -1224,16 +1230,16 @@ public void asicEContainerWithTSSignature_signWithBesSignature_shouldSucceed() { public void asicEContainerWithTSSignature_signWithTimestampSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.LT); assertTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); assertTimestampSignature(container.getSignatures().get(1)); } @@ -1242,16 +1248,16 @@ public void asicEContainerWithTSSignature_signWithTimestampSignature_shouldSucce public void asicEContainerWithTSSignature_signWithArchiveTimestampSignature_shouldSucceed() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); Signature signature = signContainerWithSignature(container, SignatureProfile.LTA); assertArchiveTimestampSignature(signature); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); container.addSignature(signature); assertAsicEContainer(container); - Assert.assertSame(2, container.getSignatures().size()); + assertSame(2, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); assertArchiveTimestampSignature(container.getSignatures().get(1)); } @@ -1260,7 +1266,7 @@ public void asicEContainerWithTSSignature_signWithArchiveTimestampSignature_shou public void asicEContainerWithTSSignature_withSignatureProfileB_EPES_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -1276,7 +1282,7 @@ public void asicEContainerWithTSSignature_withSignatureProfileB_EPES_ShouldFail( public void asicEContainerWithTSSignature_withSignatureProfileLT_TM_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -1292,7 +1298,7 @@ public void asicEContainerWithTSSignature_withSignatureProfileLT_TM_ShouldFail() public void asicEContainerWithTSSignature_withOwnSignaturePolicy_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container); @@ -1308,7 +1314,7 @@ public void asicEContainerWithTSSignature_withOwnSignaturePolicy_ShouldFail() { public void asicEContainerWithTSSignature_withOwnSignaturePolicyWithB_BES_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.B_BES); @@ -1325,7 +1331,7 @@ public void asicEContainerWithTSSignature_withOwnSignaturePolicyWithB_BES_Should public void asicEContainerWithTSSignature_withOwnSignaturePolicyWithLT_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LT); @@ -1342,7 +1348,7 @@ public void asicEContainerWithTSSignature_withOwnSignaturePolicyWithLT_ShouldFai public void asicEContainerWithTSSignature_withOwnSignaturePolicyWithLTA_ShouldFail() { Container container = buildContainer(ASICE, ASICE_WITH_TS_SIG); assertAsicEContainer(container); - Assert.assertSame(1, container.getSignatures().size()); + assertSame(1, container.getSignatures().size()); assertTimestampSignature(container.getSignatures().get(0)); SignatureBuilder signatureBuilder = SignatureBuilder.aSignature(container) .withSignatureProfile(SignatureProfile.LTA); @@ -1403,8 +1409,8 @@ public void dataToSignFinalize_networkExceptionIsNotCaught() { private Signature signContainerWithSignature(Container container, SignatureProfile signatureProfile) { DataToSign dataToSign = buildDataToSign(container, signatureProfile); - Assert.assertNotNull(dataToSign); - Assert.assertEquals(signatureProfile, dataToSign.getSignatureParameters().getSignatureProfile()); + assertNotNull(dataToSign); + assertEquals(signatureProfile, dataToSign.getSignatureParameters().getSignatureProfile()); return dataToSign.finalize(pkcs12SignatureToken.sign(dataToSign.getDigestAlgorithm(), dataToSign.getDataToSign())); } @@ -1441,7 +1447,7 @@ protected void after() { private Signature openSignatureFromExistingSignatureDocument(Container container) throws IOException { Signature signature = openAdESSignature(container); - Assert.assertEquals("id-6a5d6671af7a9e0ab9a5e4d49d69800d", signature.getId()); + assertEquals("id-6a5d6671af7a9e0ab9a5e4d49d69800d", signature.getId()); return signature; } @@ -1451,11 +1457,11 @@ private Signature openAdESSignature(Container container) throws IOException { } private void assertSignatureIsValid(Signature signature, SignatureProfile expectedSignatureProfile) { - Assert.assertNotNull(signature.getOCSPResponseCreationTime()); - Assert.assertEquals(expectedSignatureProfile, signature.getProfile()); - Assert.assertNotNull(signature.getClaimedSigningTime()); - Assert.assertNotNull(signature.getAdESSignature()); + assertNotNull(signature.getOCSPResponseCreationTime()); + assertEquals(expectedSignatureProfile, signature.getProfile()); + assertNotNull(signature.getClaimedSigningTime()); + assertNotNull(signature.getAdESSignature()); assertThat(signature.getAdESSignature().length, greaterThan(1)); - Assert.assertTrue(signature.validateSignature().isValid()); + assertTrue(signature.validateSignature().isValid()); } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/CommonOCSPSourceTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/CommonOCSPSourceTest.java index fe18b3a1c..ba4fb29b3 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/CommonOCSPSourceTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/CommonOCSPSourceTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl; import eu.europa.esig.dss.model.x509.CertificateToken; @@ -58,6 +68,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; @RunWith(MockitoJUnitRunner.class) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/EmptyDataFilesSignatureFinalizerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/EmptyDataFilesSignatureFinalizerTest.java index 3ac7e5f52..0f3471370 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/EmptyDataFilesSignatureFinalizerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/EmptyDataFilesSignatureFinalizerTest.java @@ -21,6 +21,8 @@ import java.util.Collections; import java.util.List; +import static org.junit.Assert.assertThrows; + public abstract class EmptyDataFilesSignatureFinalizerTest extends AbstractTest { protected abstract SignatureFinalizer createSignatureFinalizerWithDataFiles(List dataFiles); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/SimpleHttpGetDataLoaderTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/SimpleHttpGetDataLoaderTest.java index 224126dd8..6f719ce0f 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/SimpleHttpGetDataLoaderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/SimpleHttpGetDataLoaderTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl; import ch.qos.logback.classic.Level; @@ -262,7 +272,7 @@ public void requestShouldFollowHttpsToHttpRedirectOnAllowedHttp3xx_RedirectsEnab */ @Test public void requestShouldFollowRedirectsOfValidCertificate() { - byte[] response = createDataLoader(2).request("http://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt", true); + byte[] response = createDataLoader(3).request("http://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt", true); CertificateToken loadedCertificate = DSSUtils.loadCertificate(response); Assert.assertTrue( "Certificate subject principal should contain 'CN=EE Certification Centre Root CA'", @@ -270,7 +280,8 @@ public void requestShouldFollowRedirectsOfValidCertificate() { ); assertLogInOrder( Matchers.matchesPattern("Received HTTP 3[0-9]{2} from 'http://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt', redirecting to 'https://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt'"), - Matchers.matchesPattern("Received HTTP 3[0-9]{2} from 'https://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt', redirecting to 'https://www.sk.ee/upload/files/EE_Certification_Centre_Root_CA.der.crt'"), + Matchers.matchesPattern("Received HTTP 3[0-9]{2} from 'https://www.sk.ee/certs/EE_Certification_Centre_Root_CA.der.crt', redirecting to 'http://www.sk.ee/upload/files/EE_Certification_Centre_Root_CA.der.crt'"), + Matchers.matchesPattern("Received HTTP 3[0-9]{2} from 'http://www.sk.ee/upload/files/EE_Certification_Centre_Root_CA.der.crt', redirecting to 'https://www.sk.ee/upload/files/EE_Certification_Centre_Root_CA.der.crt'"), Matchers.matchesPattern("Reading response of specific size: [0-9]+") ); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/AsicContainerParserZipBombingTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/AsicContainerParserZipBombingTest.java index 53ef5123c..68b0226b5 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/AsicContainerParserZipBombingTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/AsicContainerParserZipBombingTest.java @@ -3,9 +3,12 @@ import org.digidoc4j.AbstractTest; import org.digidoc4j.Configuration; import org.digidoc4j.exceptions.TechnicalException; -import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; + public abstract class AsicContainerParserZipBombingTest extends AbstractTest { protected static final String MULTIPLE_DATAFILE_CONTAINER_PATH = "src/test/resources/testFiles/valid-containers/compression-ratio-46.55-with-8-datafiles.asice"; @@ -83,11 +86,11 @@ protected static Configuration createTestConfigurationWithThresholdAndRatio(long protected static void assertReadSucceeds(int expectedDataFileCount, AsicContainerParser asicContainerParser) { AsicParseResult asicParseResult = asicContainerParser.read(); - Assert.assertNotNull(asicParseResult); - Assert.assertNotNull(asicParseResult.getSignatures()); - Assert.assertEquals(1, asicParseResult.getSignatures().size()); - Assert.assertNotNull(asicParseResult.getDataFiles()); - Assert.assertEquals(expectedDataFileCount, asicParseResult.getDataFiles().size()); + assertNotNull(asicParseResult); + assertNotNull(asicParseResult.getSignatures()); + assertEquals(1, asicParseResult.getSignatures().size()); + assertNotNull(asicParseResult.getDataFiles()); + assertEquals(expectedDataFileCount, asicParseResult.getDataFiles().size()); } protected static void assertReadThrowsZipBombingException(AsicContainerParser asicContainerParser) { @@ -95,7 +98,7 @@ protected static void assertReadThrowsZipBombingException(AsicContainerParser as TechnicalException.class, asicContainerParser::read ); - Assert.assertEquals( + assertEquals( "Zip Bomb detected in the ZIP container. Validation is interrupted.", caughtException.getMessage() ); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/EmptyDataFilesContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/EmptyDataFilesContainerTest.java index 0894826b8..5b020e8e2 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/EmptyDataFilesContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/EmptyDataFilesContainerTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.asic; import org.digidoc4j.AbstractTest; @@ -12,6 +22,8 @@ import java.io.IOException; import java.io.InputStream; +import static org.junit.Assert.assertThrows; + public abstract class EmptyDataFilesContainerTest extends AbstractTest { protected static final String TEST_FILE_NAME = "test.txt"; diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/TslRefreshCallbackInteractionTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/TslRefreshCallbackInteractionTest.java index 2067db0ee..a2afa600e 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/TslRefreshCallbackInteractionTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/TslRefreshCallbackInteractionTest.java @@ -20,13 +20,15 @@ import org.digidoc4j.exceptions.TslRefreshException; import org.digidoc4j.impl.ConfigurationSingeltonHolder; import org.digidoc4j.test.TestAssert; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + @RunWith(MockitoJUnitRunner.class) public class TslRefreshCallbackInteractionTest extends AbstractTest { @@ -72,7 +74,7 @@ public void testCallbackThrowsExceptionOnManualRefresh() { mockEnsureTSLState(true); configuration.getTSL().refresh(); - Assert.assertEquals("Exception message", caughtException.getMessage()); + assertEquals("Exception message", caughtException.getMessage()); verifyCallbackCalled(2); } @@ -109,7 +111,7 @@ public void testCallbackThrowsExceptionOnOpeningContainer() { () -> ContainerOpener.open(ASICE_WITH_TS_SIG) ); - Assert.assertEquals("Exception message", caughtException.getMessage()); + assertEquals("Exception message", caughtException.getMessage()); verifyCallbackCalled(1); } @@ -127,7 +129,7 @@ public void testCallbackThrowsExceptionOnValidatingContainer() { () -> container.validate() ); - Assert.assertEquals("Error validating signatures on multiple threads: Exception message", caughtException.getMessage()); + assertEquals("Error validating signatures on multiple threads: Exception message", caughtException.getMessage()); verifyCallbackCalled(1); } @@ -169,7 +171,7 @@ public void testCallbackThrowsExceptionOnSigningContainer() { () -> createSignatureBy(container, pkcs12Esteid2018SignatureToken) ); - Assert.assertEquals("Exception message", caughtException.getMessage()); + assertEquals("Exception message", caughtException.getMessage()); verifyCallbackCalled(1); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java index cb6f601af..bf0dfc654 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java @@ -45,7 +45,6 @@ import org.digidoc4j.impl.asic.asice.AsicESignature; import org.digidoc4j.impl.asic.asice.bdoc.BDocContainer; import org.digidoc4j.impl.asic.asice.bdoc.BDocSignature; -import org.digidoc4j.signers.PKCS12SignatureToken; import org.digidoc4j.test.TestAssert; import org.hamcrest.Matchers; import org.junit.Assert; @@ -73,6 +72,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThrows; public class BDocContainerTest extends AbstractTest { @@ -884,9 +884,10 @@ public void containerWithBESProfileHasNoValidationErrors() { @Test public void signWithECCCertificate() { Container container = createNonEmptyContainerBy(Container.DocumentType.BDOC); - Signature signature = SignatureBuilder.aSignature(container). - withSignatureToken(new PKCS12SignatureToken("src/test/resources/testFiles/p12/MadDogOY.p12", "test".toCharArray())). - withEncryptionAlgorithm(EncryptionAlgorithm.ECDSA).invokeSigning(); + Signature signature = SignatureBuilder.aSignature(container) + .withSignatureToken(pkcs12EccSignatureToken) + .withEncryptionAlgorithm(EncryptionAlgorithm.ECDSA) + .invokeSigning(); container.addSignature(signature); Assert.assertEquals(1, container.getSignatures().size()); Assert.assertTrue(container.validate().isValid()); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java index 3c1214f0b..75afa7a06 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java @@ -34,6 +34,7 @@ import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertThrows; public class BDocSerializationTest extends AbstractTest { diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ContainerParticlesRemovalTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ContainerParticlesRemovalTest.java index e7133ca87..3e40dbff3 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ContainerParticlesRemovalTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ContainerParticlesRemovalTest.java @@ -44,6 +44,7 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java index 098f1b1c6..80e990b56 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.bdoc; import org.digidoc4j.Configuration; @@ -9,9 +19,13 @@ import org.digidoc4j.exceptions.InvalidDataFileException; import org.digidoc4j.impl.asic.EmptyDataFilesContainerTest; import org.digidoc4j.test.TestAssert; -import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + public class EmptyDataFilesBdocContainerTest extends EmptyDataFilesContainerTest { @Override @@ -30,13 +44,13 @@ public void testValidateSignedContainerWithEmptyDataFiles() { ContainerValidationResult validationResult = container.validate(); - Assert.assertTrue(validationResult.isValid()); - Assert.assertNotNull(validationResult.getWarnings()); - Assert.assertEquals(2, validationResult.getWarnings().size()); + assertTrue(validationResult.isValid()); + assertNotNull(validationResult.getWarnings()); + assertEquals(2, validationResult.getWarnings().size()); TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getWarnings()); TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getWarnings()); - Assert.assertNotNull(validationResult.getContainerWarnings()); - Assert.assertEquals(2, validationResult.getContainerWarnings().size()); + assertNotNull(validationResult.getContainerWarnings()); + assertEquals(2, validationResult.getContainerWarnings().size()); TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getContainerWarnings()); TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getContainerWarnings()); } @@ -52,7 +66,7 @@ public void testInvokeSigningForSignedContainerWithEmptyDataFiles() { .invokeSigning() ); - Assert.assertEquals("Cannot sign empty datafile: empty-file-2.txt", caughtException.getMessage()); + assertEquals("Cannot sign empty datafile: empty-file-2.txt", caughtException.getMessage()); TestAssert.assertSuppressed(caughtException, InvalidDataFileException.class, "Cannot sign empty datafile: empty-file-4.txt"); } @@ -67,14 +81,14 @@ public void testBuildDataToSignForSignedContainerWithEmptyDataFiles() { .buildDataToSign() ); - Assert.assertEquals("Cannot sign empty datafile: empty-file-2.txt", caughtException.getMessage()); + assertEquals("Cannot sign empty datafile: empty-file-2.txt", caughtException.getMessage()); TestAssert.assertSuppressed(caughtException, InvalidDataFileException.class, "Cannot sign empty datafile: empty-file-4.txt"); } private Container loadSignedContainerWithEmptyDataFiles() { Container container = ContainerOpener .open("src/test/resources/testFiles/valid-containers/signed-container-with-empty-datafiles.bdoc", configuration); - Assert.assertEquals(Constant.BDOC_CONTAINER_TYPE, container.getType()); + assertEquals(Constant.BDOC_CONTAINER_TYPE, container.getType()); return container; } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ExtendingBDocContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ExtendingBDocContainerTest.java index 1e1315e7c..5b8176062 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ExtendingBDocContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ExtendingBDocContainerTest.java @@ -25,6 +25,7 @@ import static java.lang.Thread.sleep; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThrows; public class ExtendingBDocContainerTest extends AbstractTest { diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java index 06cf12fdb..7b1adb771 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java @@ -66,6 +66,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.matchesRegex; import static org.hamcrest.Matchers.startsWith; +import static org.junit.Assert.assertThrows; /** * Description of tests by their suffix: diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index 912541234..ee275d776 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -1,12 +1,12 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.bdoc; @@ -51,6 +51,8 @@ import java.security.cert.X509Certificate; import java.util.List; +import static org.junit.Assert.assertThrows; + public class ValidationTest extends AbstractTest { public static final Configuration PROD_CONFIGURATION = new Configuration(Configuration.Mode.PROD); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java index 47dd3080e..7d7cd5089 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.bdoc.asic; import org.digidoc4j.Configuration; @@ -12,6 +22,8 @@ import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.assertThrows; + public class EmptyDataFilesAsicEContainerTest extends EmptyDataFilesContainerTest { @Override diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesSigningDssFacadeTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesSigningDssFacadeTest.java index de9f3a144..02f66b5c0 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesSigningDssFacadeTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesSigningDssFacadeTest.java @@ -1,17 +1,17 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.bdoc.xades; -import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.enumerations.EncryptionAlgorithm; +import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.FileDocument; import eu.europa.esig.dss.model.Policy; import eu.europa.esig.dss.model.SignerLocation; @@ -20,7 +20,6 @@ import org.digidoc4j.DataFile; import org.digidoc4j.DigestAlgorithm; import org.digidoc4j.impl.asic.xades.XadesSigningDssFacade; -import org.digidoc4j.signers.PKCS12SignatureToken; import org.digidoc4j.test.TestAssert; import org.junit.Assert; import org.junit.Test; @@ -60,13 +59,12 @@ public void signDocumentWithSha512() throws Exception { @Test public void signDocumentWithECC() throws Exception { - PKCS12SignatureToken eccSignatureToken = new PKCS12SignatureToken("src/test/resources/testFiles/p12/MadDogOY.p12", "test".toCharArray()); - X509Certificate signingCert = eccSignatureToken.getCertificate(); + X509Certificate signingCert = pkcs12EccSignatureToken.getCertificate(); this.facade.setEncryptionAlgorithm(EncryptionAlgorithm.ECDSA); this.facade.setSigningCertificate(signingCert); List dataFilesToSign = this.createDataFilesToSign(); byte[] dataToSign = this.facade.getDataToSign(dataFilesToSign); - byte[] signatureValue = eccSignatureToken.sign(DigestAlgorithm.SHA256, dataToSign); + byte[] signatureValue = pkcs12EccSignatureToken.sign(DigestAlgorithm.SHA256, dataToSign); TestAssert.assertDSSDocumentIsSigned(this.facade.signDocument(signatureValue, dataFilesToSign)); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java index c0f98d100..26d31b38c 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java @@ -136,7 +136,7 @@ public void createsECCSignature() throws Exception { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", - "-pkcs12", "src/test/resources/testFiles/p12/MadDogOY.p12", "test", "-e", "ECDSA"}; + "-pkcs12", "src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEIDSK2015.p12", "1234", "-e", "ECDSA"}; TestDigiDoc4JUtil.call(parameters); Assert.assertTrue(ContainerOpener.open(file).validate().isValid()); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/utils/KeyStoreDocumentTest.java b/digidoc4j/src/test/java/org/digidoc4j/utils/KeyStoreDocumentTest.java index 970ffd776..8109978b6 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/utils/KeyStoreDocumentTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/utils/KeyStoreDocumentTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.utils; import org.apache.commons.io.IOUtils; @@ -12,8 +22,6 @@ import org.digidoc4j.test.TestLog; import org.digidoc4j.test.util.TestCertificateUtil; import org.digidoc4j.test.util.TestKeyPairUtil; -import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -37,6 +45,11 @@ import java.util.Map; import java.util.UUID; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + public class KeyStoreDocumentTest extends AbstractTest { private static final String KEYSTORE_TYPE = "PKCS12"; @@ -66,7 +79,7 @@ public void testKeyStoreFailsToLoadWhenNotExisting() { () -> new KeyStoreDocument(nonExistingPath, KEYSTORE_TYPE, KEYSTORE_PASSWORD, minValidationInterval, maxWarningPeriod) ); - Assert.assertEquals("Resource not found: " + nonExistingPath, caughtException.getMessage()); + assertEquals("Resource not found: " + nonExistingPath, caughtException.getMessage()); testLog.verifyLogEmpty(); } @@ -82,7 +95,7 @@ public void testKeyStoreFailsToParseOnInvalidKeystoreType() { () -> new KeyStoreDocument(keyStorePath, invalidKeyStoreType, KEYSTORE_PASSWORD, minValidationInterval, maxWarningPeriod) ); - Assert.assertEquals("Failed to create key-store of type: " + invalidKeyStoreType, caughtException.getMessage()); + assertEquals("Failed to create key-store of type: " + invalidKeyStoreType, caughtException.getMessage()); testLog.verifyLogEmpty(); } @@ -98,7 +111,7 @@ public void testKeyStoreFailsToParseOnInvalidKeystorePassword() { () -> new KeyStoreDocument(keyStorePath, KEYSTORE_TYPE, invalidKeyStorePassword, minValidationInterval, maxWarningPeriod) ); - Assert.assertEquals("Failed to load key-store from: " + keyStorePath, caughtException.getMessage()); + assertEquals("Failed to load key-store from: " + keyStorePath, caughtException.getMessage()); testLog.verifyLogEmpty(); } @@ -126,17 +139,17 @@ public void testInitialKeystoreValidationWithWarningPeriod() throws Exception { String expiredTemplate = "Certificate from \"%s\" has already expired (%s) - alias: \"%s\"; subject: \"%s\""; String expiringTemplate = "Certificate from \"%s\" expires (%s) in about %d day(s) - alias: \"%s\"; subject: \"%s\""; testLog.verifyLogInOrder( - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), "expired-day", "CN=EXPIRED-DAY")), - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "expired-minute", "CN=EXPIRED-MINUTE")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), 8, "about-to-expire-1", "CN=ABOUT-TO-EXPIRE-1")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(2)).truncatedTo(ChronoUnit.SECONDS), 7, "about-to-expire-2", "CN=ABOUT-TO-EXPIRE-2")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(3)).truncatedTo(ChronoUnit.SECONDS), 6, "about-to-expire-3", "CN=ABOUT-TO-EXPIRE-3")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(4)).truncatedTo(ChronoUnit.SECONDS), 5, "about-to-expire-4", "CN=ABOUT-TO-EXPIRE-4")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(5)).truncatedTo(ChronoUnit.SECONDS), 4, "about-to-expire-5", "CN=ABOUT-TO-EXPIRE-5")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(6)).truncatedTo(ChronoUnit.SECONDS), 3, "about-to-expire-6", "CN=ABOUT-TO-EXPIRE-6")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(7)).truncatedTo(ChronoUnit.SECONDS), 2, "about-to-expire-7", "CN=ABOUT-TO-EXPIRE-7")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(8)).truncatedTo(ChronoUnit.SECONDS), 1, "about-to-expire-8", "CN=ABOUT-TO-EXPIRE-8")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(9)).minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), 0, "about-to-expire-minute", "CN=ABOUT-TO-EXPIRE-MINUTE")) + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), "expired-day", "CN=EXPIRED-DAY")), + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "expired-minute", "CN=EXPIRED-MINUTE")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), 8, "about-to-expire-1", "CN=ABOUT-TO-EXPIRE-1")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(2)).truncatedTo(ChronoUnit.SECONDS), 7, "about-to-expire-2", "CN=ABOUT-TO-EXPIRE-2")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(3)).truncatedTo(ChronoUnit.SECONDS), 6, "about-to-expire-3", "CN=ABOUT-TO-EXPIRE-3")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(4)).truncatedTo(ChronoUnit.SECONDS), 5, "about-to-expire-4", "CN=ABOUT-TO-EXPIRE-4")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(5)).truncatedTo(ChronoUnit.SECONDS), 4, "about-to-expire-5", "CN=ABOUT-TO-EXPIRE-5")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(6)).truncatedTo(ChronoUnit.SECONDS), 3, "about-to-expire-6", "CN=ABOUT-TO-EXPIRE-6")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(7)).truncatedTo(ChronoUnit.SECONDS), 2, "about-to-expire-7", "CN=ABOUT-TO-EXPIRE-7")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(8)).truncatedTo(ChronoUnit.SECONDS), 1, "about-to-expire-8", "CN=ABOUT-TO-EXPIRE-8")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(9)).minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), 0, "about-to-expire-minute", "CN=ABOUT-TO-EXPIRE-MINUTE")) ); assertKeyStoreDocumentContent(keyStoreFile, keyStoreDocument); } @@ -164,13 +177,13 @@ public void testInitialKeystoreValidationWithWarningDuration() throws Exception String expiredTemplate = "Certificate from \"%s\" has already expired (%s) - alias: \"%s\"; subject: \"%s\""; String expiringTemplate = "Certificate from \"%s\" expires (%s) in about 0 day(s) - alias: \"%s\"; subject: \"%s\""; testLog.verifyLogInOrder( - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), "expired-day", "CN=EXPIRED-DAY")), - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "expired-minute", "CN=EXPIRED-MINUTE")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-1", "CN=ABOUT-TO-EXPIRE-1")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(2L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-2", "CN=ABOUT-TO-EXPIRE-2")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(3L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-3", "CN=ABOUT-TO-EXPIRE-3")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(4L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-4", "CN=ABOUT-TO-EXPIRE-4")), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(5L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-5", "CN=ABOUT-TO-EXPIRE-5")) + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS), "expired-day", "CN=EXPIRED-DAY")), + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "expired-minute", "CN=EXPIRED-MINUTE")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(1L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-1", "CN=ABOUT-TO-EXPIRE-1")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(2L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-2", "CN=ABOUT-TO-EXPIRE-2")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(3L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-3", "CN=ABOUT-TO-EXPIRE-3")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(4L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-4", "CN=ABOUT-TO-EXPIRE-4")), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Duration.ofMinutes(5L)).truncatedTo(ChronoUnit.SECONDS), "about-to-expire-5", "CN=ABOUT-TO-EXPIRE-5")) ); assertKeyStoreDocumentContent(keyStoreFile, keyStoreDocument); } @@ -194,8 +207,8 @@ public void testOpenStreamTriggersValidationWhenPreviousValidationHasExpired() t String expiredTemplate = "Certificate from \"%s\" has already expired (%s) - alias: \"expired\"; subject: \"CN=EXPIRED\""; String expiringTemplate = "Certificate from \"%s\" expires (%s) in about 1 day(s) - alias: \"expiring\"; subject: \"CN=EXPIRING\""; testLog.verifyLogInOrder( - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) ); testLog.reset(); @@ -203,8 +216,8 @@ public void testOpenStreamTriggersValidationWhenPreviousValidationHasExpired() t stream.close(); testLog.verifyLogInOrder( - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) ); } @@ -227,8 +240,8 @@ public void testOpenStreamDoesNotTriggerValidationWhenPreviousValidationHasNotEx String expiredTemplate = "Certificate from \"%s\" has already expired (%s) - alias: \"expired\"; subject: \"CN=EXPIRED\""; String expiringTemplate = "Certificate from \"%s\" expires (%s) in about 1 day(s) - alias: \"expiring\"; subject: \"CN=EXPIRING\""; testLog.verifyLogInOrder( - Matchers.equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), - Matchers.equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) + equalTo(String.format(expiredTemplate, keyStorePath, now.minus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))), + equalTo(String.format(expiringTemplate, keyStorePath, now.plus(Period.ofDays(1)).truncatedTo(ChronoUnit.SECONDS))) ); testLog.reset(); @@ -274,13 +287,13 @@ private void assertKeyStoreDocumentContent(File sourceFile, KeyStoreDocument key try (InputStream in = keyStoreDocument.openStream()) { byte[] actualContent = IOUtils.toByteArray(in); - Assert.assertArrayEquals(expectedContent, actualContent); + assertArrayEquals(expectedContent, actualContent); } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { keyStoreDocument.writeTo(out); byte[] actualContent = out.toByteArray(); - Assert.assertArrayEquals(expectedContent, actualContent); + assertArrayEquals(expectedContent, actualContent); } } From cf018493b94c752e85c81257e37dee321e0ec976 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Wed, 25 Oct 2023 09:15:20 +0300 Subject: [PATCH 02/35] DD4J-929 Remove unnecessary test dependencies --- digidoc4j/pom.xml | 37 -- .../org/digidoc4j/main/DigiDoc4JTest.java | 451 ++++++------------ .../org/digidoc4j/test/ContainsPattern.java | 43 ++ 3 files changed, 187 insertions(+), 344 deletions(-) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index 902ca44a6..dff5984c8 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -35,9 +35,6 @@ 2.15.2 2.3.8 2.3.0.1 - 1.6.0 - 20230618 - 1.5.1 4.13.2 2.4 1.2.12 @@ -299,12 +296,6 @@ ${hamcrest.version} test - - com.jcabi - jcabi-matchers - ${jcabi-matchers.version} - test - org.mockito mockito-core @@ -371,34 +362,6 @@ ${jackson.version} test - - org.skyscreamer - jsonassert - ${jsonassert.version} - test - - - com.vaadin.external.google - android-json - - - - - org.json - json - ${json.version} - test - - - com.jayway.jsonpath - json-path - - - net.minidev - json-smart - - - com.googlecode.junit-toolbox junit-toolbox diff --git a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java index 26d31b38c..3700c3ef2 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java @@ -1,12 +1,12 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.main; @@ -25,12 +25,10 @@ import org.digidoc4j.test.util.TestCommonUtil; import org.digidoc4j.test.util.TestDigiDoc4JUtil; import org.digidoc4j.test.util.TestSigningUtil; -import org.hamcrest.core.StringContains; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; -import org.junit.contrib.java.lang.system.Assertion; import org.junit.contrib.java.lang.system.ExpectedSystemExit; import org.junit.contrib.java.lang.system.SystemOutRule; @@ -38,8 +36,12 @@ import java.io.IOException; import java.nio.file.Paths; -import static com.jcabi.matchers.RegexMatchers.containsPattern; import static org.digidoc4j.main.DigiDoc4J.isWarning; +import static org.digidoc4j.test.ContainsPattern.containsPattern; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class DigiDoc4JTest extends AbstractTest { @@ -58,14 +60,14 @@ public void testComposingAndSigningAndAddingDataToSignFile() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-dts", dataToSignFile, "text/plain", "-cert", "src/test/resources/testFiles/certs/sign_RSA_from_TEST_of_ESTEIDSK2015.pem"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertTrue(String.format("No data to sign file <%s>", dataToSignFile), new File(dataToSignFile).exists + assertTrue(String.format("No data to sign file <%s>", dataToSignFile), new File(dataToSignFile).exists ()); - Assert.assertTrue(String.format("No container file <%s>", containerFile), new File(containerFile).exists()); + assertTrue(String.format("No container file <%s>", containerFile), new File(containerFile).exists()); String signatureFile = this.getFileBy("sig"); parameters = new String[]{"-dts", dataToSignFile, "-sig", signatureFile, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; TestDigiDoc4JUtil.call(parameters); - Assert.assertTrue(String.format("No signature file <%s>", signatureFile), new File(signatureFile).exists()); + assertTrue(String.format("No signature file <%s>", signatureFile), new File(signatureFile).exists()); parameters = new String[]{"-in", containerFile, "-sig", signatureFile, "-dts", dataToSignFile}; DigiDoc4J.main(parameters); @@ -73,7 +75,7 @@ public void testComposingAndSigningAndAddingDataToSignFile() { } @Test - public void createsContainerWithSignatureProfileIsTSAForBDoc() throws Exception { + public void createsContainerWithSignatureProfileIsTSAForBDoc() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -81,22 +83,22 @@ public void createsContainerWithSignatureProfileIsTSAForBDoc() throws Exception "-profile", "LTA"}; TestDigiDoc4JUtil.call(parameters); Container container = ContainerOpener.open(file); - Assert.assertEquals(SignatureProfile.LTA, container.getSignatures().get(0).getProfile()); + assertEquals(SignatureProfile.LTA, container.getSignatures().get(0).getProfile()); } @Test - public void createsContainerWithSignatureProfileIsTSForBDoc() throws Exception { + public void createsContainerWithSignatureProfileIsTSForBDoc() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LT"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); + assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @Test - public void createsContainerWithSignatureProfileIsTSForAsice() throws Exception { + public void createsContainerWithSignatureProfileIsTSForAsice() { String fileName = this.getFileBy("asice"); String[] params = new String[]{"-in", fileName, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -105,24 +107,24 @@ public void createsContainerWithSignatureProfileIsTSForAsice() throws Exception System.setProperty("digidoc4j.mode", "TEST"); TestDigiDoc4JUtil.call(params); Container container = ContainerOpener.open(fileName); - Assert.assertEquals(SignatureProfile.LT, container.getSignatures().get(0).getProfile()); + assertEquals(SignatureProfile.LT, container.getSignatures().get(0).getProfile()); this.clearGlobalMode(); TestAssert.assertContainerIsValid(container); } @Test - public void createsContainerWithSignatureProfileIsBESForBDoc() throws Exception { + public void createsContainerWithSignatureProfileIsBESForBDoc() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "B_BES"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(SignatureProfile.B_BES, ContainerOpener.open(file).getSignatures().get(0).getProfile()); + assertEquals(SignatureProfile.B_BES, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @Test - public void createsECCSignatureWithInvalidEncryptionType() throws Exception { + public void createsECCSignatureWithInvalidEncryptionType() { this.systemExit.expectSystemExitWithStatus(1); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, @@ -132,38 +134,31 @@ public void createsECCSignatureWithInvalidEncryptionType() throws Exception { } @Test - public void createsECCSignature() throws Exception { + public void createsECCSignature() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", "src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEIDSK2015.p12", "1234", "-e", "ECDSA"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertTrue(ContainerOpener.open(file).validate().isValid()); + assertTrue(ContainerOpener.open(file).validate().isValid()); } @Test - public void createsContainerWithUnknownSignatureProfile() throws Exception { + public void createsContainerWithUnknownSignatureProfile() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "Unknown"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); + assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @Test - public void createNewDDocContainer_throwsException() throws Exception { + public void createNewDDocContainer_throwsException() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Not supported: Creating new container is not supported anymore for DDoc!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Not supported: Creating new container is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); String[] parameters = new String[]{"-in", file, "-type", "DDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -173,17 +168,10 @@ public void checkAssertion() throws Exception { } @Test - public void addDataFileToDDocContainer_throwsException() throws Exception { + public void addDataFileToDDocContainer_throwsException() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Not supported: Adding new data files is not supported anymore for DDoc!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Not supported: Adding new data files is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); Container container = ContainerOpener.open("src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"); container.saveAsFile(file); @@ -195,7 +183,7 @@ public void checkAssertion() throws Exception { } @Test - public void createsContainerWithTypeSettingBDoc() throws Exception { + public void createsContainerWithTypeSettingBDoc() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -206,23 +194,23 @@ public void createsContainerWithTypeSettingBDoc() throws Exception { } @Test - public void defaultDigidoc4jModeIsProd() throws Exception { + public void defaultDigidoc4jModeIsProd() { this.clearGlobalMode(); String[] parameters = new String[]{""}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); + assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); } @Test - public void commandLineDigidoc4jModeOverwritesDefault() throws Exception { + public void commandLineDigidoc4jModeOverwritesDefault() { this.setGlobalMode(Configuration.Mode.PROD); String[] parameters = new String[]{""}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); + assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); } @Test - public void createsContainerWithTypeSettingBasedOnFileExtensionBDoc() throws Exception { + public void createsContainerWithTypeSettingBasedOnFileExtensionBDoc() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -233,7 +221,7 @@ public void createsContainerWithTypeSettingBasedOnFileExtensionBDoc() throws Exc } @Test - public void createsContainerWithTypeSettingBDocIfNoSuitableFileExtensionAndNoType() throws Exception { + public void createsContainerWithTypeSettingBDocIfNoSuitableFileExtensionAndNoType() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", @@ -244,7 +232,7 @@ public void createsContainerWithTypeSettingBDocIfNoSuitableFileExtensionAndNoTyp } @Test - public void createsContainerAndSignsIt() throws Exception { + public void createsContainerAndSignsIt() { this.systemExit.expectSystemExitWithStatus(0); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, @@ -255,21 +243,21 @@ public void createsContainerAndSignsIt() throws Exception { @Test @Ignore("Requires a physical smart card") - public void createContainer_andSignIt_withPkcs11() throws Exception { + public void createContainer_andSignIt_withPkcs11() { String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs11", "/usr/local/lib/opensc-pkcs11.so", "22975", "2"}; TestDigiDoc4JUtil.call(parameters); Container container = ContainerOpener.open(file); - Assert.assertEquals(1, container.getDataFiles().size()); - Assert.assertEquals("test.txt", container.getDataFiles().get(0).getName()); - Assert.assertEquals(1, container.getSignatures().size()); - Assert.assertTrue(container.validate().isValid()); + assertEquals(1, container.getDataFiles().size()); + assertEquals("test.txt", container.getDataFiles().get(0).getName()); + assertEquals(1, container.getSignatures().size()); + assertTrue(container.validate().isValid()); } @Test - public void itShouldNotBePossible_ToSignWithBoth_Pkcs11AndPkcs12() throws Exception { + public void itShouldNotBePossible_ToSignWithBoth_Pkcs11AndPkcs12() { this.systemExit.expectSystemExitWithStatus(5); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, @@ -280,7 +268,7 @@ public void itShouldNotBePossible_ToSignWithBoth_Pkcs11AndPkcs12() throws Except } @Test - public void createsContainerAndAddsFileWithoutMimeType() throws Exception { + public void createsContainerAndAddsFileWithoutMimeType() { this.systemExit.expectSystemExitWithStatus(2); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", @@ -326,7 +314,7 @@ public void createMultipleSignedContainers_withinInputDirectory() throws Excepti String[] parameters = new String[]{"-inputDir", inputFolder, "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; TestDigiDoc4JUtil.call(parameters); - Assert.assertEquals(3, new File(outputFolder).listFiles().length); + assertEquals(3, new File(outputFolder).listFiles().length); TestAssert.assertFolderContainsFile(outputFolder, "firstDoc.bdoc"); TestAssert.assertFolderContainsFile(outputFolder, "secondDoc.bdoc"); TestAssert.assertFolderContainsFile(outputFolder, "thirdDoc.bdoc"); @@ -343,9 +331,9 @@ public void createMultipleSignedContainers_withoutOutputDirectory_shouldCreateOu "-type", "BDOC"}; TestDigiDoc4JUtil.call(parameters); File folder = new File(outputFolder); - Assert.assertTrue(folder.exists()); - Assert.assertTrue(folder.isDirectory()); - Assert.assertEquals(2, folder.listFiles().length); + assertTrue(folder.exists()); + assertTrue(folder.isDirectory()); + assertEquals(2, folder.listFiles().length); TestAssert.assertFolderContainsFile(outputFolder, "firstDoc.bdoc"); TestAssert.assertFolderContainsFile(outputFolder, "secondDoc.bdoc"); } @@ -372,29 +360,22 @@ public void createSignedContainer_forEachFile_withInputDirectoryAndMimeType() th "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; TestDigiDoc4JUtil.call(parameters); Container container = ContainerOpener.open(new File(outputFolder, "firstDoc.bdoc").getPath()); - Assert.assertEquals("text/xml", container.getDataFiles().get(0).getMediaType()); + assertEquals("text/xml", container.getDataFiles().get(0).getMediaType()); container = ContainerOpener.open(new File(outputFolder, "secondDoc.bdoc").getPath()); - Assert.assertEquals("text/xml", container.getDataFiles().get(0).getMediaType()); + assertEquals("text/xml", container.getDataFiles().get(0).getMediaType()); } @Test - public void commandLineInputCausesDigiDoc4JException() throws Exception { + public void commandLineInputCausesDigiDoc4JException() { this.systemExit.expectSystemExitWithStatus(1); DigiDoc4J.main(new String[]{"-in", "NotFoundFile.ddoc", "-verify"}); } @Test - public void removeFileFromDDocContainer_throwsException() throws Exception { + public void removeFileFromDDocContainer_throwsException() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Not supported: Removing data files is not supported anymore for DDoc!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Not supported: Removing data files is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); Container container = ContainerOpener.open("src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"); container.saveAsFile(file); @@ -402,114 +383,74 @@ public void checkAssertion() throws Exception { } @Test - public void verifyValidDDoc() throws Exception { + public void verifyValidDDoc() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S0 is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Signature S0 is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify"}); } @Test - public void verifyDDocWithManifestErrors() throws Exception { + public void verifyDDocWithManifestErrors() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Container contains a file named which is not found in the signature file")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Container contains a file named which is not found in the signature file"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/manifest_validation_error.asice", "-verify"}); } @Test - public void verboseMode() throws Exception { + public void verboseMode() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Opening DDoc container from file: src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Opening DDoc container from file: src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify", "-verbose"}); } @Test - public void verifyInValidDDoc() throws Exception { + public void verifyInValidDDoc() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S0 is not valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Signature S0 is not valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/changed_digidoc_test.ddoc", "-verify"}); } @Test - public void verifyDDocWithFatalError() throws Exception { + public void verifyDDocWithFatalError() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("ERROR: 75")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("ERROR: 75"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/error75.ddoc", "-verify"}); } @Test - public void verifyDDocWithoutSignature() throws Exception { + public void verifyDDocWithoutSignature() { this.systemExit.expectSystemExitWithStatus(1); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/no_signed_doc_no_signature.ddoc", "-verify"}); } @Test - public void verifyDDocWithEmptyContainer() throws Exception { + public void verifyDDocWithEmptyContainer() { this.systemExit.expectSystemExitWithStatus(1); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"}); } @Test - public void showsUsage() throws Exception { + public void showsUsage() { this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("usage: digidoc4j")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("usage: digidoc4j"))); DigiDoc4J.main(new String[]{}); } @@ -517,15 +458,8 @@ public void checkAssertion() throws Exception { @Ignore("Bug report at https://www.pivotaltracker.com/story/show/107563624") public void verifyBDocWithWarning() throws IOException { this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("The signer's certificate is not supported by SSCD!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("The signer's certificate is not supported by SSCD!"))); String[] parameters = new String[]{"-in", "src/test/resources/testFiles/invalid-containers/warning.asice", "-verify", "-warnings"}; FileUtils.copyFile( @@ -537,15 +471,8 @@ public void checkAssertion() throws Exception { @Test public void verifyDDocWithError() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("ERROR: 13 - Format attribute is mandatory!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("ERROR: 13 - Format attribute is mandatory!"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"}); } @@ -555,58 +482,44 @@ public void verifyDDocWithWarning() { this.configuration = Configuration.of(Configuration.Mode.PROD); ConfigManagerInitializer.forceInitConfigManager(this.configuration); this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "Warning: ERROR: 176 - X509IssuerName has none or invalid namespace: null")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "Warning: ERROR: 176 - X509IssuerName has none or invalid namespace: null"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/warning.ddoc", "-verify"}); } @Test - public void testIsWarningWhenNoWarningExists() throws DigiDocException { + public void testIsWarningWhenNoWarningExists() { Assert.assertFalse(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(1, "testError"))); } @Test - public void testIsNotWarningWhenCodeIsErrIssuerXmlnsAndDocumentFormatIsSkXML() throws DigiDocException { + public void testIsNotWarningWhenCodeIsErrIssuerXmlnsAndDocumentFormatIsSkXML() { Assert.assertFalse(isWarning(SignedDoc.FORMAT_SK_XML, new DigiDoc4JException(DigiDocException.ERR_ISSUER_XMLNS, "testError"))); } @Test - public void testIsWarningWhenCodeIsErrIssuerXmlnsAndDocumentFormatIsNotSkXML() throws DigiDocException { - Assert.assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.ERR_ISSUER_XMLNS, + public void testIsWarningWhenCodeIsErrIssuerXmlnsAndDocumentFormatIsNotSkXML() { + assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.ERR_ISSUER_XMLNS, "testError"))); } @Test - public void testIsWarningWhenWarningIsFound() throws DigiDocException { - Assert.assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, + public void testIsWarningWhenWarningIsFound() { + assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.ERR_DF_INV_HASH_GOOD_ALT_HASH, "test"))); - Assert.assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, + assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.ERR_OLD_VER, "test"))); - Assert.assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, + assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.ERR_TEST_SIGNATURE, "test"))); - Assert.assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, + assertTrue(isWarning(SignedDoc.FORMAT_DIGIDOC_XML, new DigiDoc4JException(DigiDocException.WARN_WEAK_DIGEST, "test"))); } @Test - public void showVersion() throws Exception { + public void showVersion() { this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("DigiDoc4j version")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("DigiDoc4j version"))); String[] parameters = {"--version"}; DigiDoc4J.main(parameters); } @@ -624,7 +537,7 @@ public void extractDataFileFromDdoc() throws Exception { } @Test - public void extractDataFile_withIncorrectParameters_shouldThrowException() throws Exception { + public void extractDataFile_withIncorrectParameters_shouldThrowException() { this.systemExit.expectSystemExitWithStatus(2); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/valid-containers/one_signature.bdoc", "-extract", "test.txt"}); @@ -640,82 +553,48 @@ public void extractDataFile_withNonExistingFile_shouldThrowException() throws Ex } @Test - public void verifyContainerWithTstASICS() throws Exception { + public void verifyContainerWithTstASICS() { String file = "src/test/resources/testFiles/valid-containers/testtimestamp.asics"; String[] parameters = new String[]{"-in", file, "-v"}; this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Container is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Container is valid"))); DigiDoc4J.main(parameters); } @Test - public void verifyValidBdocMid() throws Exception { + public void verifyValidBdocMid() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S0 is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Signature S0 is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"}); } @Test - public void verifyValidBdocMidWithDss() throws Exception { + public void verifyValidBdocMidWithDss() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("Validation was successful. Container is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"}); } @Test - public void verifyValidBdocEid() throws Exception { + public void verifyValidBdocEid() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S0 is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Signature S0 is valid"))); String[] parameters = new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_eid.bdoc", "-v"}; DigiDoc4J.main(parameters); } @Test - public void verifyValidBdocEidWithDss() throws Exception { + public void verifyValidBdocEidWithDss() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat("No match", stdOut.getLog(), - StringContains.containsString("Validation was successful. Container is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_eid.bdoc", "-v"}); } @@ -723,17 +602,12 @@ public void checkAssertion() throws Exception { public void verifyEdoc() throws Exception { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("OCSP response production time is before timestamp time")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature has 2 validation errors")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S1 is not valid")); - } - + this.systemExit.checkAssertionAfterwards(() -> { + assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); + assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); + assertThat(stdOut.getLog(), containsString("Signature S1 is not valid")); }); String outputFolder = this.testFolder.newFolder("outputFolder").getPath(); String[] parameters = new String[]{"-in", @@ -743,98 +617,66 @@ public void checkAssertion() throws Exception { } @Test - public void verifyEdocWithDss() throws Exception { + public void verifyEdocWithDss() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("OCSP response production time is before timestamp time")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature has 2 validation errors")); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Validation finished. Container is NOT valid!")); - } - + this.systemExit.checkAssertionAfterwards(() -> { + assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); + assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); + assertThat(stdOut.getLog(), containsString("Validation finished. Container is NOT valid!")); }); DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/invalid-containers/edoc2_lv-eId_sha256.edoc", "-v"}); } @Test - public void verifyValidTestBdoc() throws Exception { + public void verifyValidTestBdoc() { this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("Signature id-c0be584463a9dca56c3e9500a3d17e75 is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Signature id-c0be584463a9dca56c3e9500a3d17e75 is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"}); } @Test - public void verifyValidTestBdocWithDss() throws Exception { + public void verifyValidTestBdocWithDss() { this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("Validation was successful. Container is valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"}); } @Test - public void verifyInvalidTestBdoc() throws Exception { + public void verifyInvalidTestBdoc() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Signature S1 is not valid")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Signature S1 is not valid"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"}); } @Test - public void verifyInvalidTestBdocWithDss() throws Exception { + public void verifyInvalidTestBdocWithDss() { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), - StringContains.containsString("Validation finished. Container is NOT valid!")); - } - - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), + containsString("Validation finished. Container is NOT valid!"))); DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"}); } @Test @Ignore // unstable result - public void verifyValidBDocUnsafeInteger() throws Exception { + public void verifyValidBDocUnsafeInteger() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/InvestorToomas.bdoc", "-verify"}); } @Test - public void verifyValidBDocUnsafeIntegerSystemParam() throws Exception { + public void verifyValidBDocUnsafeIntegerSystemParam() { this.setGlobalMode(Configuration.Mode.PROD); this.systemExit.expectSystemExitWithStatus(0); System.setProperty(Constant.System.ORG_BOUNCYCASTLE_ASN1_ALLOW_UNSAFE_INTEGER, "true"); @@ -844,13 +686,8 @@ public void verifyValidBDocUnsafeIntegerSystemParam() throws Exception { @Test public void verifyBDocFullReport() throws Exception { this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(new Assertion() { - @Override - public void checkAssertion() throws Exception { - Assert.assertThat(stdOut.getLog(), StringContains.containsString( - "The certificate chain for revocation data is not trusted, it does not contain a trust anchor")); - } - }); + this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( + "The certificate chain for revocation data is not trusted, it does not contain a trust anchor"))); String outputFolder = this.testFolder.newFolder("outputFolder").getPath(); String[] parameters = new String[]{"-in", "src/test/resources/testFiles/invalid-containers/tundmatuocsp.asice", "-v", @@ -864,11 +701,11 @@ private void assertExtractingDataFile(String containerPath, String fileToExtract this.systemExit.expectSystemExitWithStatus(0); DigiDoc4J.main(new String[]{"-in", containerPath, "-extract", fileToExtract, outputPath}); TestCommonUtil.sleepInSeconds(1); - Assert.assertTrue(new File(outputPath).exists()); + assertTrue(new File(outputPath).exists()); } @Test - public void createAndValidateDetachedXades() throws Exception { + public void createAndValidateDetachedXades() { String xadesSignaturePath = "singatures0.xml"; String[] parameters = new String[]{"-xades", @@ -881,18 +718,18 @@ public void createAndValidateDetachedXades() throws Exception { "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "text/plain","-sigInputPath", xadesSignaturePath}; TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(stdOut.getLog(), containsPattern("Signature id-[a-z0-9]+ is valid")); + assertThat(stdOut.getLog(), containsPattern("Signature id-[a-z0-9]+ is valid")); new File(xadesSignaturePath).delete(); } @Test - public void validateDetachedXades_withWrongDigestFile_shouldFail() throws Exception { + public void validateDetachedXades_withWrongDigestFile_shouldFail() { String[] parameters = new String[]{"-xades", "-digFile", "test.txt", "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "text/plain", "-sigInputPath", "src/test/resources/testFiles/xades/test-bdoc-ts.xml"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("The reference data object is not intact!")); + assertThat(stdOut.getLog(), containsString("The reference data object is not intact!")); } @Test @@ -902,6 +739,6 @@ public void validateDetachedXades_mimeTypeNotSet_shouldFail() { "src/test/resources/testFiles/xades/test-bdoc-ts.xml"}; TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(stdOut.getLog(), StringContains.containsString("Problem with given parameters")); + assertThat(stdOut.getLog(), containsString("Problem with given parameters")); } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java b/digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java new file mode 100644 index 000000000..d967aee29 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java @@ -0,0 +1,43 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.test; + +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +import java.util.regex.Pattern; + +public class ContainsPattern extends TypeSafeMatcher { + + private final Pattern pattern; + + public ContainsPattern(Pattern pattern) { + this.pattern = pattern; + } + + protected boolean matchesSafely(String item) { + return this.pattern.matcher(item).find(); + } + + public void describeTo(Description description) { + description.appendText("a string containing the pattern '" + this.pattern + "'"); + } + + public static Matcher containsPattern(Pattern pattern) { + return new ContainsPattern(pattern); + } + + public static Matcher containsPattern(String regex) { + return new ContainsPattern(Pattern.compile(regex)); + } + +} From b37b478994866dc03fe438d1733db53836465836 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 16 Jan 2024 14:09:09 +0200 Subject: [PATCH 03/35] DD4J-949 Fix failing unit tests --- .../bdoc/asic/AsicSignatureFinalizerTest.java | 2 +- .../digidoc4j/impl/bdoc/tsl/TslLoaderTest.java | 12 ++++++------ .../truststores/lotl-pivot300-truststore.p12 | Bin 12770 -> 0 bytes .../truststores/lotl-pivot336-truststore.p12 | Bin 0 -> 17586 bytes 4 files changed, 7 insertions(+), 7 deletions(-) delete mode 100644 digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot300-truststore.p12 create mode 100644 digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot336-truststore.p12 diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java index 3c8432c6c..9580e456e 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java @@ -136,7 +136,7 @@ public void testCustomAiaDataLoaderUsedForSigning() { assertValidSignature(signature); Mockito.verify(dataLoaderFactory, Mockito.atLeast(1)).create(); - Mockito.verify(dataLoaderSpy, Mockito.times(1)).get("https://www.sk.ee/upload/files/TEST_of_EE_Certification_Centre_Root_CA.der.crt"); + Mockito.verify(dataLoaderSpy, Mockito.times(1)).get("http://www.sk.ee/certs/TEST_of_EE_Certification_Centre_Root_CA.der.crt"); Mockito.verifyNoMoreInteractions(dataLoaderFactory); } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/tsl/TslLoaderTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/tsl/TslLoaderTest.java index 65dfe6a02..499361827 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/tsl/TslLoaderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/tsl/TslLoaderTest.java @@ -139,11 +139,11 @@ public void loadProdTsl_withDefaultLotlTruststoreAndPivotSupportEnabled_shouldSu } @Test - public void loadProdTsl_withPivot300LotlTruststoreAndPivotSupportDisabled_shouldSucceed() { + public void loadProdTsl_withPivot336LotlTruststoreAndPivotSupportDisabled_shouldSucceed() { this.configuration = new Configuration(Configuration.Mode.PROD); // TODO: this might be needed to be updated after the next pivot release - // The used truststore contains the certificates specified in pivot LOTL with sequence number 300 - configuration.setLotlTruststorePath("prodFiles/truststores/lotl-pivot300-truststore.p12"); + // The used truststore contains the certificates specified in pivot LOTL with sequence number 336 + configuration.setLotlTruststorePath("prodFiles/truststores/lotl-pivot336-truststore.p12"); configuration.setLotlPivotSupportEnabled(false); LOTLInfo tslRepository = this.initTSLAndGetRepository(); Assert.assertEquals(Indication.TOTAL_PASSED, tslRepository.getValidationCacheInfo().getIndication()); @@ -151,11 +151,11 @@ public void loadProdTsl_withPivot300LotlTruststoreAndPivotSupportDisabled_should } @Test - public void loadProdTsl_withPivot300LotlTruststoreAndPivotSupportEnabled_shouldSucceed() { + public void loadProdTsl_withPivot336LotlTruststoreAndPivotSupportEnabled_shouldSucceed() { this.configuration = new Configuration(Configuration.Mode.PROD); // TODO: this might be needed to be updated after the next pivot release - // The used truststore contains the certificates specified in pivot LOTL with sequence number 300 - configuration.setLotlTruststorePath("prodFiles/truststores/lotl-pivot300-truststore.p12"); + // The used truststore contains the certificates specified in pivot LOTL with sequence number 336 + configuration.setLotlTruststorePath("prodFiles/truststores/lotl-pivot336-truststore.p12"); configuration.setLotlPivotSupportEnabled(true); LOTLInfo tslRepository = this.initTSLAndGetRepository(); Assert.assertEquals(Indication.TOTAL_PASSED, tslRepository.getValidationCacheInfo().getIndication()); diff --git a/digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot300-truststore.p12 b/digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot300-truststore.p12 deleted file mode 100644 index 9cbca7a69287bab36f5ff0d7f495516940a78c28..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12770 zcmV<8F&)k@f-&9#0Ru3CF_#7jDuzgg_YDCD0ic30hy;Q$gfN0JfG~nFd_r_}>zrW`eyj%n zUEAi``8be%T*E{Ls_{zeP}lI&DM5pVBd#D~WxA+f!Fsaq@BnBZ7Ij@$L3O@nF#g_c z*B*8RlSo3rjHCkY5KEH$xi*%`XXJf|P_yzUQQOEAAk|MFw+N_>jQ!%~x)5Bbx? zH#s$Os>aWB>Vy~;gI2Th?=6J6PVs$4NfBsk0+`P)zJ+=;tuuIjhg=YW(9Spgax|=c<;!DlwdijS>Xj&ubbFQd~K*0cuE#O zEn{~D)be-ljQnDU%@py0~l&V6Ni1o2HM3XM_-?lYC-&D!zxjs#5~7ZIYKC0$>Xys39JlNZ3)+x zKUMivEJPJ${&y6toWOC|;HH3sT)~E(tt=st!iqG0U!eGy~(O0-I z7Mv}jE52$q{!W?Y3@zb&PJhS-v+|{A9R*)Pu-=GjAQQ(P1tB*Z0W{?`ZIp*F{;FZ~ zS>G>+I_5jtAjr#>A!N*_|0==*M|7hmduLB^3TN||^^`|sBrE7lY2uqcDWnNBrJo5< zU1CsqEzgisd=)$vtHk@zn7r%lD>cy`b2B@A#x za*>F+fhn4&tql}ai=U8J8OX2U#U>Os1e&-tU41kKH@uq9D`6y>K2u8m2v|_uwO4s! z?VdVhP9mZRK=FX=Bqh`sF|(ph>8<150WmA|@mDtcvfqS%iuLBxv9m~bSzYj|wAIqf znZ!zlg-79v$nqNLT$P%LS)4$__0m}9J9KMSN+R8_70PBN!$0&F13aOph%el|kB1iE zmySa@HP5Ou%ju^N2GANwzzgc|^|R#r+RH6vt=%*HpjI@H0}c4>ElAjd0GhV;%@sI; z#8eqFbEb8lxp>+wReEoh8d^$1qG@d6?Btxk4-@UEJ~Z~HPe7+vS>}s9S=ZRaP(r95h!taVrvHqq@ z0*?xRdtVKqu@U5_^L65D-)@a7RkhQ`FtTi37;@St?lF^6bRT`jaf^XK@*eT%hpX!KPh$EY{iwIDi1i#S6PagcPi7OkZC++kZJmt8Lt6c>}MVbQIG*lk8 zpz>Mh&vunZ0a&!wLPCe-59-iWhA&C|oFPF;Y;pv51U#PldWz40y9EvaZw(z5_mfL) zW?!is0hn_#aPXmC`pz!T!s@K=-e9TNXVZ`JdTpdkU{9S<%M%2`k1f@t8_bV3_7|kH zX9~|x=xi$!wRi+|REXQN0DmNI``0120u4i*4hVA#x}Uh?O~Ff!hLdj0LaIv zvgsHl%wQlf0lIIdC)G70x~|)x-nbG)nN9xW!9|%0Ke7LZ5KJhNmnErn-?5s8t9?nZ z1r43;Dzt2yk4=v-Ihl+2 zad$KFP%6tNr{{L~x(!$9y5#CUp(fwGTdWwehJNx*yc)G}ETPa%QM|W4%De$01b4jG z$-o2+d@xnOb7Btq12K3DswjWKxd8z^SOOez?>#bpz|}LEoV6xbst_q{NRPDY-~3+8 z_}b$CQb;#>CZUdzz z$wm_@>XYRlqexKpBrD`kixS$MWfL#GZd%eQ!=ya3Q1h=SO(&+35yG zrV~4A$J8h{XC4{VoM`1j>4`X3K{t=Qc0KCA?`T(aL0YUn(i~>>M+n_2I#x9dEQ1&? zq`LyReu4h=XCvDD6F)IaQI#jmneR!+-l8N7=qLF2+G5*UkOk(DeXVMM2DW1hWmX2| zO|N=D_;-S}3)0Fl|1ESjU7{wyf;3KyX25?iOQs```YGWvCT6_V7!+19adt`>=FmXi z?pMHR`uH9S%xfiO(I@~ z`Rc()CEZqtcJ~vtFbR_*_)Y+P^kIdeRj2+&I>oA-$rGtx7!(Kn(&`e}7qz)=cO)2H zxd`%78JUr_$t`b+2}R^{7En#{d#z`C=#JKFNxeN}xmJ*v8-t4On#HeOA1Zf);UR*p zig2I9xRSZATJ{lOGN?o*%3(p+opmLL8k1+NV^_@{+J*vWc1hpH?@8i?`4zJ%KkKkD z`5q-`8W4${ZERIGM)e9qamlSjtdD@f#>eG1b$EF^;(G}_6rn>$M??M|*s_qy9gEA` zR+{J^0=Z@)+R>|9x*-BVVq*G=2X2PVv)F)*zQ$Yr5%t#V{={ya7b&{W6$S}bc)YVq z>0bkI(E}hRJ#`ZJ#2`Uv>L|#)cA)lXj%WMp)5mG@bWB~~ zEF5@6_rCpmxKe)yP2i{LWibJ2Ko1ArMjkD}CMSD><(ywxeLH&jRo46hBcGY}oh3eo z+=S{PU*I+;noV(9(XcMw*RSy4m~q23fQdH)$@lGYA9xYcrSId!rj-Lm+HiB4Bb_SV zoEOL02+05mz&vhxjUKCV7(s%}3ohF{uLv5qwfOUgYG^m+9yZjYOUY3@}FmoKNDUPk9T!~N}6GEHe z2sMF3#A`ZXt^gEm;b8GdgfAi2_Lx-Ff}pr<=}u^sp>3(z!BG6vuKyBn58l9U!4+~a z+@&4`9e|pPZEf+P3rb>h%WF^%QuIt9?Kd=t-iW*WyUk#{#e>9)t4*H>-UjRB+qz(; z)I>*@Zd+(^@;`}B>y?3l_aa0uH@W1E$ z_IwKC|G?1$(1`h1rYOG8ZJPidt_<;Nst3S6r&yh<0*TIs?BfmlT$Uvo>}Kp7In>}F zozT?P;zAhMj*?=SQX>hZiO)IP`w~H)Pk8MS-B(u{{Qz~VT6k_M{A2I z(*}$TFA$U=6Vk>EWJp3ToswdEH3Af>K&IN6!6^E?OIP8n?X=c1T_8fr70#b&#+X7D zrQ2&uEQg%`IxDhyCHtTr0%hI1pc&DK7NWp%P5v%9Zh1hj>EbmpD=%r^#UgUc-~*e{ z0^i-c=J@lX+0tHl?F*_ z)-f7)$%_kT5Z`PoGGFrS z@MaEU&zcha64|)!1%J)}F-@{rtN(e?Mdz6mXBqI$)@DQpWd$SU*u)g5G(XQ*ov_e+ zj@=`PpL^$6#;-7>B5Fl>&-MQ%3$icoz@~;}hpmP%B6^kX>pn{7K(HvVNGv8W{A$6XjE?jk$_xG($!G zZQM}Ff6QXcDMCCxT2^?gQR&z)UP|p15|g-lPvJ#B5V!H0$?_!Lhj-dE+y%bt_ElqE zv}PrIcmwdgVpZrJ6N#HAY(bkw!s;xSb-2OFM~i7hBgL4RL!LI@rPo#F0y-vOgqG{T}m6#8J75S}y49A`z~k{M6E(iJ+V) z#nG1ri)3)cl`+3Z zwnwT+71Vx2o$7EfNGptk<uLxkLNE1ch?fnBOUUoD108Bc0aU zUd*kcQ)sZyyavLze%3Dgs>tZ>Sh(QYiM$G6l9i_3@bp`;VGd$SL3^wc(vXptWYxPl zHSm6xoQc-qF=q6EL6{Bd&SCdxC}X@h9hOviSfhcADn$N$Fsv5`P{Lz8R*uh?P%o?9jWV%~WPIhfF0Jmj|%trn_yDT+1wAq*NA9-b5WlJh7@$%fEM4 z-qI)&-+z=krAQrn^6dCJ<2jfrfF;Z0_N7^<)>uK0& z56?X#M8ZR=x2{^l!Dl2*R0Zm{Qv{8vN3^~4yJKP5+;#|MC?YS4bwKg)H>e~U({7hG z7sV)}_-GN!X>|i)gE%vOHhSUsA;bx)&KWx?Xp+1pvY!GK4BTu{Hw0|k9ue1;#=B*wulUYMIj5Yu3pb2krh!E3z(qlF&t`|!V|NE z_HNMYmKN|LN2Kn-sgOQIeh`ax_~QH}4v8H_=bq^CMc*Y!2WsY8cl2N>*|Tc(@zt}_TPn!^+WLt=bo*$Beshw+ zT=%`Y_qk7V`CP&!v+POZ0y@XVaQ;8_(KeXf^OT}mwqmyS4oi?8C;CM+5k@D>#Mi-W z?o)Q&m-m)EN#pCN36X`0K!&D?o6A!^BeT;uPmLyB-D#F@j*R&1f%` zCgkIh)UnQ37TfF|=7q5*3IkZ^EcxicxI>jfi1j00MDi;}!~oRfyhh8qngWa$#OL^?kjH%Fg;3AsTaKC6VGv*R6J^|G|&~g~jh#8oLG_+8& z6os8Y6~A2}jaGvp6(_WiFZcUw=h{NM=&`eZD`g1?`vBCRqy(n=bqqP>ts`JP9QL{j zAyZHC-?_etNMVt-=@RBhU(Pof`D*EzU9SRl3Y9lD>2@ zBdeNHI<7qZ`|7m`5UkYuf2YB-aCK=&6uxpqde-m&f>!0ft4;i(t!jy~XXt*ZczNa| zV-?O4T6qXlOO9%A>njZfp*S({mmpWP^WSO)qdpn8@m2n?TcUXd)Ub2}t|55of3{?(n%%Bw*5*_<**2EK`a9uspI`xTxqX^-W)oCbeW0^(f zF@%nwm(bc@`(Uz*<`9HW-X}6@GU)XeRsc1mEM*I@9Eg?^j+rwjBvHK58;-o;Q{-{H zy0zOyv;q@GMw(7p32imWhf7l7`KItUbw{_JqI}!vxLR05!Vb;M7@`-))4SkyE{DFU zQogden#S`M=rtrO8$8SPlGG^03gV&`!5jADK)Uyj`yUC&j^Y@sCxC=CS->iB@0Vp29H6)+x#ERKGbABw|S7(2Qy zUXk7_b!l*{>R#XC$4p2TW*r5@r8y_mNn8to-Jsi^m%_oVfh<8Q$hH*dK%AG}kDSq< zAX z{o<_;BxjjFci;jf1fe>AdompOQJ{DE=qZnQ?9bXybJ>BWb)sr8f-?p32}JBrx%zl- zIeVG84+9{Nuytg$fMn>#+ez*xhyr0Qe0jYxd~8tyBUTxv-?bh2lRI8qfSQV#Ks(1k zRDjfoz;&eqayPX|Ke&RubB4O(^)0vJZ(sadY@+Elx~{=3IcGmPP;)^dC%}S z_9g?yspinsN{tIRYMRQEArd`Vk!pOI||0Za5H(* z?l-kI%sj;O9bsnACTxO?4p^d4?;Fu9xznkBL|j{jDn;1wt)4O95Zb5pLCDO1XUg`l zc$y=`GEL$V=3oIS%|>MJcLABI4DEQ1@^O4|S1#E`I37Fw^Vp)`uKjV9YSInGx#XFZ zp@4y2yJ#Q5p*9TjT2LSr2`rLB@u+(*z5ob8IG&^cH^*ZTzIK)A_5<7C{*n`=D+U+E zLDj{1pspBWZI12RbB|GlyY#~kbP(Ql`4@U{UlX^cm8`>2igclI*MH|5HFb=a;gBB# zC@yHo^yU$|p+F^22VYGjqJk81-Z{Mneb`FXxf(=+CR zxtB#Wlfa`@d28h2&k8KCOLhn&aUP;}8_pO|Q#D&WIVp%yV&J=n1&2 zr41PTWY^Hwlwqt*aHid-tiqz~EN11KkvyR}(TmK(Om1L^oQs;Mey${`T_Ikisvn&U z6>#zD9$?FY#{@70=F10BD2Lw^{>x%u-r&zCHl5>oBx}fS_ho#MO&8qOTk)|61_~K6>CFa z86EM$H~`@WMco$xO+L{I&N9s0E?Uo4;0|y@;{JH0^g*#2zgzVxvcev!{2^tV;NOHD zeV`WRAxf9gsq|TylfR>ef{X_}_YMYWDpZK`m)ry)Rm_ZVghC-0Z~( ztk6fF#)y7y#x|v`IvTeW^35!&f}}{t^lpf<+z7s~hEv%-t7e=VO5e(9}hyJ*U%a2#7;7%|6=g{9iE`8xsTF=jKl-WWQLUgFhA0%7FT z8z_^jJ=#DQDrlmKEvSsIwlk|Y(`S{4DyVP3ma1asN#Oa9FvYlcIfv(k0A}Tn_e>8x zH15qipMS}q5stbe;i+EZ5@Gp;QhYg!_BD-IktI37S%gr`3N%xih%fZgdp|RVjm<9wEHt*%QIi z*PK^okz)TvSjkh7TD={Qey;n}MaGjvhE_qog?FgKV?2FDDc#I=eN+tNl;ADIC)2+m?Tjcic5wtzSj5C`K#WW#Bs+lf;=xvvmt@DT@ z;f+tQbh%OY=IJgH2xo+~(@k#-5q7z6b!^b7>mdi)C*fqW}N%l+(FYAW>yFp-tT>sZ+ zHN(tZJ)v#xyE-a1Fs#-IG#v3$P=8smt1Kx`A?1<#ye_`^2VfnLcUiM`I01l0tP~(g z@C4R|NiWqt5!-9hEytd-yk}g{Ak-IdL^;MQdF?~3fj%<(rnTm4 zLM%WS7Q)>@ONbIkmkaiRTIIivtJ#RG>Phrhc25mBDTcxJiOQ(wgkp%ozr?`WZ}k_Q zK5DvO`+>kU^IjgSHH!+AeZc3AtcDkR#fTC+T(81^UHzpy?ZG8C!n2N+QA^7>^yCU& zL~z{Zm)gBt1lJ#qpVbLMkcc?D7J@wVv>ByC1+m^_cx`>=)o_Di($4YbfW^RkMii0M zFzxi;+G9TvOHJ{=<4~nq~RjP{aR)a!GnCo!5Rr57dk1YG@sFft6nn z41aH__Oj4cT(UqC{FYr>Q~TjQHlgDql+(naZk0YrjVADm(NI}tzCTE-Ldp~6S}h%R z%@m%t9%V>&Uqh!{pjfc~)zk9k9*ww3N0|aqPFsA(=vp_3=6(rQ%yTmwIWvC?-Kmpl z2TRp17MF2CCtw@+mBJX?IfQ;&HW6pKs2>5L@Org~XuPEXIdg``xDV947VjJjqjmEsvnvlCg^n(p4| z4HYOU^fK|=2)|7&=zy`!5o73kJ#UyIWXb^)pHaUkW>7lASPguzP%Ww!H=hBNzee6N zd_SBff*HsdN~XeLbKTOjx1WO(O7U}WYgdMn;t)M2t`ApLxAPUaN?D6O5>D+@H9al2 zU>s`M3QdZz7*O${a9rI_2*V6atk8rO)f3T{0eG|QgX-b+*s6Da0C}f!9&LG0%!>oC zKfPLhIGj5QYia~*OTICKE=*+7*6Vyc$!h2C*1EMFcwl`v`F#2I9E9rJF|SvaHjVZF z23Y$ua@mb5qDOWHUl&zAntyVYP5FH=@!_^hZLx*?s5gK9d1nmFvJ~>iQEJO8#b)%l zs;=ni=n;OGLrdQ{x&ldb;{QaI`P09uL$6w_L86KDq_cGrz83GM2WJr=#wd&`ChWHb zyuy@i%xR{!`pVXX$j)?XB#5-iYencB-I{-=vk2xFl}bT*j``Ctg)<@h>oZ?&fP!H( z+KsYlN~6$@-bDUdu7h^OM% z6Ur1{6!*~s69@5+0UTA{aWoq(Zm;oIS#upX78447og-V`PeuI2r|B4P6IKW%)$N3* z!+X1J7mZ%W+$bjwGy@F!NxP6>*-O1Of~8v9@WnOdo|5rN622M!0fF^YZ0GmGL5Vr& zz1o7+hoM8^aG>9Fuy-5H-M4vc`*x9p2HqCZ{Q$_EOh)8|QgW~yJuX0_V-#Q`dJFX` zQUBJtx&jAJH)x1i=D=a(E&;b@L%`oGCri(~M5$WhqIkX?)EgXOrlDbDKZ-?^(d?(5 z00o@6g$rZIjs#ClyV1jU(!U<6I3fr|sAWocRFdy9FjA05NzkUJudkj-5F8_F@PXp>SE=_aS`)J#m=S)|oG#ER`*}Kb-Ey~cabde`MHx=7 z)DtFLLwdu04wVtr(|xhrvg2d|DeaHsRqk1QQI5_`*|GKHvDINECV3k<{{Q~3X8q}v z9uVtGd!Vcg*creVldTzubyDdW;TMQ|n4#(uhZw-t=K_RS1smGEVG*BEUEu4K#Xju4dOx6^V~|9V2W;gna5sO>1FYXQ-i3xV^f^#2#OeCRj$Y z>X1Z*XT$%T@)?r~tUo52Z*g(vXcsc^mWw&qjW;G5Su7C6^~R*A6mb55vH>AQ!;x2+ zhETrvA>R=saWIEFuR7#mBY`U!2`Eu>@P_1t#<35_rHEOl+{@ghmA&2=@@os8It(Li z{VnsNW6%3K<9robm!@2l+&^KlTx|e$|A3&rTO{MSn!F=HRuAc+8-v-iy`5qBp`BKwh2)T6iLT;E$?_SmF8W zrMI#WB_9s6lBHpG+@N(VZh8z~M%oRnL+|6`U>bWLKW-c+*pdo91hc=-@#*hyR`%Cf zkqwNLu2pOza*Ws1p-@cfFXjD*+^S$dCV??pj*?H?8KJtAsC*#lp=J`>O&tCpC@kiWYis<@NLyh!E5a^yMQv9Vh|*NBKEk=jv^`E+L13E^7; z(yO=zBRquhLE{%|{{W7J5ye~4Yh2~jM85Q2oc(y`D(fI~-trV#;P|trDCo&d#COc? zl1aC9UpM`w(tn}aYIA4eXc?7^1L)vN+0IH15Sc$p8?w;6k3(;kQslcOFE4XC{Fn#8 zN-dN6`U35+o{1$OC?T(vCs~+BW0z>4ER%}Jydm4LOwJuM{hY5o(S2LQ=eu06~5zBhz8&7(r02*8I+4TceASf039sKa6Y zQbYfHP9lzV8g%~ocp2>7BZ*#bZP0R7gUG-($q^C@r!GBHEIq;z{aAoP(v(b$K8nKz zvwYzN%{e$i{y34#`zjR`gL*YmA%>v|e49c85EEug@a(}3%ZCBzYC}Vz-%oRyvdUuu zVal}~<5Fi*FSTf%q&l1qa7vL(n9tE7rXPk0yDUjsuG2S6UGwdlT{%PM zN`A`!UOR&1ll5a5kx38tHDDhOQ)LlxpXcl1PQC3c{`MgdXW9HnZ|r;`W~ zs!Z2w85@nCOQ5Ht;9x~;v~mdR5+X-v7&BtW$4TP8jT)X&l~ENQiGY{ch4nVbXq?FH z+Tg-bQ=9N!`9kr~NqQ-r>R8yiwSEH-c7YwORT7hqCL>m6iUiA^S6WKZlo64oOk<{8 zh%?@;7~Pw);0Ne(7wfvFU|{$pf$aDb`!BE-IECu|2ONrkC+E``h#iDW)iRHdIfcG* zKiFDOffwP)!>JgCVYs zC{A1txfFLLIa5VUgsQQM@)D!_g;pRvsP$kcSnvv915>3R31)&%<{9H2fYIxM`$fsK z#;O1eG`}AwEio|Dl%8U1)>Fsq1NHC(Q|4 zo4=j4E+Sg|`SZ3fFjpo)6(u$V{6;FCT{MHi9fZs4?=FK50DOoN&}%KUs5^{Pw#mlA zr^JV1bpj0N6r;ji8y3ia#9MSf_!)1T%$DJjVM5ptlFlip?8tfaRk*fruzK*=>w$iU z0YW_n1sz5xp+5DYKv?a#Z%|idi}`z7D~odY^5mA|E%)UOt9CPmld1jHWA}vexa;-4 z!KSiIlMf@8AGiL6?FY-Y%cCF5Esd!u_GLLj&OB#n^boKE46J=^3?|^gl2Mkyp`h%w zpa=^tN`Cxg1Ii|UAN$%t-gC)Tl0h|7nZ_SB9%?~Ow&Zz3nt&xb#NRjZ+Hp+QZX^K} zUbfWKdWXd^bk);An7=ABQ=lrgJe(u_!@;BORjZm;=!1o*0aZsNN8SHMv>j#b(jelZ zUh-GNO+R$&Vxt7{~NCXc_#Bk>*ImtN0?^A#~Rr*vGwngmod7a_n82GUT zLOOE!@UMJ1D_pif>z`@4WxQLgz%C)uo(H2QG3N)#44H2;*Y#yR2>X2zQ$bE!&vd?O z6#rV)S%;o^y!ym0kMEh>e`yYLS_LIv%-BNrdg{)TtltvsdZqS6)bpxB2;`?t$@cCPHLgdf*?&}@OnEg~oMMVc-yu(c01hEexU~+H{3{lX z`-A?70YC%r4JXA~47EgHBeFg>TvH&G#aYjDVTAzz}Dzilc;Xc^`pyvpBcIG44@(NkAaqt=j4Lxn4mnnz8-u|p7<#)ak9DO9<5)((gxo$HFi?UMl=VM5Y%g1c9Rr5nt-mChvF2kjc5J zs--p;V`Z!TDzX*zr9jq*)tJgY7;;)LUCR|5H28wh$CmwH@nGg=sbj$ej zPpv_tLY_6-cVYCbKWg}ah}o8ppvDD)6E}nb=-YxnMQxg-yEYrY1VB;Q&?|ut%k-$k zcsGgBJ{~oOJ{J*B-1ZOQ0`9F1^8`!(ab%r|nzxs@%GJYK{NN=&n}Nrk7KU8}A4^-; z(_pK+vKJ_&1Gi|ZFkk~sAdkUOs$ zEPt;sL6o-H-r=<&Xk=1^1X%MPqARuHkequn6{Pih*FH|*HVsAsfyxkh$a+;&ApBbi z#P@2nqd)$`_EdY!^?X&-(8!`4u0w?}lFm85UrlN#-T>SG4knZMXCoOQrO~A_g^v1} z3ndJ%sba1}G3JNj_U%f&8#;IxfhfDTDq}tNkIA}w^#3lCNt`KIY}5fM7$D?x)=B2v z=F)<#n9eyy5JrM-NEr`bMq&j+)Ib&Xh&VsV0T~=*(C(NzK5z7os-|nL40Wo3wAwL# zm?ov#-@Ya{OpmJz`zqhh>}PBa!?Qq@gD^fYAutIB1uG5%0vZJX1QbqLf}>PwpUFAA o=Vw4V9p`Mmhr0w6lr;@V7Xv|dEzon{k!dJb02TK&0s{etphrER0ssI2 diff --git a/digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot336-truststore.p12 b/digidoc4j/src/test/resources/prodFiles/truststores/lotl-pivot336-truststore.p12 new file mode 100644 index 0000000000000000000000000000000000000000..750fa98400eb8ee534a07c574b7912a7c8005e28 GIT binary patch literal 17586 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 Date: Thu, 25 Jan 2024 10:55:23 +0200 Subject: [PATCH 04/35] DD4J-969 Temporarily disable tests that use Lithuanian trusted list as it is currently unusable --- .../src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index ee275d776..ca22e6284 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -64,6 +64,7 @@ public static void setUpOnce() throws Exception { } @Test + @Ignore("DD4J-978 Lithuanian trusted list is temporarily unusable") public void validateProdBDocContainer_isValid() { Container container = ContainerBuilder.aContainer(). fromExistingFile("src/test/resources/prodFiles/valid-containers/Baltic MoU digital signing_EST_LT_LV.bdoc"). @@ -864,6 +865,7 @@ public void sameCertAddedTwiceToTSL_containerValidationShouldSucceed() { } @Test + @Ignore("DD4J-978 Lithuanian trusted list is temporarily unusable") public void prodContainerWithSignatureWarningOfTrustedCertificateNotMatchingWithTrustService_warningIsRemoved() { Container container = ContainerBuilder.aContainer(). fromExistingFile("src/test/resources/prodFiles/valid-containers/Baltic MoU digital signing_EST_LT_LV.bdoc"). From fe3ccf19f71e64b047a0445e8149b464e62fad55 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 25 Jan 2024 12:49:45 +0200 Subject: [PATCH 05/35] DD4J-968 Replace expiring test certificate from 'TEST of ESTEID2018' --- .../test/java/org/digidoc4j/AbstractTest.java | 2 +- .../p12/sign_ECC_from_TEST_of_ESTEID2018.p12 | Bin 0 -> 1766 bytes .../resources/testFiles/p12/sign_ESTEID2018.p12 | Bin 1720 -> 0 bytes 3 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 digidoc4j/src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEID2018.p12 delete mode 100644 digidoc4j/src/test/resources/testFiles/p12/sign_ESTEID2018.p12 diff --git a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java index 892113c81..205ffb6aa 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java @@ -110,7 +110,7 @@ public abstract class AbstractTest extends ConfigurationSingeltonHolder { protected static final PKCS12SignatureToken pkcs12SignatureToken = new PKCS12SignatureToken("src/test/resources/testFiles/p12/sign_RSA_from_TEST_of_ESTEIDSK2015.p12", "1234".toCharArray()); protected static final PKCS12SignatureToken pkcs12EccSignatureToken = new PKCS12SignatureToken("src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEIDSK2015.p12", "1234".toCharArray()); - protected static final PKCS12SignatureToken pkcs12Esteid2018SignatureToken = new PKCS12SignatureToken("src/test/resources/testFiles/p12/sign_ESTEID2018.p12", "1234".toCharArray()); + protected static final PKCS12SignatureToken pkcs12Esteid2018SignatureToken = new PKCS12SignatureToken("src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEID2018.p12", "1234".toCharArray()); protected Configuration configuration; @Rule diff --git a/digidoc4j/src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEID2018.p12 b/digidoc4j/src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEID2018.p12 new file mode 100644 index 0000000000000000000000000000000000000000..533da99c7c6ae28d13fa2922b2ea21392883c235 GIT binary patch literal 1766 zcmY+Ec{JPU8pnT$h<)E{jM_>t<`=bhlwMo4DYXo0r}ib(+A2-N5~@YpSXzWJ*3>qX zQmNV}v6foG*bW92ON{Ljmz#Ufy)*Zo=X}rezMt>&Jb%3JIS+_~FGC@0AP!y#=Tc3* znR?6z;eeFj;Ll+=csdKGfH=s@|Fa-TFdPKK!jD;sh4cKUiamF=ecD|rYm|FRpEWfYV+we$K-qwvyRgJgkzY9HM%4ll52Me-r_u5ERT4Z;m7Q8u<4f%Ov&ocR6SwbJlAmAg>@=A|92*+K`uPWo~K(i+v`(rUSDl&I;?eB)7`O0j zRM1>Ydm#72mlgPK6Zi8HnAzfutT{im1KXhqZCk|6mXR`2xFaaFf$I@4WAxtUMzyC5 zXK(2*<%$*e2w5w+Sr#FqKhf5Usw{MMsAm9-21;T&`z#mX&-Mm;441C8@1P};B z0#W~FXqI;s&;vkLAX(A_v;ke#Ne`6!YoHiX6eesR80vc&sSD~Lb+78`=pnVVK^%i?L~c_|{n3o_ocaCVa6_|H)S51D^+1 zMRaaKe+w$1Ip?!RYB|LFP&u~FS|N6m^9YqmLAU6j-9jU(xzie3=Cvw)k~Fi~OMgt7 z;7<&7y!ml->4mT5_;lfpH+n%%9YS^#A84`Pcfts7K8PbyPu!#Uim|~wI#VTS+p!Bs zrL8~YiHopX*E&C2hQzd;9osM_R+i_#-3};r%e*ER!7#E+F+3Ev-S9X_ zBAUw7stEQCsYxLOZ{3Q|4#ltV5X0iOuXwZlh|H*RpB#I3BPr~-BQ|7Bpmn+2Te1Fl zk5Vxf%Xg8`=IE*I&~j{@gD2m=cyP?%`QTwyOqiCFY4^*8{uYR8g3?U)m5SI*TIcjY zxLioGI3r$1kvTPYHnuk%>Knk>)>x5JGitomx2x>)2}9^#2pdTC@1==lAc5eJw!SiK zRm>ZnEF-%iv^s5IC7Mi~{K{=?!x+7Ozl9ppxo`!&dQwV$UqkEvY=~&hSl-hR7o5qo2? z;G`0~sMBDtLpfCMgF=ObCv2^RQ`GR~D)N)f`^O@=5B+>qm*ge$K$8Zm$Y)vfeS;NJ z^kuKZ6W83yI_Kx(pL%s)k~GFSl5HHt+D+3OIyhVf__L{QKSb1i_(>|UD3EugYK__%YP3p7Lq^Crb#&JPEoH-gukfdT|IldeS+cL_P%tx@Oyw+Geqr-$n%gi=imt)by5B* z(xu8iH5Q4^rOOyeXhQeHyX6vh8wY+}QxrD2u&?Zq&8O@~D<{#0wq&Hn+{HY9IChBO z4;RQgcP@9zs!tYE?3>{m`IQ}!aJnYkPr$|1HfCV9`^*RW z%x`5e-z2})v@4gWuBJ6Ff@{ZPLTd4!8D4Azk3vb3=PRa=8igzyoFQemn_gx*;m_Yx z)y)VuLMfky>njMm9feV>oq3!-NYmPTRbjyetzsh6k*+aprF_>mdvj_PunmYq=QE4@ zlT%6QsqRy}$%wBcD{Wc3_6@%W6(#qaI+f<X|+5 zE^^Vk4#N+2i&N=X14&>oIC-g_*%@Fy+n>A(YJ-NL9LNP{SL0`cUSbDeqW(@z4h$^1 qB5xS|l-7ZmP2+Y}g^A8P>S#TxJY_x&F-4v47?S?sc#!q4)%H)AW-V&~ literal 0 HcmV?d00001 diff --git a/digidoc4j/src/test/resources/testFiles/p12/sign_ESTEID2018.p12 b/digidoc4j/src/test/resources/testFiles/p12/sign_ESTEID2018.p12 deleted file mode 100644 index cdd353372bb72c288269a9483eef46a1089e0982..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1720 zcmY+Ac~p}J7R9rCh9w0h39>|xJp>4R3E8NMIB}3gC=A$?5Vi!cAptC_17%6rTa~ac zN{w1Xb`X#qR6tu5qzZ@vmL-CK2slDgQ7F?h)1IDp?s@0^-n;LQ3yKiUFen@pAwm&K zX6X*;G8L!-R3bw70wM%!7k>$gpmBd&LHU3PdU_Xgcjbpb{?GN9G885eu7kq2AReLo zf4KV^3t%Ksc+y3Z-r2RAZ#TK~`o`|jEsZcZq|Xfy-d;Yo_UXJuFacH3+W#=R8;x^u z8$OhidYB!CL>XwXUoLt?)z~jYH<4Ks!!Yo}tTiloc!%#L=tA5N_>h)#m6yWg&bjhX zgCk2Kt?)ojPy6#S-{-1;r!;wcI4G7?K=DsNCgCY#j70ORwcx^8TZc5tf{ju6+H|(n zohidCBP)vRRCX%DoGxwN4w>&1CpT5V?5tQo)`v+FQWu?V8MPnJRzI>?-<%JL5;UcC z)?A4pAF#jlA8rj(VoYR%v_JDv!Vt}LO(7wW4M-3q91;OJ4YAmr0(OfJA?zvw!h=LY zqW)lEp#EP*bs`2pdGbPo^oSHPol2q8$y5rN1d4!>KaUg;5)m-4i|)Xnkloht*9Q8x z&=LO)eUb=X0_y6H*H+a0FfQdB%w{MV{1JMx2uRkC=#>q?ZuNE+^M_PmjjEqIo$%O5 zSYX#Qq*2~tO4%ok+b^awOsBm-5%m&T@8*%Dm&Zfo4=sVe^8%y=| zXS4(-X~8hNwCzaEBN>xJn>cmbfqRb7-<))R3OZwZ;3%!m{N+zmuQGqlGgH4;lOna& zb9{r9Ls942411iL{B@z%b5wXUJ97*H!*o&JEkBpfUS6sunY+r-A@EB*7baj2pHZ2g z0NhotzK`639*dk%`H*0hk-CD^&d90g1ta=%qkS(r2hKh|eXJyG0xsW1 z@fd``W(C%78ag`Fc`l=D%tTzsH%iv;iJkCRamZ!*=H}2&19z2q`d51S~PFG+3GcQ)rzWPC!uO187-^EwGFEI zy=lP4+HgU#(9oH(*b>&AJ-TT;GWN>{(di{2^Kc)=KpiTLhX#LS6( zj+`nu+VFN;8oB6k+YFPP>(wxuX=G>mYCl~wa6VKeCHvv^lr)LOm7J@k1=gV?%QK-A_4DRVx_gR;9>~-S=O-bb&40@%-}@3< zKH@%Ot5{-DWa8?2G#}UG4!k0p4dx?x!_Mm_Mw_vPylNNr;~$?st~_|-33!sbcnGv? z1$A%)M74)2rYkEl_@=vA`|C%G_U6f1+GI0{3+K?{8*)&I?z97TYu+bsUhT#4g|dx~_MOKlZm=ElMdfC>p5nMJ+Ya-y;wp2&?9lOSOL2o`q9BJd)`a?B_pl0Wc>cjqYJ&QFr};vKDh2Y~SmV_wQhEXu9Ng$@}a5 From 107a35668d0ec2c35c94a06bf7edc2320995b911 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Fri, 26 Jan 2024 08:49:59 +0200 Subject: [PATCH 06/35] DD4J-968 Update failing signature validation test after the expiration of the old signing certificate from 'TEST of ESTEID2018' --- .../test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java index a7b6075e7..7d5c6bec0 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java @@ -93,7 +93,9 @@ public void validateContainer_withSpaceInDataFileNameEncodedAsPlusInSignature_sh ); ContainerValidationResult validationResult = container.validate(); TestAssert.assertContainsExactSetOfErrors(validationResult.getErrors(), - "The reference data object has not been found!" + "The reference data object has not been found!", + "The current time is not in the validity range of the signer's certificate!", + "The certificate validation is not conclusive!" ); } From 84b7767c6f574dfdf8285d6aa8572f2ef0c844a1 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 18 Jan 2024 08:26:29 +0200 Subject: [PATCH 07/35] DD4J-949 Update DSS to version 6.0 --- ddoc4j/pom.xml | 4 +- digidoc4j/pom.xml | 41 +++++++---------- .../main/java/org/digidoc4j/Container.java | 6 +-- .../java/org/digidoc4j/ContainerOpener.java | 4 +- .../src/main/java/org/digidoc4j/DataFile.java | 2 +- .../java/org/digidoc4j/DigestDataFile.java | 7 ++- .../main/java/org/digidoc4j/ShutdownHook.java | 4 +- .../impl/SimpleHttpGetDataLoader.java | 1 - .../org/digidoc4j/impl/StreamDocument.java | 2 +- .../impl/asic/AsicContainerCreator.java | 6 +-- .../impl/asic/AsicContainerParser.java | 15 ++++--- .../asic/AsicValidationReportBuilder.java | 24 +++++----- .../impl/asic/DataLoaderDecorator.java | 6 +-- .../impl/asic/manifest/AsicManifest.java | 30 ++++++------- .../impl/asic/manifest/ManifestParser.java | 2 +- .../impl/asic/manifest/ManifestValidator.java | 16 +++---- .../report/ContainerValidationReport.java | 31 +++++++------ .../report/SignatureValidationReport.java | 20 ++++----- .../SignatureValidationReportCreator.java | 2 +- .../impl/asic/report/package-info.java | 2 +- .../asic/tsl/TSLCertificateSourceImpl.java | 2 +- .../digidoc4j/impl/asic/tsl/TslLoader.java | 9 +++- .../impl/asic/xades/BesSignature.java | 45 +++++++++---------- .../impl/asic/xades/TimestampSignature.java | 35 +++++++-------- .../impl/asic/xades/XadesSignatureParser.java | 25 +++++------ .../asic/xades/XadesSigningDssFacade.java | 6 +-- .../xades/XadesValidationReportProcessor.java | 12 ++++- .../TimestampSignatureValidator.java | 34 +++++++------- .../validation/XadesSignatureValidator.java | 10 ++--- .../main/MultipleContainersExecutor.java | 25 +++++------ .../org/digidoc4j/signers/TimestampToken.java | 6 +-- .../org/digidoc4j/utils/MimeTypeUtil.java | 3 +- .../test/java/org/digidoc4j/AbstractTest.java | 6 +-- .../java/org/digidoc4j/ContainerZipTest.java | 24 +++++++--- .../test/java/org/digidoc4j/FileNameTest.java | 16 +++++-- .../digidoc4j/FileWritingOperationsTest.java | 32 ++++++------- .../org/digidoc4j/impl/SkDataLoaderTest.java | 26 +++++------ .../digidoc4j/impl/StreamDocumentTest.java | 9 ++-- .../impl/asic/DataLoaderDecoratorTest.java | 40 ++++++++--------- .../asic/manifest/ManifestValidatorTest.java | 18 ++++---- .../impl/bdoc/BDocContainerTest.java | 2 +- .../impl/bdoc/asic/TimeStampTokenTest.java | 18 ++++++-- .../XadesValidationReportProcessorTest.java | 20 ++++++--- .../signers/PKCS11SignatureTokenTest.java | 32 +++++++------ .../test/MockConfigurableDataLoader.java | 5 --- .../org/digidoc4j/test/MockSkDataLoader.java | 36 ++++++++------- .../digidoc4j/test/MockStreamDocument.java | 25 +++++------ pom.xml | 8 ++-- 48 files changed, 394 insertions(+), 360 deletions(-) diff --git a/ddoc4j/pom.xml b/ddoc4j/pom.xml index 7e70fe6d1..b1a7cf3cb 100644 --- a/ddoc4j/pom.xml +++ b/ddoc4j/pom.xml @@ -24,11 +24,11 @@ org.bouncycastle - bcpkix-jdk15on + bcpkix-jdk18on org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on commons-codec diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index dff5984c8..adb577178 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -23,26 +23,24 @@ org.digidoc4j.dss - 1.1.1 1.5.0 4.4 - 2.13.0 - 3.13.0 + 2.15.1 + 3.14.0 2.4.3 - 5.11.1.d4j.1 + 6.0.d4j.1 2.2 - 5.2.1 + 5.3 2.15.2 - 2.3.8 - 2.3.0.1 + 3.0.2 4.13.2 2.4 - 1.2.12 + 1.3.14 4.11.0 2.1 1.19.0 2.35.0 - 2.3.3 + 3.0.3 1.6 1.4 @@ -81,11 +79,11 @@ org.bouncycastle - bcpkix-jdk15on + bcpkix-jdk18on org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on commons-codec @@ -257,27 +255,18 @@ dss-crl-parser-stream ${dss.version} - + org.glassfish.jaxb jaxb-runtime ${jaxb.version} - - javax.activation - activation - ${activation.version} - - - com.sun.xml.bind - jaxb-impl - ${jaxb.version} - org.glassfish.jaxb jaxb-core - ${jaxb-core.version} + ${jaxb.version} + ch.qos.logback logback-classic @@ -537,13 +526,13 @@ - + - - + + diff --git a/digidoc4j/src/main/java/org/digidoc4j/Container.java b/digidoc4j/src/main/java/org/digidoc4j/Container.java index bdf06a11f..2f92ccff9 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/Container.java +++ b/digidoc4j/src/main/java/org/digidoc4j/Container.java @@ -16,7 +16,7 @@ import java.io.Serializable; import java.util.List; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; /** * Offers functionality for handling data files and signatures in a container. @@ -213,9 +213,9 @@ enum DocumentType { @Override public String toString() { if (this == BDOC || this == ASICE) - return MimeType.ASICE.getMimeTypeString(); + return MimeTypeEnum.ASICE.getMimeTypeString(); if (this == ASICS) - return MimeType.ASICS.getMimeTypeString(); + return MimeTypeEnum.ASICS.getMimeTypeString(); return super.toString(); } } diff --git a/digidoc4j/src/main/java/org/digidoc4j/ContainerOpener.java b/digidoc4j/src/main/java/org/digidoc4j/ContainerOpener.java index fe5c2a291..1be3fc08d 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/ContainerOpener.java +++ b/digidoc4j/src/main/java/org/digidoc4j/ContainerOpener.java @@ -10,7 +10,7 @@ package org.digidoc4j; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.impl.asic.AsicFileContainerParser; import org.digidoc4j.impl.asic.AsicParseResult; @@ -140,7 +140,7 @@ private static Container openPadesContainer(String path, Configuration configura } private static boolean isAsicSContainer(AsicParseResult parseResult) { - return parseResult.getMimeType().equals(MimeType.ASICS.getMimeTypeString()); + return parseResult.getMimeType().equals(MimeTypeEnum.ASICS.getMimeTypeString()); } private static boolean isBDocContainer(AsicParseResult parseResult) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/DataFile.java b/digidoc4j/src/main/java/org/digidoc4j/DataFile.java index 9a32c433f..d2d591fee 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/DataFile.java +++ b/digidoc4j/src/main/java/org/digidoc4j/DataFile.java @@ -11,11 +11,11 @@ package org.digidoc4j; import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import eu.europa.esig.dss.enumerations.MimeType; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.DSSException; import eu.europa.esig.dss.model.FileDocument; import eu.europa.esig.dss.model.InMemoryDocument; -import eu.europa.esig.dss.model.MimeType; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; diff --git a/digidoc4j/src/main/java/org/digidoc4j/DigestDataFile.java b/digidoc4j/src/main/java/org/digidoc4j/DigestDataFile.java index 51d390807..29014babf 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/DigestDataFile.java +++ b/digidoc4j/src/main/java/org/digidoc4j/DigestDataFile.java @@ -1,15 +1,14 @@ package org.digidoc4j; -import java.util.Arrays; - +import eu.europa.esig.dss.enumerations.MimeType; +import eu.europa.esig.dss.model.DigestDocument; import org.apache.commons.codec.binary.Base64; import org.digidoc4j.exceptions.InvalidDataFileException; import org.digidoc4j.exceptions.NotSupportedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.europa.esig.dss.model.DigestDocument; -import eu.europa.esig.dss.model.MimeType; +import java.util.Arrays; public class DigestDataFile extends DataFile { diff --git a/digidoc4j/src/main/java/org/digidoc4j/ShutdownHook.java b/digidoc4j/src/main/java/org/digidoc4j/ShutdownHook.java index b1c925ca2..8ec043a23 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/ShutdownHook.java +++ b/digidoc4j/src/main/java/org/digidoc4j/ShutdownHook.java @@ -21,8 +21,8 @@ * registering this hook by {@link Runtime#addShutdownHook(Thread)} should be sufficient. *

* In case of some sort of webapp in a servlet container where there are multiple levels of contexts - * the recommended way to use it is to register a {@link javax.servlet.ServletContextListener} and call - * {@link ShutdownHook#run()} method inside {@link javax.servlet.ServletContextListener#contextDestroyed(ServletContextEvent)} + * the recommended way to use it is to register a {@link jakarta.servlet.ServletContextListener} and call + * {@link ShutdownHook#run()} method inside {@link jakarta.servlet.ServletContextListener#contextDestroyed(ServletContextEvent)} *

* NB! As the usage method of this hook is dependant on the system/situation and may vary, * so in consequence it's still in experimental status diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/SimpleHttpGetDataLoader.java b/digidoc4j/src/main/java/org/digidoc4j/impl/SimpleHttpGetDataLoader.java index c9d25d448..446b513aa 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/SimpleHttpGetDataLoader.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/SimpleHttpGetDataLoader.java @@ -77,7 +77,6 @@ public DataAndUrl get(List urlStrings) { * @param refresh whether the cached data should be refreshed or not * @return {@code byte} array of obtained data */ - @Override public byte[] get(String url, boolean refresh) { return request(url, refresh); } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/StreamDocument.java b/digidoc4j/src/main/java/org/digidoc4j/impl/StreamDocument.java index b6895eab4..8960e55e8 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/StreamDocument.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/StreamDocument.java @@ -11,9 +11,9 @@ package org.digidoc4j.impl; +import eu.europa.esig.dss.enumerations.MimeType; import eu.europa.esig.dss.model.CommonDocument; import eu.europa.esig.dss.model.DSSException; -import eu.europa.esig.dss.model.MimeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerCreator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerCreator.java index ed719dcbd..0c87b35a1 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerCreator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerCreator.java @@ -10,8 +10,8 @@ package org.digidoc4j.impl.asic; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.model.DSSDocument; -import eu.europa.esig.dss.model.MimeType; import org.apache.commons.io.IOUtils; import org.digidoc4j.Configuration; import org.digidoc4j.Constant; @@ -76,9 +76,9 @@ public void writeAsiceMimeType(String containerType) { logger.debug("Writing asic mime type to asic zip file"); String mimeTypeString; if (Constant.ASICS_CONTAINER_TYPE.equals(containerType)){ - mimeTypeString = MimeType.ASICS.getMimeTypeString(); + mimeTypeString = MimeTypeEnum.ASICS.getMimeTypeString(); } else { - mimeTypeString = MimeType.ASICE.getMimeTypeString(); + mimeTypeString = MimeTypeEnum.ASICE.getMimeTypeString(); } byte[] mimeTypeBytes = mimeTypeString.getBytes(CHARSET); new BytesEntryCallback(getAsicMimeTypeZipEntry(mimeTypeBytes), mimeTypeBytes).write(); diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerParser.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerParser.java index 198f04fd8..e066a4f5b 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerParser.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicContainerParser.java @@ -10,9 +10,10 @@ package org.digidoc4j.impl.asic; +import eu.europa.esig.dss.enumerations.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; -import eu.europa.esig.dss.model.MimeType; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BOMInputStream; import org.apache.commons.lang3.StringUtils; @@ -168,7 +169,7 @@ private void extractTimeStamp(ZipEntry entry) { logger.debug("Extracting timestamp file"); InputStream zipFileInputStream = getZipEntryInputStream(entry); String fileName = entry.getName(); - timestampToken = new DataFile(zipFileInputStream, fileName, MimeType.TST.getMimeTypeString()); + timestampToken = new DataFile(zipFileInputStream, fileName, MimeTypeEnum.TST.getMimeTypeString()); } private void extractDataFile(ZipEntry entry) { @@ -238,11 +239,11 @@ protected String getDataFileMimeType(String fileName) { } private void validateParseResult() { - if (!StringUtils.equalsIgnoreCase(MimeType.ASICE.getMimeTypeString(), mimeType) - && !StringUtils.equalsIgnoreCase(MimeType.ASICS.getMimeTypeString(), mimeType)) { - logger.error("Container mime type is not " + MimeType.ASICE.getMimeTypeString() + " but is " + mimeType); - throw new UnsupportedFormatException("Container mime type is not " + MimeType.ASICE.getMimeTypeString() - + " OR " + MimeType.ASICS.getMimeTypeString() + " but is " + mimeType); + if (!StringUtils.equalsIgnoreCase(MimeTypeEnum.ASICE.getMimeTypeString(), mimeType) + && !StringUtils.equalsIgnoreCase(MimeTypeEnum.ASICS.getMimeTypeString(), mimeType)) { + logger.error("Container mime type is not " + MimeTypeEnum.ASICE.getMimeTypeString() + " but is " + mimeType); + throw new UnsupportedFormatException("Container mime type is not " + MimeTypeEnum.ASICE.getMimeTypeString() + + " OR " + MimeTypeEnum.ASICS.getMimeTypeString() + " but is " + mimeType); } if (!this.signatures.isEmpty() && this.dataFiles.isEmpty()) { throw new ContainerWithoutFilesException("The reference data object(s) is not found!"); diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicValidationReportBuilder.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicValidationReportBuilder.java index 5a6071200..bafee0c1e 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicValidationReportBuilder.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/AsicValidationReportBuilder.java @@ -1,19 +1,22 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic; +import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; import eu.europa.esig.dss.simplereport.jaxb.XmlValidationPolicy; import eu.europa.esig.dss.spi.DSSUtils; -import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; import eu.europa.esig.dss.validation.reports.Reports; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; import org.digidoc4j.ValidationResult; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.exceptions.TechnicalException; @@ -24,9 +27,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; import java.io.File; import java.io.StringWriter; import java.io.UnsupportedEncodingException; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/DataLoaderDecorator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/DataLoaderDecorator.java index 17906f77b..52ef7284d 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/DataLoaderDecorator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/DataLoaderDecorator.java @@ -104,7 +104,7 @@ private static ProxyProperties createProxyPropertiesIfHostAndPortPresent(Integer proxyProperties.setHost(proxyHost); if (isNotBlank(proxyUser) && isNotBlank(proxyPassword)) { proxyProperties.setUser(proxyUser); - proxyProperties.setPassword(proxyPassword); + proxyProperties.setPassword(proxyPassword.toCharArray()); } return proxyProperties; } else { @@ -154,7 +154,7 @@ private static void configureSslKeystore(CommonsDataLoader dataLoader, String ss dataLoader.setSslKeystoreType(sslKeystoreType); } if (sslKeystorePassword != null) { - dataLoader.setSslKeystorePassword(sslKeystorePassword); + dataLoader.setSslKeystorePassword(sslKeystorePassword.toCharArray()); } } } @@ -166,7 +166,7 @@ private static void configureSslTruststore(CommonsDataLoader dataLoader, String dataLoader.setSslTruststoreType(sslTruststoreType); } if (sslTruststorePassword != null) { - dataLoader.setSslTruststorePassword(sslTruststorePassword); + dataLoader.setSslTruststorePassword(sslTruststorePassword.toCharArray()); } } } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/AsicManifest.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/AsicManifest.java index 8c6b4e473..dbaac7e78 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/AsicManifest.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/AsicManifest.java @@ -1,20 +1,20 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.manifest; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.asic.xades.definition.ManifestAttribute; import eu.europa.esig.dss.asic.xades.definition.ManifestElement; import eu.europa.esig.dss.asic.xades.definition.ManifestNamespace; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; +import eu.europa.esig.dss.xml.utils.DomUtils; import org.digidoc4j.Constant; import org.digidoc4j.DataFile; import org.slf4j.Logger; @@ -40,7 +40,7 @@ public class AsicManifest { /** * Creates an instance of ASiC manifest without specifying container type - * (the root file entry mimetype defaults to {@link MimeType#ASICE}). + * (the root file entry mimetype defaults to {@link MimeTypeEnum#ASICE}). */ public AsicManifest() { this(null); @@ -49,8 +49,8 @@ public AsicManifest() { /** * Creates an instance of ASiC manifest with the specified container type. * Container type {@link Constant#ASICS_CONTAINER_TYPE} sets the root file entry mimetype as - * {@link MimeType#ASICS}, any other value makes the root file entry mimetype to default to - * {@link MimeType#ASICE}. + * {@link MimeTypeEnum#ASICS}, any other value makes the root file entry mimetype to default to + * {@link MimeTypeEnum#ASICE}. * * @param containerType the container type */ @@ -65,9 +65,9 @@ public AsicManifest(String containerType) { Element entryElement = DomUtils.addElement(dom, manifestElement, ManifestNamespace.NS, ManifestElement.FILE_ENTRY); DomUtils.setAttributeNS(entryElement, ManifestNamespace.NS, ManifestAttribute.FULL_PATH, "/"); if (Constant.ASICS_CONTAINER_TYPE.equals(containerType)) { - DomUtils.setAttributeNS(entryElement, ManifestNamespace.NS, ManifestAttribute.MEDIA_TYPE, MimeType.ASICS.getMimeTypeString()); + DomUtils.setAttributeNS(entryElement, ManifestNamespace.NS, ManifestAttribute.MEDIA_TYPE, MimeTypeEnum.ASICS.getMimeTypeString()); } else { - DomUtils.setAttributeNS(entryElement, ManifestNamespace.NS, ManifestAttribute.MEDIA_TYPE, MimeType.ASICE.getMimeTypeString()); + DomUtils.setAttributeNS(entryElement, ManifestNamespace.NS, ManifestAttribute.MEDIA_TYPE, MimeTypeEnum.ASICE.getMimeTypeString()); } } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestParser.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestParser.java index 04605e3ac..0116c86d3 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestParser.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestParser.java @@ -10,11 +10,11 @@ package org.digidoc4j.impl.asic.manifest; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.asic.xades.definition.ManifestAttribute; import eu.europa.esig.dss.asic.xades.definition.ManifestElement; import eu.europa.esig.dss.asic.xades.definition.ManifestNamespace; import eu.europa.esig.dss.model.DSSDocument; +import eu.europa.esig.dss.xml.utils.DomUtils; import org.digidoc4j.exceptions.DuplicateDataFileException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestValidator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestValidator.java index b03de19c8..c331bcc5d 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestValidator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/manifest/ManifestValidator.java @@ -10,8 +10,8 @@ package org.digidoc4j.impl.asic.manifest; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.model.DSSDocument; +import eu.europa.esig.dss.xml.utils.DomUtils; import org.apache.xml.security.signature.Reference; import org.digidoc4j.Signature; import org.digidoc4j.exceptions.DigiDoc4JException; @@ -37,9 +37,9 @@ public class ManifestValidator { public static final String MANIFEST_PATH = "META-INF/manifest.xml"; public static final String MIMETYPE_PATH = "mimetype"; private static final Logger logger = LoggerFactory.getLogger(ManifestValidator.class); - private List detachedContents; - private ManifestParser manifestParser; - private Collection signatures; + private final List detachedContents; + private final ManifestParser manifestParser; + private final Collection signatures; public ManifestValidator(ManifestParser manifestParser, List detachedContents, Collection signatures) { @@ -56,10 +56,10 @@ public static List validateEntries(Map one = new HashSet(manifestEntries.values()); - Set onePrim = new HashSet(manifestEntries.values()); - Set two = new HashSet(signatureEntries); - Set twoPrim = new HashSet(); + Set one = new HashSet<>(manifestEntries.values()); + Set onePrim = new HashSet<>(manifestEntries.values()); + Set two = new HashSet<>(signatureEntries); + Set twoPrim = new HashSet<>(); for (ManifestEntry manifestEntry : signatureEntries) { String mimeType = manifestEntry.getMimeType(); String alterName = manifestEntry.getFileName().replaceAll("\\+", " "); diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/ContainerValidationReport.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/ContainerValidationReport.java index 1cc05ddc6..eafc7c88f 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/ContainerValidationReport.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/ContainerValidationReport.java @@ -1,26 +1,25 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.report; +import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; + import java.util.ArrayList; import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; - @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "SimpleReport") diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java index a0f930ea5..2dabb7cbd 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java @@ -13,7 +13,7 @@ import eu.europa.esig.dss.enumerations.Indication; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.enumerations.SubIndication; -import eu.europa.esig.dss.simplereport.jaxb.Adapter1; +import eu.europa.esig.dss.jaxb.parsers.DateParser; import eu.europa.esig.dss.simplereport.jaxb.Adapter3; import eu.europa.esig.dss.simplereport.jaxb.Adapter4; import eu.europa.esig.dss.simplereport.jaxb.Adapter6; @@ -25,14 +25,14 @@ import eu.europa.esig.dss.simplereport.jaxb.XmlSignatureScope; import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamps; import eu.europa.esig.dss.simplereport.jaxb.XmlToken; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlSchemaType; +import jakarta.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; @@ -83,12 +83,12 @@ public class SignatureValidationReport implements Serializable { protected List infos; @XmlElement(name = "SigningTime", type = String.class) - @XmlJavaTypeAdapter(Adapter1.class) + @XmlJavaTypeAdapter(DateParser.class) @XmlSchemaType(name = "dateTime") protected Date signingTime; @XmlElement(name = "BestSignatureTime", required = true, type = String.class) - @XmlJavaTypeAdapter(Adapter1 .class) + @XmlJavaTypeAdapter(DateParser.class) @XmlSchemaType(name = "dateTime") protected Date bestSignatureTime; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java index ba4139bee..e383f08e7 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java @@ -59,7 +59,7 @@ private SignatureValidationReport cloneSignatureValidationReport() { if (simpleReport.getSignaturesCount() > 1) { logger.warn("Simple report contains more than one signature: " + simpleReport.getSignaturesCount()); } - Optional signatureXmlReport = simpleReport.getSignatureOrTimestamp().stream() + Optional signatureXmlReport = simpleReport.getSignatureOrTimestampOrEvidenceRecord().stream() .filter(s -> s instanceof XmlSignature) .findFirst(); if (signatureXmlReport.isPresent()) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/package-info.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/package-info.java index 32b3a19ac..a4946592b 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/package-info.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/package-info.java @@ -1,2 +1,2 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://dss.esig.europa.eu/validation/simple-report", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://dss.esig.europa.eu/validation/simple-report", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.digidoc4j.impl.asic.report; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java index 61fc31dcb..624c34014 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java @@ -104,7 +104,7 @@ public void addTSLCertificate(X509Certificate certificate) { MutableTimeDependentValues statusHistoryList = new MutableTimeDependentValues<>(); statusHistoryList.addOldest(statusAndInformationExtensions); - TrustProperties trustProperties = new TrustProperties(getFirstSuitableTLInfo().getDSSId(), + TrustProperties trustProperties = new TrustProperties(getFirstSuitableTLInfo(), trustServiceProviderBuilder.build(), statusHistoryList); addCertificate(new CertificateToken(certificate), Arrays.asList(trustProperties)); diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TslLoader.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TslLoader.java index 821eea4bf..3fe6e10dd 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TslLoader.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TslLoader.java @@ -144,9 +144,14 @@ private LOTLSource createLOTLSource() { private KeyStoreCertificateSource getTrustStore() { try (InputStream lotlTrustStoreInputStream = openLotlTrustStoreInputStream()) { - return new KeyStoreCertificateSource(lotlTrustStoreInputStream, + return new KeyStoreCertificateSource( + lotlTrustStoreInputStream, configuration.getLotlTruststoreType(), - configuration.getLotlTruststorePassword()); + Optional + .ofNullable(configuration.getLotlTruststorePassword()) + .map(String::toCharArray) + .orElse(null) + ); } catch (IOException e) { throw new LotlTrustStoreNotFoundException("Unable to retrieve trust-store", e); } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/BesSignature.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/BesSignature.java index 212ac543c..94288e5ee 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/BesSignature.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/BesSignature.java @@ -1,26 +1,22 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.xades; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - import eu.europa.esig.dss.enumerations.SignatureAlgorithm; +import eu.europa.esig.dss.model.x509.CertificateToken; +import eu.europa.esig.dss.spi.DSSUtils; +import eu.europa.esig.dss.validation.SignatureProductionPlace; import eu.europa.esig.dss.validation.SignerRole; -import eu.europa.esig.dss.xades.definition.XAdESPaths; +import eu.europa.esig.dss.xml.utils.DomUtils; +import eu.europa.esig.xades.definition.XAdESPath; import org.apache.commons.codec.binary.Base64; import org.apache.xml.security.signature.Reference; import org.bouncycastle.cert.ocsp.BasicOCSPResp; @@ -31,10 +27,13 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import eu.europa.esig.dss.spi.DSSUtils; -import eu.europa.esig.dss.DomUtils; -import eu.europa.esig.dss.validation.SignatureProductionPlace; -import eu.europa.esig.dss.model.x509.CertificateToken; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; /** * BES signature @@ -45,7 +44,7 @@ public class BesSignature extends DssXadesSignature { private final static String XPATH_KEY_INFO_X509_CERTIFICATE = "./ds:KeyInfo/ds:X509Data/ds:X509Certificate"; private SignatureProductionPlace signerLocation; private transient Element signatureElement; - private XAdESPaths xAdESPaths; // This variable contains the XAdESPaths adapted to the signature schema. + private XAdESPath xAdESPaths; // This variable contains the XAdESPaths adapted to the signature schema. private X509Cert signingCertificate; private Set encapsulatedCertificates; @@ -227,7 +226,7 @@ protected Element getSignatureElement() { return signatureElement; } - protected XAdESPaths getxPathQueryHolder() { + protected XAdESPath getxPathQueryHolder() { return xAdESPaths; } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/TimestampSignature.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/TimestampSignature.java index 30dec5fde..24ebb19aa 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/TimestampSignature.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/TimestampSignature.java @@ -1,19 +1,21 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.xades; -import java.security.cert.X509Certificate; -import java.util.Date; - -import eu.europa.esig.dss.xades.definition.XAdESPaths; +import eu.europa.esig.dss.model.DSSException; +import eu.europa.esig.dss.model.x509.CertificateToken; +import eu.europa.esig.dss.spi.x509.tsp.TimestampToken; +import eu.europa.esig.dss.xades.validation.XAdESSignature; +import eu.europa.esig.dss.xml.utils.DomUtils; +import eu.europa.esig.xades.definition.XAdESPath; import org.apache.commons.codec.binary.Base64; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.tsp.TimeStampToken; @@ -27,11 +29,8 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import eu.europa.esig.dss.model.DSSException; -import eu.europa.esig.dss.DomUtils; -import eu.europa.esig.dss.validation.timestamp.TimestampToken; -import eu.europa.esig.dss.model.x509.CertificateToken; -import eu.europa.esig.dss.xades.validation.XAdESSignature; +import java.security.cert.X509Certificate; +import java.util.Date; public class TimestampSignature extends TimemarkSignature { @@ -86,7 +85,7 @@ public Date getTrustedSigningTime() { } private TimeStampToken findTimestampToken() { - XAdESPaths xAdESPaths = getxPathQueryHolder(); + XAdESPath xAdESPaths = getxPathQueryHolder(); logger.debug("Finding timestamp token"); NodeList timestampNodes = DomUtils.getNodeList(getSignatureElement(), xAdESPaths.getSignatureTimestampPath()); if (timestampNodes.getLength() == 0) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSignatureParser.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSignatureParser.java index 03073e18d..ad421beba 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSignatureParser.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSignatureParser.java @@ -1,20 +1,20 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.xades; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.validation.SignaturePolicy; -import eu.europa.esig.dss.xades.definition.XAdESPaths; import eu.europa.esig.dss.xades.validation.XAdESSignature; +import eu.europa.esig.dss.xml.utils.DomUtils; +import eu.europa.esig.xades.definition.XAdESPath; import org.apache.commons.lang3.StringUtils; import org.digidoc4j.impl.asic.TmSignaturePolicyType; import org.digidoc4j.utils.Helper; @@ -95,11 +95,10 @@ private boolean isTimeMarkSignature(XAdESSignature xAdESSignature) { * is thrown if more than one EncapsulatedTimeStamp elements are encountered in a single SignatureTimeStamp * element when parsing a signature. * - * TODO: remove this solution after migrating to DSS 5.9 where the described case is handled, - * albeit in a different way. + * TODO (DD4J-782): remove this solution after it has been verified to be sufficiently handled in DSS. */ private static void assertNoExcessEncapsulatedTimeStamps(final XAdESSignature xadesSignature) { - final XAdESPaths xadesPaths = xadesSignature.getXAdESPaths(); + final XAdESPath xadesPaths = xadesSignature.getXAdESPaths(); final NodeList signatureTimeStamps = DomUtils.getNodeList(xadesSignature.getSignatureElement(), xadesPaths.getSignatureTimestampPath()); if (signatureTimeStamps == null || signatureTimeStamps.getLength() < 1) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSigningDssFacade.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSigningDssFacade.java index 8eaf398d6..6ba29b269 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSigningDssFacade.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesSigningDssFacade.java @@ -10,8 +10,7 @@ package org.digidoc4j.impl.asic.xades; -import eu.europa.esig.dss.DomUtils; -import eu.europa.esig.dss.asic.common.definition.ASiCNamespace; +import eu.europa.esig.asic.manifest.definition.ASiCManifestNamespace; import eu.europa.esig.dss.enumerations.DigestAlgorithm; import eu.europa.esig.dss.enumerations.EncryptionAlgorithm; import eu.europa.esig.dss.enumerations.SignatureLevel; @@ -36,6 +35,7 @@ import eu.europa.esig.dss.xades.DSSXMLUtils; import eu.europa.esig.dss.xades.XAdESSignatureParameters; import eu.europa.esig.dss.xades.signature.XAdESService; +import eu.europa.esig.dss.xml.utils.DomUtils; import org.digidoc4j.DataFile; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.exceptions.TechnicalException; @@ -248,7 +248,7 @@ private DSSDocument surroundWithXadesXmlTag(DSSDocument signedDocument) { logger.debug("Surrounding signature document with xades tag"); Document signatureDom = DomUtils.buildDOM(signedDocument); Element signatureElement = signatureDom.getDocumentElement(); - Document document = XmlDomCreator.createDocument(ASiCNamespace.NS.getUri(), XmlDomCreator.ASICS_NS, signatureElement); + Document document = XmlDomCreator.createDocument(ASiCManifestNamespace.NS.getUri(), XmlDomCreator.ASICS_NS, signatureElement); byte[] documentBytes = DSSXMLUtils.serializeNode(document); return new InMemoryDocument(documentBytes); } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java index 031f56a9e..880aa59c1 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.asic.xades; import eu.europa.esig.dss.i18n.I18nProvider; @@ -38,7 +48,7 @@ public static void process(Reports validationReports) { * @param validationReports */ private static void removeFalsePositiveWarningsFromValidationReports(Reports validationReports) { - for (XmlToken xmlToken : validationReports.getSimpleReportJaxb().getSignatureOrTimestamp()) { + for (XmlToken xmlToken : validationReports.getSimpleReportJaxb().getSignatureOrTimestampOrEvidenceRecord()) { if (xmlToken instanceof XmlSignature) { removeFalsePositiveWarningsFromSignatureResult((XmlSignature) xmlToken); } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/TimestampSignatureValidator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/TimestampSignatureValidator.java index ad71851b9..f003ccbba 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/TimestampSignatureValidator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/TimestampSignatureValidator.java @@ -10,17 +10,13 @@ package org.digidoc4j.impl.asic.xades.validation; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.stream.Collectors; - +import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.enumerations.RevocationType; import eu.europa.esig.dss.simplereport.SimpleReport; import eu.europa.esig.dss.spi.DSSRevocationUtils; +import eu.europa.esig.dss.spi.x509.tsp.TimestampToken; import eu.europa.esig.dss.validation.reports.Reports; +import eu.europa.esig.dss.xades.validation.XAdESSignature; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.digidoc4j.Configuration; import org.digidoc4j.X509Cert; @@ -33,9 +29,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.europa.esig.dss.validation.timestamp.TimestampToken; -import eu.europa.esig.dss.diagnostic.DiagnosticData; -import eu.europa.esig.dss.xades.validation.XAdESSignature; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; public class TimestampSignatureValidator extends XadesSignatureValidator { @@ -64,7 +64,7 @@ private void addSigningTimeErrors() { } Date timestamp = signatureTimestamps.stream() .map(TimestampToken::getGenerationTime) - .filter(t -> t != null) + .filter(Objects::nonNull) .sorted() .findFirst() .orElse(null); @@ -82,18 +82,18 @@ private void addSigningTimeErrors() { .findFirst() .orElse(null); if (ocspTime == null) { - this.log.error("OCSP response production time is before timestamp time"); + log.error("OCSP response production time is before timestamp time"); addValidationError(new TimestampAfterOCSPResponseTimeException()); return; } int deltaLimit = this.configuration.getRevocationAndTimestampDeltaInMinutes(); long differenceInMinutes = DateUtils.differenceInMinutes(timestamp, ocspTime); - this.log.debug("Difference in minutes: <{}>", differenceInMinutes); + log.debug("Difference in minutes: <{}>", differenceInMinutes); if (!DateUtils.isInRangeMinutes(timestamp, ocspTime, deltaLimit)) { - this.log.error("The difference between the OCSP response production time and the signature timestamp is too large <{} minutes>", differenceInMinutes); + log.error("The difference between the OCSP response production time and the signature timestamp is too large <{} minutes>", differenceInMinutes); this.addValidationError(new TimestampAndOcspResponseTimeDeltaTooLargeException()); } else if (this.configuration.getAllowedTimestampAndOCSPResponseDeltaInMinutes() < differenceInMinutes && differenceInMinutes < deltaLimit) { - this.log.warn("The difference (in minutes) between the OCSP response production time and the signature timestamp is in allowable range (<{}>, allowed maximum <{}>)", differenceInMinutes, deltaLimit); + log.warn("The difference (in minutes) between the OCSP response production time and the signature timestamp is in allowable range (<{}>, allowed maximum <{}>)", differenceInMinutes, deltaLimit); this.addValidationWarning(new DigiDoc4JException("The difference between the OCSP response time and the signature timestamp is in allowable range")); } } @@ -114,9 +114,9 @@ private void addRevocationErrors() { return; } RevocationType certificateRevocationSource = diagnosticData.getCertificateRevocationSource(certificateId); - this.log.debug("Revocation source is <{}>", certificateRevocationSource); + log.debug("Revocation source is <{}>", certificateRevocationSource); if (RevocationType.CRL.equals(certificateRevocationSource)) { - this.log.error("Signing certificate revocation source is CRL instead of OCSP"); + log.error("Signing certificate revocation source is CRL instead of OCSP"); this.addValidationError(new UntrustedRevocationSourceException()); } } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java index 1fe038f81..7b9271cc6 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java @@ -10,7 +10,6 @@ package org.digidoc4j.impl.asic.xades.validation; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.detailedreport.DetailedReport; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.enumerations.Indication; @@ -24,8 +23,9 @@ import eu.europa.esig.dss.simplereport.jaxb.XmlToken; import eu.europa.esig.dss.validation.SignaturePolicy; import eu.europa.esig.dss.validation.reports.Reports; -import eu.europa.esig.dss.xades.definition.XAdESPaths; import eu.europa.esig.dss.xades.validation.XAdESSignature; +import eu.europa.esig.dss.xml.utils.DomUtils; +import eu.europa.esig.xades.definition.XAdESPath; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.digidoc4j.Configuration; @@ -130,7 +130,7 @@ protected void addPolicyErrors() { } protected boolean isSignaturePolicyImpliedElementPresented() { - XAdESPaths xAdESPaths = this.getDssSignature().getXAdESPaths(); + XAdESPath xAdESPaths = this.getDssSignature().getXAdESPaths(); Element signaturePolicyImpliedElement = DomUtils.getElement(this.getDssSignature().getSignatureElement(), String.format("%s%s", xAdESPaths.getSignaturePolicyIdentifierPath(), xAdESPaths.getCurrentSignaturePolicyImplied().replace(".", ""))); @@ -190,7 +190,7 @@ private void addPolicyUriValidationErrors() { private void addPolicyIdentifierQualifierValidationErrors() { LOGGER.debug("Extracting policy identifier qualifier validation errors"); - XAdESPaths xAdESPaths = getDssSignature().getXAdESPaths(); + XAdESPath xAdESPaths = getDssSignature().getXAdESPaths(); Element signatureElement = getDssSignature().getSignatureElement(); String xAdESPrefix = xAdESPaths.getNamespace().getPrefix(); Element element = DomUtils.getElement(signatureElement, xAdESPaths.getSignaturePolicyIdentifierPath()); @@ -280,7 +280,7 @@ private boolean isTimestampValidForSignature() { } String timestampId = timestampIdList.get(0); DetailedReport detailedReport = this.validationReport.getDetailedReport(); - return this.isIndicationValid(detailedReport.getTimestampValidationIndication(timestampId)); + return this.isIndicationValid(detailedReport.getBasicTimestampValidationIndication(timestampId)); } private SimpleReport getSimpleReport(Map simpleReports) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/main/MultipleContainersExecutor.java b/digidoc4j/src/main/java/org/digidoc4j/main/MultipleContainersExecutor.java index cc75acdb1..6c8258ae8 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/main/MultipleContainersExecutor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/main/MultipleContainersExecutor.java @@ -1,19 +1,16 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.main; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - +import eu.europa.esig.dss.enumerations.MimeType; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; @@ -22,7 +19,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.europa.esig.dss.model.MimeType; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; /** * Container executor for batch task e.g. input folder and output folder diff --git a/digidoc4j/src/main/java/org/digidoc4j/signers/TimestampToken.java b/digidoc4j/src/main/java/org/digidoc4j/signers/TimestampToken.java index fbdc729f1..3d0aa7e52 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/signers/TimestampToken.java +++ b/digidoc4j/src/main/java/org/digidoc4j/signers/TimestampToken.java @@ -11,8 +11,8 @@ package org.digidoc4j.signers; import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.model.InMemoryDocument; -import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.TimestampBinary; import eu.europa.esig.dss.service.tsp.OnlineTSPSource; import eu.europa.esig.dss.spi.DSSUtils; @@ -102,8 +102,8 @@ private static DataFile getTimestampToken(OnlineTSPSource onlineTSPSource, Diges TimestampBinary timestampBinary = onlineTSPSource.getTimeStampResponse(digestAlgorithm, digest); String timestampFilename = "timestamp"; timeStampToken.setDocument( - new InMemoryDocument(timestampBinary.getBytes(), timestampFilename, MimeType.TST)); - timeStampToken.setMediaType(MimeType.TST.getMimeTypeString()); + new InMemoryDocument(timestampBinary.getBytes(), timestampFilename, MimeTypeEnum.TST)); + timeStampToken.setMediaType(MimeTypeEnum.TST.getMimeTypeString()); return timeStampToken; } diff --git a/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java b/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java index 7347de2c8..cba5fab63 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java +++ b/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java @@ -1,10 +1,9 @@ package org.digidoc4j.utils; +import eu.europa.esig.dss.enumerations.MimeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.europa.esig.dss.model.MimeType; - /** * Created by Janar Rahumeel (CGI Estonia) */ diff --git a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java index 205ffb6aa..983b8f936 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java @@ -10,9 +10,9 @@ package org.digidoc4j; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.enumerations.ObjectIdentifierQualifier; import eu.europa.esig.dss.model.DSSDocument; -import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.Policy; import eu.europa.esig.dss.model.x509.CertificateToken; import eu.europa.esig.dss.service.tsp.OnlineTSPSource; @@ -485,11 +485,11 @@ protected List createDataFilesToSign() { } protected DataFile createBinaryDataFile(String fileName, byte[] fileContent) { - return new DataFile(fileContent, fileName, MimeType.BINARY.getMimeTypeString()); + return new DataFile(fileContent, fileName, MimeTypeEnum.BINARY.getMimeTypeString()); } protected DataFile createTextDataFile(String fileName, String fileContent) { - return new DataFile(fileContent.getBytes(StandardCharsets.UTF_8), fileName, MimeType.TEXT.getMimeTypeString()); + return new DataFile(fileContent.getBytes(StandardCharsets.UTF_8), fileName, MimeTypeEnum.TEXT.getMimeTypeString()); } protected void evictTSLCache() { diff --git a/digidoc4j/src/test/java/org/digidoc4j/ContainerZipTest.java b/digidoc4j/src/test/java/org/digidoc4j/ContainerZipTest.java index 1d3379955..ff1877b04 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/ContainerZipTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/ContainerZipTest.java @@ -1,6 +1,16 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import org.digidoc4j.ddoc.Manifest; import org.digidoc4j.exceptions.DigiDoc4JException; import org.junit.Assert; @@ -146,7 +156,7 @@ public void loadedBdocWithNonFirstMimeTypeSavedAsStreamShouldHaveStoredMimeTypeA @Test public void loadedAsiceWithNonFirstMimeTypeSavedAsStreamShouldHaveStoredMimeTypeAsFirstEntry() throws Exception { File testNonFirstMimeTypeAsiceFile = testFolder.newFile("original-non-first-mimetype-asice.asice"); - saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsiceFile, MimeType.ASICE.getMimeTypeString()); + saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsiceFile, MimeTypeEnum.ASICE.getMimeTypeString()); Container container = ContainerOpener.open(testNonFirstMimeTypeAsiceFile.getPath()); readAndAssertFirstEntryStoredMimeType(container.saveAsStream()); } @@ -154,7 +164,7 @@ public void loadedAsiceWithNonFirstMimeTypeSavedAsStreamShouldHaveStoredMimeType @Test public void loadedAsicsWithNonFirstMimeTypeSavedAsStreamShouldHaveStoredMimeTypeAsFirstEntry() throws Exception { File testNonFirstMimeTypeAsicsFile = testFolder.newFile("original-non-first-mimetype-asics.asics"); - saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsicsFile, MimeType.ASICS.getMimeTypeString()); + saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsicsFile, MimeTypeEnum.ASICS.getMimeTypeString()); Container container = ContainerOpener.open(testNonFirstMimeTypeAsicsFile.getPath()); readAndAssertFirstEntryStoredMimeType(container.saveAsStream()); } @@ -170,7 +180,7 @@ public void loadedBdocWithNonFirstMimeTypeSavedAsFileShouldHaveStoredMimeTypeAsF @Test public void loadedAsiceWithNonFirstMimeTypeSavedAsFileShouldHaveStoredMimeTypeAsFirstEntry() throws Exception { File testNonFirstMimeTypeAsiceFile = testFolder.newFile("original-non-first-mimetype-asice.asice"); - saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsiceFile, MimeType.ASICE.getMimeTypeString()); + saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsiceFile, MimeTypeEnum.ASICE.getMimeTypeString()); File testFile = createTestContainerFile(ContainerOpener.open(testNonFirstMimeTypeAsiceFile.getPath()), "loaded-non-first-mimetype-asice.asice"); readAndAssertFirstEntryStoredMimeType(new FileInputStream(testFile)); } @@ -178,7 +188,7 @@ public void loadedAsiceWithNonFirstMimeTypeSavedAsFileShouldHaveStoredMimeTypeAs @Test public void loadedAsicsWithNonFirstMimeTypeSavedAsFileShouldHaveStoredMimeTypeAsFirstEntry() throws Exception { File testNonFirstMimeTypeAsicsFile = testFolder.newFile("original-non-first-mimetype-asics.asics"); - saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsicsFile, MimeType.ASICS.getMimeTypeString()); + saveDegenerateContainerWithNonFirstMimeType(testNonFirstMimeTypeAsicsFile, MimeTypeEnum.ASICS.getMimeTypeString()); File testFile = createTestContainerFile(ContainerOpener.open(testNonFirstMimeTypeAsicsFile.getPath()), "loaded-non-first-mimetype-asics.asics"); readAndAssertFirstEntryStoredMimeType(new FileInputStream(testFile)); } @@ -230,13 +240,13 @@ private File createTestDeflatedMimeTypeBdocFile() throws Exception { private File createTestDeflatedMimeTypeAsiceFile() throws Exception { File testDeflatedMimeTypeAsiceFile = testFolder.newFile("original-deflated-mimetype-asice.asice"); - saveDegenerateContainerWithDeflatedMimeType(testDeflatedMimeTypeAsiceFile, MimeType.ASICE.getMimeTypeString()); + saveDegenerateContainerWithDeflatedMimeType(testDeflatedMimeTypeAsiceFile, MimeTypeEnum.ASICE.getMimeTypeString()); return testDeflatedMimeTypeAsiceFile; } private File createTestDeflatedMimeTypeAsicsFile() throws Exception { File testDeflatedMimeTypeAsicsFile = testFolder.newFile("original-deflated-mimetype-asics.asics"); - saveDegenerateContainerWithDeflatedMimeType(testDeflatedMimeTypeAsicsFile, MimeType.ASICS.getMimeTypeString()); + saveDegenerateContainerWithDeflatedMimeType(testDeflatedMimeTypeAsicsFile, MimeTypeEnum.ASICS.getMimeTypeString()); return testDeflatedMimeTypeAsicsFile; } diff --git a/digidoc4j/src/test/java/org/digidoc4j/FileNameTest.java b/digidoc4j/src/test/java/org/digidoc4j/FileNameTest.java index 902582959..f25e17114 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/FileNameTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/FileNameTest.java @@ -1,9 +1,19 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j; import java.io.File; import java.io.FileInputStream; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import org.digidoc4j.exceptions.InvalidDataFileException; import org.digidoc4j.utils.Helper; import org.junit.Assert; @@ -16,7 +26,7 @@ public void createContainerWithSpecialCharactersInFileName() throws Exception { File folder = this.testFolder.newFolder("tmp"); try (FileInputStream stream = new FileInputStream("src/test/resources/testFiles/special-char-files/dds_acrobat.pdf")) { Container container = ContainerBuilder.aContainer().withDataFile(stream, - "xxx,%2003:1737,%2031.08.2015.a.pdf", MimeType.PDF.getMimeTypeString()) + "xxx,%2003:1737,%2031.08.2015.a.pdf", MimeTypeEnum.PDF.getMimeTypeString()) .usingTempDirectory(folder.getPath()).build(); String file = this.getFileBy("bdoc"); container.saveAsFile(file); @@ -28,7 +38,7 @@ public void createContainerWithSpecialCharactersInFileName() throws Exception { public void createContainer() throws Exception { File folder = this.testFolder.newFolder("tmp"); try (FileInputStream stream = new FileInputStream("src/test/resources/testFiles/special-char-files/dds_acrobat.pdf")) { - Container container = ContainerBuilder.aContainer().withDataFile(stream, "cgi.pdf", MimeType.PDF.getMimeTypeString()) + Container container = ContainerBuilder.aContainer().withDataFile(stream, "cgi.pdf", MimeTypeEnum.PDF.getMimeTypeString()) .usingTempDirectory(folder.getPath()).build(); String file = this.getFileBy("bdoc"); container.saveAsFile(file); diff --git a/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java b/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java index bebacb3e3..3d122de60 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java @@ -1,16 +1,16 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import org.digidoc4j.test.RestrictedExternalResourceRule; import org.digidoc4j.test.RestrictedExternalResourceRule.FileWritingRestrictedException; import org.digidoc4j.test.TestAssert; @@ -80,7 +80,7 @@ public void creatingDataFilesForDDoc_shouldNotStoreDataFilesOnDisk_byDefault() t public void creatingLargeDataFile_shouldStoreFileOnDisk() throws Throwable { InputStream dataFileInputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); try { - DataFile dataFile = new LargeDataFile(dataFileInputStream, "stream-file.txt", MimeType.TEXT.getMimeTypeString()); + DataFile dataFile = new LargeDataFile(dataFileInputStream, "stream-file.txt", MimeTypeEnum.TEXT.getMimeTypeString()); Assert.assertFalse("Did not create a temporary file", true); } catch (Exception e) { throw e.getCause(); @@ -118,10 +118,10 @@ public void openingExistingContainer_withLarge2MbFile_shouldNotStoreDataFilesOnD @Override protected Container createNonEmptyContainerBy(Container.DocumentType documentType) { - DataFile pathDataFile = new DataFile("src/test/resources/testFiles/helper-files/test.txt", MimeType.TEXT.getMimeTypeString()); - DataFile byteDataFile = new DataFile(new byte[]{1, 2, 3}, "byte-file.txt", MimeType.TEXT.getMimeTypeString()); + DataFile pathDataFile = new DataFile("src/test/resources/testFiles/helper-files/test.txt", MimeTypeEnum.TEXT.getMimeTypeString()); + DataFile byteDataFile = new DataFile(new byte[]{1, 2, 3}, "byte-file.txt", MimeTypeEnum.TEXT.getMimeTypeString()); InputStream dataFileInputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); - DataFile streamDataFile = new DataFile(dataFileInputStream, "stream-file.txt", MimeType.TEXT.getMimeTypeString()); + DataFile streamDataFile = new DataFile(dataFileInputStream, "stream-file.txt", MimeTypeEnum.TEXT.getMimeTypeString()); return ContainerBuilder.aContainer(documentType).withDataFile(pathDataFile).withDataFile(byteDataFile). withDataFile(streamDataFile).build(); } @@ -130,9 +130,9 @@ private Container createNonEmptyContainerIncludingPDFFileBy(Container.DocumentTy InputStream dataFileInputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); File pdfFile = new File("src/test/resources/testFiles/special-char-files/dds_acrobat.pdf"); return ContainerBuilder.aContainer(documentType). - withDataFile(dataFileInputStream, "test-stream.txt", MimeType.TEXT.getMimeTypeString()). - withDataFile("src/test/resources/testFiles/helper-files/test.txt", MimeType.TEXT.getMimeTypeString()). - withDataFile(pdfFile, MimeType.PDF.getMimeTypeString()).build(); + withDataFile(dataFileInputStream, "test-stream.txt", MimeTypeEnum.TEXT.getMimeTypeString()). + withDataFile("src/test/resources/testFiles/helper-files/test.txt", MimeTypeEnum.TEXT.getMimeTypeString()). + withDataFile(pdfFile, MimeTypeEnum.PDF.getMimeTypeString()).build(); } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/SkDataLoaderTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/SkDataLoaderTest.java index 03a71c912..367dc74a2 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/SkDataLoaderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/SkDataLoaderTest.java @@ -10,7 +10,7 @@ package org.digidoc4j.impl; -import eu.europa.esig.dss.model.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.service.http.proxy.ProxyConfig; import eu.europa.esig.dss.service.http.proxy.ProxyProperties; import org.digidoc4j.AbstractTest; @@ -28,13 +28,13 @@ public class SkDataLoaderTest extends AbstractTest { @Test - public void ocspDataLoader_withoutProxyConfiguration() throws Exception { + public void ocspDataLoader_withoutProxyConfiguration() { SkDataLoader dataLoader = new SkOCSPDataLoader(this.configuration); Assert.assertNull(dataLoader.getProxyConfig()); } @Test - public void ocspDataLoader_withProxyConfiguration() throws Exception { + public void ocspDataLoader_withProxyConfiguration() { this.configuration.setHttpProxyHost("proxyHost"); this.configuration.setHttpProxyPort(1345); SkDataLoader dataLoader = new SkOCSPDataLoader(this.configuration); @@ -51,7 +51,7 @@ public void ocspDataLoader_withProxyConfiguration() throws Exception { } @Test - public void dataLoader_withPasswordProxyConfiguration() throws Exception { + public void dataLoader_withPasswordProxyConfiguration() { this.configuration.setHttpProxyHost("proxyHost"); this.configuration.setHttpProxyPort(1345); this.configuration.setHttpProxyUser("proxyUser"); @@ -66,24 +66,24 @@ public void dataLoader_withPasswordProxyConfiguration() throws Exception { Assert.assertEquals("proxyHost", httpProperties.getHost()); Assert.assertEquals(1345, httpProperties.getPort()); Assert.assertEquals("proxyUser", httpProperties.getUser()); - Assert.assertEquals("proxyPassword", httpProperties.getPassword()); + Assert.assertArrayEquals("proxyPassword".toCharArray(), httpProperties.getPassword()); } @Test @Ignore("Requires access to the proxy server") - public void createSignAsicOverProxy() throws Exception { + public void createSignAsicOverProxy() { TslLoader.invalidateCache(); this.configuration.setHttpProxyHost("cache.elion.ee"); this.configuration.setHttpProxyPort(8080); Container container = ContainerBuilder.aContainer().withConfiguration(this.configuration). - withDataFile("src/test/resources/testFiles/helper-files/test.txt", MimeType.TEXT.getMimeTypeString()). + withDataFile("src/test/resources/testFiles/helper-files/test.txt", MimeTypeEnum.TEXT.getMimeTypeString()). build(); - Signature signature = this.createSignatureBy(container, SignatureProfile.LT, this.pkcs12SignatureToken); + Signature signature = this.createSignatureBy(container, SignatureProfile.LT, pkcs12SignatureToken); Assert.assertTrue(signature.validateSignature().isValid()); } @Test - public void dataLoader_withoutSslConfiguration_shouldNotSetSslValues() throws Exception { + public void dataLoader_withoutSslConfiguration_shouldNotSetSslValues() { MockSkDataLoader dataLoader = new MockSkDataLoader(this.configuration); Assert.assertNull(dataLoader.getSslKeystore()); Assert.assertNull(dataLoader.getSslKeystoreType()); @@ -98,7 +98,7 @@ public void dataLoader_withoutSslConfiguration_shouldNotSetSslValues() throws Ex } @Test - public void dataLoader_withSslConfiguration_shouldSetSslValues() throws Exception { + public void dataLoader_withSslConfiguration_shouldSetSslValues() { this.configuration.setSslKeystorePath("classpath:testFiles/keystores/keystore.p12"); this.configuration.setSslKeystoreType("PKCS12"); this.configuration.setSslKeystorePassword("keystore-password"); @@ -108,10 +108,10 @@ public void dataLoader_withSslConfiguration_shouldSetSslValues() throws Exceptio MockSkDataLoader dataLoader = new MockSkDataLoader(this.configuration); Assert.assertNotNull(dataLoader.getSslKeystore()); Assert.assertEquals("PKCS12", dataLoader.getSslKeystoreType()); - Assert.assertEquals("keystore-password", dataLoader.getSslKeystorePassword()); + Assert.assertArrayEquals("keystore-password".toCharArray(), dataLoader.getSslKeystorePassword()); Assert.assertNotNull(dataLoader.getSslTruststore()); Assert.assertEquals("JKS", dataLoader.getSslTruststoreType()); - Assert.assertEquals("digidoc4j-password", dataLoader.getSslTruststorePassword()); + Assert.assertArrayEquals("digidoc4j-password".toCharArray(), dataLoader.getSslTruststorePassword()); Assert.assertTrue(dataLoader.isSslKeystoreTypeSet()); Assert.assertTrue(dataLoader.isSslKeystorePasswordSet()); Assert.assertTrue(dataLoader.isSslTruststoreTypeSet()); @@ -119,7 +119,7 @@ public void dataLoader_withSslConfiguration_shouldSetSslValues() throws Exceptio } @Test - public void dataLoader_withMinimalSslConfiguration_shouldNotSetNullValues() throws Exception { + public void dataLoader_withMinimalSslConfiguration_shouldNotSetNullValues() { this.configuration.setSslKeystorePath("classpath:testFiles/keystores/keystore.jks"); this.configuration.setSslTruststorePath("classpath:testFiles/keystores/truststore.jks"); MockSkDataLoader dataLoader = new MockSkDataLoader(this.configuration); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/StreamDocumentTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/StreamDocumentTest.java index 56fc2419e..344e1fec9 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/StreamDocumentTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/StreamDocumentTest.java @@ -11,8 +11,9 @@ package org.digidoc4j.impl; import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import eu.europa.esig.dss.enumerations.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; import eu.europa.esig.dss.model.DSSException; -import eu.europa.esig.dss.model.MimeType; import org.apache.commons.io.IOUtils; import org.digidoc4j.AbstractTest; import org.digidoc4j.DataFile; @@ -118,7 +119,7 @@ public void getMimeType() throws Exception { @Test public void setMimeType() throws Exception { - this.document.setMimeType(MimeType.XML); + this.document.setMimeType(MimeTypeEnum.XML); Assert.assertEquals("text/xml", this.document.getMimeType().getMimeTypeString()); } @@ -187,7 +188,7 @@ public int read() throws IOException { } }; - this.document = new StreamDocument(stream, "suur_a.txt", MimeType.TEXT); + this.document = new StreamDocument(stream, "suur_a.txt", MimeTypeEnum.TEXT); stream.close(); this.document.openStream(); } @@ -214,7 +215,7 @@ public void testGetDigestThrowsException() throws Exception { @Override protected void before() { try (ByteArrayInputStream stream = new ByteArrayInputStream(new byte[]{0x041})) { - this.document = new StreamDocument(stream, "suur_a.txt", MimeType.TEXT); + this.document = new StreamDocument(stream, "suur_a.txt", MimeTypeEnum.TEXT); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/DataLoaderDecoratorTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/DataLoaderDecoratorTest.java index 959107a33..8abf57699 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/DataLoaderDecoratorTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/DataLoaderDecoratorTest.java @@ -104,7 +104,7 @@ public void decorateWithSslSettingsShouldApplyAllSslKeystoreConfigurationIfPrese DataLoaderDecorator.decorateWithSslSettings(dataLoader, configuration); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystoreType(KEYSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD.toCharArray()); Mockito.verifyNoMoreInteractions(dataLoader); } @@ -121,7 +121,7 @@ public void decorateWithSslSettingsForShouldApplyAllSslKeystoreConfigurationIfPr DataLoaderDecorator.decorateWithSslSettingsFor(connectionType, dataLoader, configuration); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystoreType(KEYSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD.toCharArray()); Mockito.verifyNoMoreInteractions(dataLoader); Mockito.reset(configuration, dataLoader); @@ -168,7 +168,7 @@ public void decorateWithSslSettingsShouldApplyAllSslTruststoreConfigurationIfPre DataLoaderDecorator.decorateWithSslSettings(dataLoader, configuration); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststoreType(TRUSTSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD.toCharArray()); Mockito.verifyNoMoreInteractions(dataLoader); } @@ -185,7 +185,7 @@ public void decorateWithSslSettingsForShouldApplyAllSslTruststoreConfigurationIf DataLoaderDecorator.decorateWithSslSettingsFor(connectionType, dataLoader, configuration); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststoreType(TRUSTSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD.toCharArray()); Mockito.verifyNoMoreInteractions(dataLoader); Mockito.reset(configuration, dataLoader); @@ -272,11 +272,11 @@ public void decorateWithSslSettingsShouldApplyAllConfiguredSslProperties() { Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystoreType(KEYSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD.toCharArray()); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststoreType(TRUSTSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD.toCharArray()); ArgumentCaptor protocolsCaptor = ArgumentCaptor.forClass(String[].class); Mockito.verify(dataLoader, Mockito.times(1)).setSupportedSSLProtocols(protocolsCaptor.capture()); @@ -306,11 +306,11 @@ public void decorateWithSslSettingsForShouldApplyAllConfiguredSslProperties() { Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystoreType(KEYSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslKeystorePassword(KEYSTORE_PASSWORD.toCharArray()); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststore(any(KeyStoreDocument.class)); Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststoreType(TRUSTSTORE_TYPE); - Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD); + Mockito.verify(dataLoader, Mockito.times(1)).setSslTruststorePassword(TRUSTSTORE_PASSWORD.toCharArray()); ArgumentCaptor protocolsCaptor = ArgumentCaptor.forClass(String[].class); Mockito.verify(dataLoader, Mockito.times(1)).setSupportedSSLProtocols(protocolsCaptor.capture()); @@ -512,7 +512,7 @@ public void decorateWithProxySettingsShouldApplyHttpUserAndPasswordIfConfigured( Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); } @Test @@ -533,7 +533,7 @@ public void decorateWithProxySettingsForShouldApplyHttpUserAndPasswordIfConfigur Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); Mockito.reset(configuration, dataLoader); } @@ -556,7 +556,7 @@ public void decorateWithProxySettingsShouldApplyHttpsUserAndPasswordIfConfigured Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); } @Test @@ -577,7 +577,7 @@ public void decorateWithProxySettingsForShouldApplyHttpsUserAndPasswordIfConfigu Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); Mockito.reset(configuration, dataLoader); } @@ -608,7 +608,7 @@ public void decorateWithProxySettingsShouldApplyAllButHttpUserAndPasswordIfNotCo Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); } @Test @@ -637,7 +637,7 @@ public void decorateWithProxySettingsForShouldApplyAllButHttpUserAndPasswordIfNo Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); Mockito.reset(configuration, dataLoader); } @@ -662,7 +662,7 @@ public void decorateWithProxySettingsShouldApplyAllButHttpsUserAndPasswordIfNotC Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); Assert.assertEquals(473, capturedProxyConfig.getHttpsProperties().getPort()); Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); @@ -691,7 +691,7 @@ public void decorateWithProxySettingsForShouldApplyAllButHttpsUserAndPasswordIfN Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); Assert.assertEquals(473, capturedProxyConfig.getHttpsProperties().getPort()); Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); @@ -724,13 +724,13 @@ public void decorateWithProxySettingsShouldApplyAllConfiguredProxySettings() { Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); Assert.assertEquals(473, capturedProxyConfig.getHttpsProperties().getPort()); Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); } @Test @@ -755,13 +755,13 @@ public void decorateWithProxySettingsForShouldApplyAllConfiguredProxySettings() Assert.assertEquals("httpProxyHost", capturedProxyConfig.getHttpProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpProperties().getExcludedHosts()); Assert.assertEquals("httpProxyUser", capturedProxyConfig.getHttpProperties().getUser()); - Assert.assertEquals("httpProxyPassword", capturedProxyConfig.getHttpProperties().getPassword()); + Assert.assertArrayEquals("httpProxyPassword".toCharArray(), capturedProxyConfig.getHttpProperties().getPassword()); Assert.assertEquals(473, capturedProxyConfig.getHttpsProperties().getPort()); Assert.assertEquals("httpsProxyHost", capturedProxyConfig.getHttpsProperties().getHost()); Assert.assertNull(capturedProxyConfig.getHttpsProperties().getExcludedHosts()); Assert.assertEquals("httpsProxyUser", capturedProxyConfig.getHttpsProperties().getUser()); - Assert.assertEquals("httpsProxyPassword", capturedProxyConfig.getHttpsProperties().getPassword()); + Assert.assertArrayEquals("httpsProxyPassword".toCharArray(), capturedProxyConfig.getHttpsProperties().getPassword()); Mockito.reset(configuration, dataLoader); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/manifest/ManifestValidatorTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/manifest/ManifestValidatorTest.java index 8f8b0c8e7..a8c8b4554 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/manifest/ManifestValidatorTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/manifest/ManifestValidatorTest.java @@ -1,19 +1,19 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl.asic.manifest; +import eu.europa.esig.dss.enumerations.MimeType; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.FileDocument; import eu.europa.esig.dss.model.InMemoryDocument; -import eu.europa.esig.dss.model.MimeType; import org.digidoc4j.Configuration; import org.digidoc4j.DataFile; import org.digidoc4j.Signature; diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java index bf0dfc654..8bf31315a 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocContainerTest.java @@ -10,9 +10,9 @@ package org.digidoc4j.impl.bdoc; -import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.validation.SignaturePolicy; import eu.europa.esig.dss.xades.validation.XAdESSignature; +import eu.europa.esig.dss.xml.utils.DomUtils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java index d4bea3a2b..703da1fc8 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java @@ -1,9 +1,21 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.bdoc.asic; import java.io.FileInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; +import eu.europa.esig.dss.spi.x509.tsp.TimestampToken; import org.digidoc4j.AbstractTest; import org.digidoc4j.Configuration; import org.digidoc4j.Container; @@ -23,10 +35,8 @@ import org.junit.contrib.java.lang.system.SystemOutRule; import eu.europa.esig.dss.enumerations.DigestAlgorithm; -import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.enumerations.SignatureAlgorithm; import eu.europa.esig.dss.utils.Utils; -import eu.europa.esig.dss.validation.timestamp.TimestampToken; import eu.europa.esig.dss.enumerations.Indication; import eu.europa.esig.dss.enumerations.TimestampType; @@ -124,9 +134,9 @@ public void createsContainerWithTstASICS() throws Exception { assertNotNull(manifestEntry); assertNotNull(timestampEntry); String mimeTypeContent = this.getFileContent(zipFile.getInputStream(mimeTypeEntry)); - Assert.assertTrue(mimeTypeContent.contains(MimeType.ASICS.getMimeTypeString())); + Assert.assertTrue(mimeTypeContent.contains(MimeTypeEnum.ASICS.getMimeTypeString())); String manifestContent = this.getFileContent(zipFile.getInputStream(manifestEntry)); - Assert.assertTrue(manifestContent.contains(MimeType.ASICS.getMimeTypeString())); + Assert.assertTrue(manifestContent.contains(MimeTypeEnum.ASICS.getMimeTypeString())); Container container = ContainerOpener.open(fileName); SignatureValidationResult validate = container.validate(); Assert.assertTrue(validate.isValid()); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java index 48e42b728..5463c9cba 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.bdoc.xades; import eu.europa.esig.dss.i18n.I18nProvider; @@ -31,7 +41,7 @@ public void organizationNameMissingWarningRemoved() { i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) ); XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestamp().add(signature); + simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); Reports validationReports = Mockito.mock(Reports.class); when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); @@ -54,7 +64,7 @@ public void organizationNameMissingWarningRemovedFromTimestamp() { ); mockSignatureTimestamps(signature, timestamp); XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestamp().add(signature); + simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); Reports validationReports = Mockito.mock(Reports.class); when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); @@ -77,7 +87,7 @@ public void trustedCertificateNotMatchingWithTrustedServiceWarningRemoved() { i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) ); XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestamp().add(signature); + simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); Reports validationReports = Mockito.mock(Reports.class); when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); @@ -100,7 +110,7 @@ public void trustedCertificateNotMatchingWithTrustedServiceWarningRemovedFromTim ); mockSignatureTimestamps(signature, timestamp); XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestamp().add(signature); + simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); Reports validationReports = Mockito.mock(Reports.class); when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); @@ -123,7 +133,7 @@ public void noWarningRemoved() { i18nProvider.getMessage(MessageTag.QUAL_CERT_TYPE_AT_CC) ); XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestamp().add(signature); + simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); Reports validationReports = Mockito.mock(Reports.class); when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); diff --git a/digidoc4j/src/test/java/org/digidoc4j/signers/PKCS11SignatureTokenTest.java b/digidoc4j/src/test/java/org/digidoc4j/signers/PKCS11SignatureTokenTest.java index 60cdf4548..60e6d5d50 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/signers/PKCS11SignatureTokenTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/signers/PKCS11SignatureTokenTest.java @@ -1,21 +1,19 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.signers; -import java.security.KeyStore; -import java.security.cert.X509Certificate; -import java.util.List; - -import javax.xml.bind.DatatypeConverter; - +import eu.europa.esig.dss.token.DSSPrivateKeyEntry; +import eu.europa.esig.dss.token.PasswordInputCallback; +import eu.europa.esig.dss.token.PrefilledPasswordCallback; +import jakarta.xml.bind.DatatypeConverter; import org.digidoc4j.AbstractTest; import org.digidoc4j.Container; import org.digidoc4j.DigestAlgorithm; @@ -27,9 +25,9 @@ import org.junit.Ignore; import org.junit.Test; -import eu.europa.esig.dss.token.DSSPrivateKeyEntry; -import eu.europa.esig.dss.token.PasswordInputCallback; -import eu.europa.esig.dss.token.PrefilledPasswordCallback; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.util.List; /** * PKCS#11 module path depends on your operating system and installed smart card or hardware token library. diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/MockConfigurableDataLoader.java b/digidoc4j/src/test/java/org/digidoc4j/test/MockConfigurableDataLoader.java index c07d0c183..3155cc1af 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/MockConfigurableDataLoader.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/MockConfigurableDataLoader.java @@ -64,11 +64,6 @@ public DataAndUrl get(List urlStrings) throws DSSException { } } - @Override - public byte[] get(String url, boolean refresh) throws DSSException { - return getter.get(url, refresh); - } - @Override public byte[] post(String url, byte[] content) throws DSSException { return poster.post(url, content); diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/MockSkDataLoader.java b/digidoc4j/src/test/java/org/digidoc4j/test/MockSkDataLoader.java index 8d95e6558..1b8693fc7 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/MockSkDataLoader.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/MockSkDataLoader.java @@ -1,21 +1,19 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.test; import eu.europa.esig.dss.model.DSSDocument; -import eu.europa.esig.dss.model.FileDocument; import org.digidoc4j.Configuration; import org.digidoc4j.ServiceType; import org.digidoc4j.impl.SkDataLoader; -import org.digidoc4j.utils.ResourceUtils; /** * Created by Janar Rahumeel (CGI Estonia) @@ -25,10 +23,10 @@ public class MockSkDataLoader extends SkDataLoader { private DSSDocument sslKeystore; private String sslKeystoreType; - private String sslKeystorePassword; + private char[] sslKeystorePassword; private DSSDocument sslTruststore; private String sslTruststoreType; - private String sslTruststorePassword; + private char[] sslTruststorePassword; private boolean isSslKeystoreTypeSet; private boolean sslKeystorePasswordSet; private boolean sslTruststoreTypeSet; @@ -47,6 +45,7 @@ public DSSDocument getSslKeystore() { return sslKeystore; } + @Override public void setSslKeystore(DSSDocument sslKeystore) { super.setSslKeystore(sslKeystore); this.sslKeystore = sslKeystore; @@ -56,17 +55,19 @@ public String getSslKeystoreType() { return sslKeystoreType; } + @Override public void setSslKeystoreType(String sslKeystoreType) { super.setSslKeystoreType(sslKeystoreType); this.sslKeystoreType = sslKeystoreType; this.isSslKeystoreTypeSet = true; } - public String getSslKeystorePassword() { + public char[] getSslKeystorePassword() { return sslKeystorePassword; } - public void setSslKeystorePassword(String sslKeystorePassword) { + @Override + public void setSslKeystorePassword(char[] sslKeystorePassword) { super.setSslKeystorePassword(sslKeystorePassword); this.sslKeystorePassword = sslKeystorePassword; this.sslKeystorePasswordSet = true; @@ -76,6 +77,7 @@ public DSSDocument getSslTruststore() { return sslTruststore; } + @Override public void setSslTruststore(DSSDocument sslTruststore) { this.sslTruststore = sslTruststore; super.setSslKeystore(sslTruststore); @@ -85,17 +87,19 @@ public String getSslTruststoreType() { return sslTruststoreType; } + @Override public void setSslTruststoreType(String sslTruststoreType) { super.setSslTruststoreType(sslTruststoreType); this.sslTruststoreType = sslTruststoreType; this.sslTruststoreTypeSet = true; } - public String getSslTruststorePassword() { + public char[] getSslTruststorePassword() { return sslTruststorePassword; } - public void setSslTruststorePassword(String sslTruststorePassword) { + @Override + public void setSslTruststorePassword(char[] sslTruststorePassword) { super.setSslTruststorePassword(sslTruststorePassword); this.sslTruststorePassword = sslTruststorePassword; this.sslTruststorePasswordSet = true; diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/MockStreamDocument.java b/digidoc4j/src/test/java/org/digidoc4j/test/MockStreamDocument.java index fedac7e6a..2dfe2307d 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/MockStreamDocument.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/MockStreamDocument.java @@ -1,23 +1,22 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.test; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; +import org.digidoc4j.impl.StreamDocument; + import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; -import org.digidoc4j.impl.StreamDocument; - -import eu.europa.esig.dss.model.MimeType; - /** * Created by Janar Rahumeel (CGI Estonia) */ @@ -25,7 +24,7 @@ public class MockStreamDocument extends StreamDocument { public MockStreamDocument() { - super(new ByteArrayInputStream(new byte[]{0x041}), "fileName.txt", MimeType.TEXT); + super(new ByteArrayInputStream(new byte[]{0x041}), "fileName.txt", MimeTypeEnum.TEXT); } @Override diff --git a/pom.xml b/pom.xml index d7380c7b0..cb8cd15c4 100644 --- a/pom.xml +++ b/pom.xml @@ -142,9 +142,9 @@ 1.8 1.8 - 1.70 + 1.76 1.16.0 - 1.7.36 + 2.0.11 8.3.1 0.8.10 @@ -165,12 +165,12 @@ org.bouncycastle - bcpkix-jdk15on + bcpkix-jdk18on ${bouncycastle.version} org.bouncycastle - bcprov-jdk15on + bcprov-jdk18on ${bouncycastle.version} From 83f36a36f96827a919b07643195e2c656ccc7318 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 18 Jan 2024 08:29:26 +0200 Subject: [PATCH 08/35] DD4J-979 Refactor ddoc4j BouncyCastleNotaryFactory to be compatible with Bouncy Castle 1.76 --- .../factory/BouncyCastleNotaryFactory.java | 39 +++-- ...eNotaryFactoryResponderIdToStringTest.java | 145 ++++++++++++++++++ .../org/digidoc4j/test/util/TestOcspUtil.java | 6 +- 3 files changed, 174 insertions(+), 16 deletions(-) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactoryResponderIdToStringTest.java diff --git a/ddoc4j/src/main/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactory.java b/ddoc4j/src/main/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactory.java index 7ae0dfc73..a4c622f18 100644 --- a/ddoc4j/src/main/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactory.java +++ b/ddoc4j/src/main/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactory.java @@ -1,27 +1,39 @@ package org.digidoc4j.ddoc.factory; -import org.digidoc4j.ddoc.*; -import org.digidoc4j.ddoc.utils.BouncyCastleNotaryUtil; -import org.digidoc4j.ddoc.utils.ConfigManager; -import org.digidoc4j.ddoc.utils.ConvertUtils; -import org.bouncycastle.asn1.*; +import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ocsp.BasicOCSPResponse; import org.bouncycastle.asn1.ocsp.ResponderID; -import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.ocsp.*; +import org.bouncycastle.cert.ocsp.BasicOCSPResp; +import org.bouncycastle.cert.ocsp.CertificateID; +import org.bouncycastle.cert.ocsp.OCSPResp; +import org.bouncycastle.cert.ocsp.RevokedStatus; +import org.bouncycastle.cert.ocsp.SingleResp; +import org.bouncycastle.cert.ocsp.UnknownStatus; import org.bouncycastle.operator.ContentVerifier; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; +import org.digidoc4j.ddoc.Base64Util; +import org.digidoc4j.ddoc.CertID; +import org.digidoc4j.ddoc.CertValue; +import org.digidoc4j.ddoc.DigiDocException; +import org.digidoc4j.ddoc.Notary; import org.digidoc4j.ddoc.Signature; +import org.digidoc4j.ddoc.SignedDoc; +import org.digidoc4j.ddoc.utils.BouncyCastleNotaryUtil; +import org.digidoc4j.ddoc.utils.ConfigManager; +import org.digidoc4j.ddoc.utils.ConvertUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.OutputStream; -import java.security.*; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Provider; +import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.List; @@ -321,16 +333,13 @@ public Notary parseAndVerifyResponse(Signature sig, Notary not) * @param basResp * @return stringified responder ID */ - private String responderIDtoString(BasicOCSPResp basResp) { + static String responderIDtoString(BasicOCSPResp basResp) { if(basResp != null) { ResponderID respid = basResp.getResponderId().toASN1Primitive(); - Object o = ((DERTaggedObject)respid.toASN1Primitive()).getObject(); - if(o instanceof org.bouncycastle.asn1.DEROctetString) { - org.bouncycastle.asn1.DEROctetString oc = (org.bouncycastle.asn1.DEROctetString)o; - return "byKey: " + SignedDoc.bin2hex(oc.getOctets()); + if(respid.getKeyHash() != null) { + return "byKey: " + SignedDoc.bin2hex(respid.getKeyHash()); } else { - X509Name name = new X509Name((ASN1Sequence)o); - return "byName: " + name.toString(); + return "byName: " + respid.getName().toString(); } } else diff --git a/digidoc4j/src/test/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactoryResponderIdToStringTest.java b/digidoc4j/src/test/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactoryResponderIdToStringTest.java new file mode 100644 index 000000000..cf634e4c9 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/ddoc/factory/BouncyCastleNotaryFactoryResponderIdToStringTest.java @@ -0,0 +1,145 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.ddoc.factory; + +import eu.europa.esig.dss.spi.DSSRevocationUtils; +import org.apache.commons.codec.binary.Base64; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.ocsp.ResponderID; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.ocsp.BasicOCSPResp; +import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder; +import org.bouncycastle.cert.ocsp.RespID; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.digidoc4j.test.util.TestKeyPairUtil; +import org.digidoc4j.test.util.TestOcspUtil; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.security.PrivateKey; +import java.security.Security; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +/** + * This test covers the changes in the {@link BouncyCastleNotaryFactory#responderIDtoString(BasicOCSPResp)} of the old + * {@code ddoc4j} module, caused by the update to Bouncy Castle version 1.76 (jdk18on) from the previously used version + * of 1.70 (jdk15on). + */ +public class BouncyCastleNotaryFactoryResponderIdToStringTest { + + @BeforeClass + public static void setUpStatic() { + Security.addProvider(new BouncyCastleProvider()); + } + + @Test + public void responderIDtoString_WhenBasicOcspRespIsNull_ReturnsNull() { + String result = BouncyCastleNotaryFactory.responderIDtoString(null); + + assertThat(result, nullValue()); + } + + @Test + public void responderIDtoString_WhenBasicOcspRespResponderIdIsByNameEsteidSkOcspResponder_ReturnsIdStringByName() { + BasicOCSPResp basicOcspResp = loadBasicOcspResp( + "MIIBsAoBAKCCAakwggGlBgkrBgEFBQcwAQEEggGWMIIBkjCB/KFsMGoxCzAJBgNV" + + "BAYTAkVFMQ8wDQYDVQQKEwZFU1RFSUQxDTALBgNVBAsTBE9DU1AxITAfBgNVBAMT" + + "GEVTVEVJRC1TSyBPQ1NQIFJFU1BPTkRFUjEYMBYGCSqGSIb3DQEJARYJcGtpQHNr" + + "LmVlGA8yMDAyMTAwNzExMTA0N1owVDBSMD0wCQYFKw4DAhoFAAQUJk2D09/TR+gq" + + "txo/O5Aq31AEQNwEFHgXtQX5s1jNWYzeZ15EBkx1hmldAgQ9nDIMgAAYDzIwMDIx" + + "MDA3MTExMDQ2WqElMCMwIQYJKwYBBQUHMAECBBT7MmTl4RavU7lCjNHBMHE4e1cZ" + + "YTANBgkqhkiG9w0BAQUFAAOBgQI3ixQNVnmY8xgUe3FcrWPeqfr0fb4yvm5oxvE+" + + "hkOzhRL/DB4mnaJhG+hGoV8fQPYwJpAU5lcL5SMWPdMqPWA4bUUn8Sz5Opf8SvDi" + + "p9ZOG3YcqUIyRArXhYe8QJ10HLSIex+nvuP6I/T9N/lPQOTK1kvBK5bikTIadbrk" + + "xi8VzA==" + ); + + String result = BouncyCastleNotaryFactory.responderIDtoString(basicOcspResp); + + assertThat(result, equalTo( + "byName: C=EE,O=ESTEID,OU=OCSP,CN=ESTEID-SK OCSP RESPONDER,E=pki@sk.ee" + )); + } + + @Test + public void responderIDtoString_WhenBasicOcspRespResponderIdIsByNameKlass3SkOcspResponder_ReturnsIdStringByName() { + BasicOCSPResp basicOcspResp = loadBasicOcspResp( + "MIIBxAoBAKCCAb0wggG5BgkrBgEFBQcwAQEEggGqMIIBpjCCAQ+hfzB9MQswCQYD" + + "VQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsG" + + "A1UECxMET0NTUDEhMB8GA1UEAxMYS0xBU1MzLVNLIE9DU1AgUkVTUE9OREVSMRgw" + + "FgYJKoZIhvcNAQkBFglwa2lAc2suZWUYDzIwMDMxMDI0MTA1NzE5WjBUMFIwPTAJ" + + "BgUrDgMCGgUABBRah9vDBESosFQzbhsgnloU2ACuAgQU5T8MnXE9b7wZv5r0br8J" + + "/kDrnZYCBD9u6LKAABgPMjAwMzEwMjQxMDU3MTlaoSUwIzAhBgkrBgEFBQcwAQIE" + + "FEoJJm7/2OlQqcaFCtclJmGORxWrMA0GCSqGSIb3DQEBBQUAA4GBAJfnFWPdzjLZ" + + "OefeZa8R4S3ASHgeU85vWDZ+Klio+7dn6fap85BSvHn63sYIccVvO1QsSahu1yIg" + + "cRzVxkCNYZabbS0Cjzf+dlV4U2vIlidO6Y2q2kgzaeLvfBsPm+tcQ2YPcw9vKKrw" + + "DjH6h3QhUAC67mi91tRCYWfVo3rwVjE1" + ); + + String result = BouncyCastleNotaryFactory.responderIDtoString(basicOcspResp); + + assertThat(result, equalTo( + "byName: C=EE,O=AS Sertifitseerimiskeskus,OU=OCSP,CN=KLASS3-SK OCSP RESPONDER,E=pki@sk.ee" + )); + } + + @Test + public void responderIDtoString_WhenBasicOcspRespResponderIdIsByNameCustomSubjectDn_ReturnsIdStringByName() { + String customSubjectDn = "CN=CUSTOM,O=TEST,C=EE"; + BasicOCSPResp basicOcspResp = buildBasicOcspResp(new RespID(new X500Name(customSubjectDn))); + + String result = BouncyCastleNotaryFactory.responderIDtoString(basicOcspResp); + + assertThat(result, equalTo( + "byName: " + customSubjectDn + )); + } + + @Test + public void responderIDtoString_WhenBasicOcspRespResponderIdIsByKeyCustomKeyHash_ReturnsIdStringByKey() { + ASN1OctetString customKeyHashOctets = new DEROctetString(new byte[]{ + 0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef + }); + BasicOCSPResp basicOcspResp = buildBasicOcspResp(new RespID(new ResponderID(customKeyHashOctets))); + + String result = BouncyCastleNotaryFactory.responderIDtoString(basicOcspResp); + + assertThat(result, equalTo( + "byKey: 0123456789abcdef" + )); + } + + private static BasicOCSPResp loadBasicOcspResp(String ocspResponseBase64) { + try { + byte[] binary = Base64.decodeBase64(ocspResponseBase64); + return DSSRevocationUtils.loadOCSPFromBinaries(binary); + } catch (Exception e) { + throw new IllegalStateException("Failed to parse OCSP response", e); + } + } + + private static BasicOCSPResp buildBasicOcspResp(RespID respId) { + BasicOCSPRespBuilder basicOCSPRespBuilder = TestOcspUtil.createBasicOCSPRespBuilder(respId); + + AsymmetricCipherKeyPair keyPair = TestKeyPairUtil.generateEcKeyPair("secp384r1"); + PrivateKey privateKey = TestKeyPairUtil.toPrivateKey(keyPair.getPrivate()); + ContentSigner ocspSigner = TestOcspUtil.createOcspSigner(privateKey, "SHA384withECDSA"); + + return TestOcspUtil.buildBasicOCSPResp(basicOCSPRespBuilder, ocspSigner); + } + +} diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestOcspUtil.java b/digidoc4j/src/test/java/org/digidoc4j/test/util/TestOcspUtil.java index b7b2b0e82..4a2c7fee7 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestOcspUtil.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/util/TestOcspUtil.java @@ -31,8 +31,12 @@ public final class TestOcspUtil { + public static BasicOCSPRespBuilder createBasicOCSPRespBuilder(RespID responderId) { + return new BasicOCSPRespBuilder(responderId); + } + public static BasicOCSPRespBuilder createBasicOCSPRespBuilder(X500Name responderSubjectDn) { - return new BasicOCSPRespBuilder(new RespID(responderSubjectDn)); + return createBasicOCSPRespBuilder(new RespID(responderSubjectDn)); } public static BasicOCSPRespBuilder createBasicOCSPRespBuilder(X509CertificateHolder responderCertificate) { From 48225594aa88e4600cd8fd2d5e689289e5faebd7 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 18 Jan 2024 08:31:00 +0200 Subject: [PATCH 09/35] DD4J-980 Refactor SkDataLoader to be compatible with changed DSS CommonsDataLoader --- .../java/org/digidoc4j/impl/SkDataLoader.java | 49 ++++++++++++------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/SkDataLoader.java b/digidoc4j/src/main/java/org/digidoc4j/impl/SkDataLoader.java index 0de0699f2..54d7b7b91 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/SkDataLoader.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/SkDataLoader.java @@ -1,12 +1,12 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.impl; @@ -14,11 +14,14 @@ import org.apache.commons.lang3.StringUtils; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.protocol.HttpContext; import org.digidoc4j.Configuration; import org.digidoc4j.ServiceType; import org.digidoc4j.exceptions.ConnectionTimedOutException; @@ -59,25 +62,35 @@ public byte[] post(final String url, final byte[] content) { if (StringUtils.isBlank(this.userAgent)) { throw new TechnicalException("Header is unset"); } + HttpPost httpRequest = null; - CloseableHttpResponse httpResponse = null; CloseableHttpClient client = null; try { final URI uri = URI.create(url.trim()); httpRequest = new HttpPost(uri); httpRequest.setHeader("User-Agent", this.userAgent); - ByteArrayInputStream bis = new ByteArrayInputStream(content); - HttpEntity httpEntity = new InputStreamEntity(bis, content.length, null); - HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); + + final ByteArrayInputStream bis = new ByteArrayInputStream(content); + final HttpEntity httpEntity = new InputStreamEntity(bis, content.length, null); + final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); httpRequest.setEntity(requestEntity); + if (StringUtils.isNotBlank(this.contentType)) { httpRequest.setHeader("Content-Type", this.contentType); } + client = getHttpClient(url); - httpResponse = this.getHttpResponse(client, httpRequest); - validateHttpResponse(httpResponse, url); - byte[] responseBytes = readHttpResponse(httpResponse); + + final HttpHost targetHost = getHttpHost(httpRequest); + final HttpContext localContext = getHttpContext(targetHost); + final HttpClientResponseHandler responseHandler = getHttpClientResponseHandler(); + byte[] responseBytes = client.execute(targetHost, httpRequest, localContext, response -> { + validateHttpResponse(response, url); + return responseHandler.handleResponse(response); + }); + publishExternalServiceAccessEvent(url, true); + return responseBytes; } catch (UnknownHostException e) { publishExternalServiceAccessEvent(url, false); @@ -92,11 +105,11 @@ public byte[] post(final String url, final byte[] content) { publishExternalServiceAccessEvent(url, false); throw new NetworkException("Unable to process <" + getServiceType() + "> POST call for service <" + url + ">", url, getServiceType(), e); } finally { - closeQuietly(httpRequest, httpResponse, client); + closeQuietly(httpRequest, client); } } - private void validateHttpResponse(CloseableHttpResponse httpResponse, String url) { + private void validateHttpResponse(ClassicHttpResponse httpResponse, String url) { if (httpResponse.getCode() == HttpStatus.SC_FORBIDDEN) { throw new ServiceAccessDeniedException(url, getServiceType()); } From 7064e5469a4b6c63779d16049bfffdcc69392a7d Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Fri, 19 Jan 2024 13:27:04 +0200 Subject: [PATCH 10/35] DD4J-949 Update constraint files to be compatible with DSS 6.0 --- .../src/main/resources/conf/constraint.xml | 34 ------------------ .../main/resources/conf/test_constraint.xml | 34 ------------------ .../eIDAS_test_constraint_all_fail_level.xml | 33 ----------------- .../eIDAS_test_constraint_all_warn_level.xml | 33 ----------------- .../eIDAS_test_constraint_version_fail.xml | 33 ----------------- ...eIDAS_test_constraint_well_signed_fail.xml | 33 ----------------- .../constraints/moved_constraint.xml | 35 ------------------- 7 files changed, 235 deletions(-) diff --git a/digidoc4j/src/main/resources/conf/constraint.xml b/digidoc4j/src/main/resources/conf/constraint.xml index 935dad36a..7e84e1381 100644 --- a/digidoc4j/src/main/resources/conf/constraint.xml +++ b/digidoc4j/src/main/resources/conf/constraint.xml @@ -147,16 +147,6 @@ - - - - - - - - - - @@ -217,19 +207,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -339,17 +316,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/main/resources/conf/test_constraint.xml b/digidoc4j/src/main/resources/conf/test_constraint.xml index 935dad36a..7e84e1381 100644 --- a/digidoc4j/src/main/resources/conf/test_constraint.xml +++ b/digidoc4j/src/main/resources/conf/test_constraint.xml @@ -147,16 +147,6 @@ - - - - - - - - - - @@ -217,19 +207,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -339,17 +316,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_fail_level.xml b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_fail_level.xml index f820a75a7..8ccd563e8 100644 --- a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_fail_level.xml +++ b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_fail_level.xml @@ -15,15 +15,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -150,19 +141,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -261,17 +239,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_warn_level.xml b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_warn_level.xml index cb89627b0..039b5486c 100644 --- a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_warn_level.xml +++ b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_all_warn_level.xml @@ -15,15 +15,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -150,19 +141,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -261,17 +239,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_version_fail.xml b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_version_fail.xml index ce3b2a9e5..d0b3dc380 100644 --- a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_version_fail.xml +++ b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_version_fail.xml @@ -15,15 +15,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -150,19 +141,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -261,17 +239,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_well_signed_fail.xml b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_well_signed_fail.xml index 6b1d29bc6..4e436ecab 100644 --- a/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_well_signed_fail.xml +++ b/digidoc4j/src/test/resources/testFiles/constraints/eIDAS_test_constraint_well_signed_fail.xml @@ -15,15 +15,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -150,19 +141,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -261,17 +239,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - diff --git a/digidoc4j/src/test/resources/testFiles/constraints/moved_constraint.xml b/digidoc4j/src/test/resources/testFiles/constraints/moved_constraint.xml index 2e9a4c379..e4ec1bc22 100644 --- a/digidoc4j/src/test/resources/testFiles/constraints/moved_constraint.xml +++ b/digidoc4j/src/test/resources/testFiles/constraints/moved_constraint.xml @@ -15,15 +15,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -143,26 +134,12 @@ - - - http://uri.etsi.org/TrstSvc/Svctype/TSA - http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-QC - http://uri.etsi.org/TrstSvc/Svctype/TSA/TSS-AdESQCandQES - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/recognisedatnationallevel - @@ -261,17 +238,6 @@ - - http://uri.etsi.org/TrstSvc/Svctype/CA/QC - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP - http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - - - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation - http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted - @@ -371,6 +337,5 @@ - From f64f0f590dcff6a35f8848fb1b985073c1220d11 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 23 Jan 2024 09:51:43 +0200 Subject: [PATCH 11/35] DD4J-981 Restore support for non-standard mime-types --- .../src/main/java/org/digidoc4j/DataFile.java | 3 +- .../org/digidoc4j/utils/MimeTypeUtil.java | 84 ++++++++++++++++++- .../org/digidoc4j/utils/MimeTypeUtilTest.java | 60 +++++++++++++ 3 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/utils/MimeTypeUtilTest.java diff --git a/digidoc4j/src/main/java/org/digidoc4j/DataFile.java b/digidoc4j/src/main/java/org/digidoc4j/DataFile.java index d2d591fee..62f1e8c59 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/DataFile.java +++ b/digidoc4j/src/main/java/org/digidoc4j/DataFile.java @@ -23,6 +23,7 @@ import org.digidoc4j.exceptions.InvalidDataFileException; import org.digidoc4j.exceptions.TechnicalException; import org.digidoc4j.impl.StreamDocument; +import org.digidoc4j.utils.MimeTypeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -99,7 +100,7 @@ public DataFile() { protected MimeType getMimeType(String mimeType) { try { - MimeType mimeTypeCode = MimeType.fromMimeTypeString(mimeType); + MimeType mimeTypeCode = MimeTypeUtil.fromMimeTypeString(mimeType); logger.debug("Mime type: {}", mimeTypeCode); return mimeTypeCode; } catch (DSSException e) { diff --git a/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java b/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java index cba5fab63..3831f8680 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java +++ b/digidoc4j/src/main/java/org/digidoc4j/utils/MimeTypeUtil.java @@ -1,9 +1,23 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.utils; import eu.europa.esig.dss.enumerations.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Objects; +import java.util.ServiceLoader; + /** * Created by Janar Rahumeel (CGI Estonia) */ @@ -36,7 +50,75 @@ public static MimeType mimeTypeOf(String mimeType) { log.warn("Incorrect Mime-Type <{}> detected, fixing ...", mimeType); mimeType = mimeType.replace("\\", "/"); } - return MimeType.fromMimeTypeString(mimeType); + return fromMimeTypeString(mimeType); + } + + /** + * Returns the first representation of the {@code MimeType} corresponding to the given mime-type string, + * or a custom {@code MimeType} object with the specified mime-type string if no existing representation + * of the {@code MimeType} is found. + * Use this method when support for custom mime-types is needed. + * In case fallback to {@link eu.europa.esig.dss.enumerations.MimeTypeEnum#BINARY} is preferred for non-standard + * mime-types, use {@link MimeType#fromMimeTypeString(String)}. + * + * @param mimeTypeString is a string identifier composed of two parts: a "type" and a "subtype" + * @return the extrapolated mime-type from the {@code String} + * + * @see MimeType#fromMimeTypeString(String) + */ + public static MimeType fromMimeTypeString(final String mimeTypeString) { + Objects.requireNonNull(mimeTypeString, "The mimeTypeString cannot be null!"); + + for (MimeTypeLoader mimeTypeLoader : ServiceLoader.load(MimeTypeLoader.class)) { + MimeType mimeType = mimeTypeLoader.fromMimeTypeString(mimeTypeString); + if (mimeType != null) { + return mimeType; + } + } + + return new CustomMimeType(mimeTypeString); + } + + static final class CustomMimeType implements MimeType { + + private final String mimeTypeString; + + CustomMimeType(final String mimeTypeString) { + this.mimeTypeString = mimeTypeString; + } + + @Override + public String getMimeTypeString() { + return mimeTypeString; + } + + @Override + public String getExtension() { + return null; + } + + @Override + public int hashCode() { + return mimeTypeString.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj instanceof CustomMimeType) { + CustomMimeType other = (CustomMimeType) obj; + return mimeTypeString.equals(other.mimeTypeString); + } else { + return false; + } + } + + @Override + public String toString() { + return "MimeType [mimeTypeString=" + mimeTypeString + "]"; + } + } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/utils/MimeTypeUtilTest.java b/digidoc4j/src/test/java/org/digidoc4j/utils/MimeTypeUtilTest.java new file mode 100644 index 000000000..a19151a6b --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/utils/MimeTypeUtilTest.java @@ -0,0 +1,60 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.utils; + +import eu.europa.esig.dss.enumerations.MimeType; +import eu.europa.esig.dss.enumerations.MimeTypeEnum; +import org.digidoc4j.AbstractTest; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.junit.Assert.assertThrows; + +public class MimeTypeUtilTest extends AbstractTest { + + @Test + public void fromMimeTypeString_WhenInputIsNull_ThrowsException() { + NullPointerException caughtException = assertThrows( + NullPointerException.class, + () -> MimeTypeUtil.fromMimeTypeString(null) + ); + + assertThat( + caughtException.getMessage(), + equalTo("The mimeTypeString cannot be null!") + ); + } + + @Test + public void fromMimeTypeString_WhenInputCorrespondsToExistingMimeTypeEnumValue_ReturnsCorrespondingMimeTypeObject() { + String mimeTypeString = MimeTypeEnum.TEXT.getMimeTypeString(); + + MimeType result = MimeTypeUtil.fromMimeTypeString(mimeTypeString); + + assertThat(result, sameInstance(MimeTypeEnum.TEXT)); + } + + @Test + public void fromMimeTypeString_WhenInputCorrespondsToNoMimeTypeEnumValue_ReturnsCustomMimeTypeObjectWithSpecifiedMimeTypeString() { + String mimeTypeString = "foo/bar"; + + MimeType result = MimeTypeUtil.fromMimeTypeString(mimeTypeString); + + assertThat(result, instanceOf(MimeTypeUtil.CustomMimeType.class)); + assertThat(result.getMimeTypeString(), equalTo(mimeTypeString)); + assertThat(result.getExtension(), nullValue()); + } + +} From 055831e9d4eda4c9a26aa87804ac98f778be7969 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Wed, 24 Jan 2024 09:42:20 +0200 Subject: [PATCH 12/35] DD4J-949 Fix unit test problems caused by DSS update --- .../tsl/DefaultTSLRefreshCallbackTest.java | 5 +- .../digidoc4j/impl/bdoc/ValidationTest.java | 87 ++++++++----------- .../bdoc/report/ValidationReportTest.java | 7 ++ .../impl/pades/PadesValidationTest.java | 2 +- .../java/org/digidoc4j/test/TestAssert.java | 32 +++++-- 5 files changed, 72 insertions(+), 61 deletions(-) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/DefaultTSLRefreshCallbackTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/DefaultTSLRefreshCallbackTest.java index 72ea03def..b57d2dace 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/DefaultTSLRefreshCallbackTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/asic/tsl/DefaultTSLRefreshCallbackTest.java @@ -74,7 +74,8 @@ public void testSummaryWithEmptyLOTLInfos() { } private void testSummaryWithNoLOTLInfos(List lotlInfos) { - TLValidationJobSummary summary = new TLValidationJobSummary(lotlInfos, null); + TLValidationJobSummary summary = Mockito.mock(TLValidationJobSummary.class); + Mockito.doReturn(lotlInfos).when(summary).getLOTLInfos(); TslRefreshException caughtException = Assert.assertThrows( TslRefreshException.class, @@ -82,6 +83,8 @@ private void testSummaryWithNoLOTLInfos(List lotlInfos) { ); Assert.assertEquals("No TSL refresh info found!", caughtException.getMessage()); + Mockito.verify(summary).getLOTLInfos(); + Mockito.verifyNoMoreInteractions(summary); Mockito.verifyNoInteractions(configuration); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index ca22e6284..5cce971c5 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -168,8 +168,9 @@ public void signatureFileContainsIncorrectFileName() { .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_signature.asice", PROD_CONFIGURATION); SignatureValidationResult validate = container.validate(); List errors = validate.getErrors(); - Assert.assertEquals(7, errors.size()); - TestAssert.assertContainsError("(Signature ID: S0) - The signature file for signature S0 has an entry for file <0123456789~#%&()=`@{[]}'.txt> with mimetype but the manifest file does not have an entry for this file", errors); + TestAssert.assertContainsExactNumberOfErrorsAndAllExpectedErrorMessages(errors, 7, + "(Signature ID: S0) - The signature file for signature S0 has an entry for file <0123456789~#%&()=`@{[]}'.txt> with mimetype but the manifest file does not have an entry for this file" + ); } @Test @@ -244,15 +245,12 @@ public void manifestFileContainsIncorrectFileName() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_manifest.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); SignatureValidationResult validate = container.validate(); - Assert.assertEquals(2, validate.getErrors().size()); - Assert.assertEquals( - "(Signature ID: S0) - Manifest file has an entry for file with mimetype but " - + "the signature file for signature S0 does not have an entry for this file", - validate.getErrors().get(0).toString()); - Assert.assertEquals( - "(Signature ID: S0) - The signature file for signature S0 has an entry for file " - + "with mimetype but the manifest file does not have an entry for this file", - validate.getErrors().get(1).toString()); + TestAssert.assertContainsExactSetOfErrors(validate.getErrors(), + "(Signature ID: S0) - Manifest file has an entry for file with mimetype but " + + "the signature file for signature S0 does not have an entry for this file", + "(Signature ID: S0) - The signature file for signature S0 has an entry for file " + + "with mimetype but the manifest file does not have an entry for this file" + ); } @Test @@ -274,10 +272,9 @@ public void revocationAndTimeStampDifferenceTooLarge() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/revocation_timestamp_delta_26h.asice", PROD_CONFIGURATION); SignatureValidationResult validate = container.validate(); - Assert.assertEquals(1, validate.getErrors().size()); - Assert.assertEquals( - "(Signature ID: S0) - The difference between the OCSP response time and the signature timestamp is too large", - validate.getErrors().get(0).toString()); + TestAssert.assertContainsExactSetOfErrors(validate.getErrors(), + "(Signature ID: S0) - The difference between the OCSP response time and the signature timestamp is too large" + ); } @Test @@ -285,18 +282,13 @@ public void revocationAndTimeStampDifferenceNotTooLarge() { Configuration configuration = new Configuration(Configuration.Mode.PROD); int delta27Hours = 27 * 60; configuration.setRevocationAndTimestampDeltaInMinutes(delta27Hours); - SignatureValidationResult result = ContainerOpener + ContainerValidationResult result = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/revocation_timestamp_delta_26h.asice", configuration) .validate(); - Assert.assertEquals(0, result.getErrors().size()); - Assert.assertEquals(2, result.getWarnings().size()); - TestAssert.assertContainsError( + TestAssert.assertContainerIsValid(result); + TestAssert.assertContainsExactSetOfErrors(result.getWarnings(), "The difference between the OCSP response time and the signature timestamp is in allowable range", - result.getWarnings() - ); - TestAssert.assertContainsError( - "The authority info access is not present!", - result.getWarnings() + "The authority info access is not present!" ); } @@ -304,12 +296,11 @@ public void revocationAndTimeStampDifferenceNotTooLarge() { public void signatureFileAndManifestFileContainDifferentMimeTypeForFile() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/mimetype_mismatch.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); - SignatureValidationResult validate = container.validate(); - Assert.assertEquals(1, validate.getErrors().size()); - Assert.assertEquals( - "(Signature ID: S0) - Manifest file has an entry for file with mimetype " - + " but the signature file for signature S0 indicates the mimetype is ", - validate.getErrors().get(0).toString()); + ContainerValidationResult result = container.validate(); + TestAssert.assertContainsExactSetOfErrors(result.getErrors(), + "(Signature ID: S0) - Manifest file has an entry for file with mimetype " + + " but the signature file for signature S0 indicates the mimetype is " + ); } @Test(expected = DuplicateDataFileException.class) @@ -348,11 +339,9 @@ public void containerHasFileWhichIsNotInManifestAndNotInSignatureFile() { "src/test/resources/prodFiles/invalid-containers/extra_file_in_container.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); SignatureValidationResult result = container.validate(); - List errors = result.getErrors(); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals( - "Container contains a file named which is not found in the signature file", - errors.get(0).getMessage()); + TestAssert.assertContainsExactSetOfErrors(result.getErrors(), + "Container contains a file named which is not found in the signature file" + ); } @Test @@ -392,7 +381,7 @@ public void invalidNoncePolicyOid() { List errors = result.getErrors(); TestAssert.assertContainsExactSetOfErrors(errors, "Wrong policy identifier: 1.3.6.1.4.1.10015.1000.3.4.3", - "The certificate is not related to a granted status!", + "The certificate is not related to a qualified certificate issuing trust service with valid status!", "The current time is not in the validity range of the signer's certificate!", "The certificate validation is not conclusive!", "The best-signature-time is not before the expiration date of the signing certificate!", @@ -467,7 +456,7 @@ public void nonceIncorrectContent() { TestAssert.assertContainsExactSetOfErrors(result.getErrors(), "OCSP nonce is invalid", "Wrong policy identifier: 1.3.6.1.4.1.10015.1000.2.10.10", - "The certificate is not related to a granted status!", + "The certificate is not related to a qualified certificate issuing trust service with valid status!", "The signature policy is not available!", "The reference data object has not been found!", "The signature file for signature S0 has an entry for file with mimetype " @@ -669,7 +658,7 @@ public void signaturesWithCrlShouldBeInvalid() throws Exception { PROD_CONFIGURATION) .validate(); Assert.assertFalse(result.isValid()); - Assert.assertTrue(result.getErrors().get(0) instanceof UntrustedRevocationSourceException); + TestAssert.assertContainsError(UntrustedRevocationSourceException.class, result.getErrors()); } @Test @@ -682,12 +671,13 @@ public void bDoc_withoutOcspResponse_shouldBeInvalid() throws Exception { @Test public void bDoc_invalidOcspResponse() { - try { - this.openContainerByConfiguration(Paths.get("src/test/resources/prodFiles/invalid-containers/bdoc21-vigane-ocsp.bdoc"), PROD_CONFIGURATION); - Assert.fail("Should not be able to successfully open container!"); - } catch (DSSException exception) { - Assert.assertEquals("Cannot create the token reference. The element with local name [EncapsulatedOCSPValue] must contain an encapsulated base64 token value!", exception.getMessage()); - } + Container container = openContainerByConfiguration(Paths.get("src/test/resources/prodFiles/invalid-containers/bdoc21-vigane-ocsp.bdoc"), PROD_CONFIGURATION); + ContainerValidationResult result = container.validate(); + TestAssert.assertContainsExactSetOfErrors(result.getErrors(), + "The certificate validation is not conclusive!", + "No revocation data found for the certificate!", + "The certificate is not related to a qualified certificate issuing trust service with valid status!" + ); } @Test @@ -758,9 +748,7 @@ public void mixTSLCertAndTSLOnlineSources_SignatureTypeLT_valid() throws Excepti Container container = this.createNonEmptyContainerByConfiguration(); this.createSignatureBy(container, SignatureProfile.LT, new PKCS12SignatureToken("src/test/resources/testFiles/p12/user_one.p12", "user_one".toCharArray())); - SignatureValidationResult result = container.validate(); - Assert.assertTrue(result.isValid()); - Assert.assertEquals(0, result.getErrors().size()); + TestAssert.assertContainerIsValid(container); } @Test @@ -812,7 +800,7 @@ public void validateBDocTs_Invalid() throws Exception { "The certificate chain for time-stamp is not trusted, it does not contain a trust anchor.", "Signature has an invalid timestamp", "The certificate validation is not conclusive!", - "The certificate is not related to a granted status!", + "The certificate is not related to a qualified certificate issuing trust service with valid status!", "No revocation data found for the certificate!", "The time-stamp message imprint is not intact!", "Unable to build a certificate chain up to a trusted list!", @@ -940,8 +928,7 @@ public void container_withExpiredAIAOCSP_LTA_shouldBeInvalid() { TestAssert.assertContainsExactSetOfErrors(validationResult.getErrors(), "The certificate validation is not conclusive!", "No acceptable revocation data for the certificate!", - "The revocation data is not consistent!", - "The current time is not in the validity range of the signer's certificate!" + "The revocation data is not consistent!" ); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java index 755b93b3f..c2fec5c31 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java @@ -19,6 +19,7 @@ import org.digidoc4j.test.TestAssert; import org.digidoc4j.test.util.TestDataBuilderUtil; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; import java.nio.file.Paths; @@ -26,6 +27,7 @@ public class ValidationReportTest extends AbstractTest { @Test + @Ignore("DD4J-967") public void validContainerWithOneSignature() throws Exception { Container container = this.createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/test.txt")); Signature signature = this.createSignatureBy(container, SignatureProfile.LT, pkcs12SignatureToken); @@ -52,6 +54,7 @@ public void validContainerWithOneSignature() throws Exception { } @Test + @Ignore("DD4J-967") public void validContainerWithOneTmSignature() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_TM_SIG); String report = container.validate().getReport(); @@ -68,6 +71,7 @@ public void validContainerWithOneTmSignature() throws Exception { } @Test + @Ignore("DD4J-967") public void containerWithOneBesSignature() throws Exception { Container container = this.createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/test.txt")); this.createSignatureBy(container, SignatureProfile.B_BES, pkcs12SignatureToken); @@ -84,6 +88,7 @@ public void containerWithOneBesSignature() throws Exception { } @Test + @Ignore("DD4J-967") public void containerWithOneEpesSignature() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_B_EPES_SIG); String report = container.validate().getReport(); @@ -99,6 +104,7 @@ public void containerWithOneEpesSignature() throws Exception { } @Test + @Ignore("DD4J-967") public void validContainerWithTwoSignatures() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_TM_AND_TS_SIG); SignatureValidationResult result = container.validate(); @@ -120,6 +126,7 @@ public void validContainerWithTwoSignatures() throws Exception { } @Test + @Ignore("DD4J-967") public void invalidContainerWithOneSignature() throws Exception { Container container = TestDataBuilderUtil.open("src/test/resources/testFiles/invalid-containers/bdoc-tm-ocsp-revoked.bdoc"); SignatureValidationResult result = container.validate(); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java index 676190517..f6a8c478c 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java @@ -76,7 +76,7 @@ public void PadesLTAndPadesB_shouldFail() { "The current time is not in the validity range of the signer's certificate!", "The best-signature-time is not before the expiration date of the signing certificate!", "The past signature validation is not conclusive!", - "The certificate is not related to a granted status!" + "The certificate is not related to a qualified certificate issuing trust service with valid status!" ); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java b/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java index 9e4391eb1..cda96d81a 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java @@ -1,12 +1,12 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.test; @@ -42,6 +42,9 @@ import java.util.List; import java.util.regex.Pattern; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; + /** * Created by Janar Rahumeel (CGI Estonia) */ @@ -130,12 +133,23 @@ public static void assertContainsExactNumberOfErrorsAndAllExpectedErrorMessages( Assert.fail(stringBuilder.toString()); } + public static void assertContainsError(Class expectedErrorType, List errors) { + for (DigiDoc4JException e : errors) { + if (expectedErrorType.isInstance(e)) { + return; + } + } + Assert.fail(String.format("Expected <%s> was not found", expectedErrorType.getSimpleName())); + } + public static void assertSignatureMetadataContainsFileName(Signature signature, String fileName) { Assert.assertNotNull(TestAssert.findSignedFile(signature, fileName)); } public static void assertContainerIsValid(ContainerValidationResult containerValidationResult) { - if (!containerValidationResult.isValid()) { + if (containerValidationResult.isValid()) { + assertThat(containerValidationResult.getErrors(), empty()); + } else { StringBuilder stringBuilder = new StringBuilder("Container is invalid"); for (DigiDoc4JException exception : containerValidationResult.getErrors()) { stringBuilder.append(System.lineSeparator()).append('\t').append(exception); From 8e27fa164aafcf42369994654de8116e0c2ce4bd Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Wed, 31 Jan 2024 15:22:49 +0200 Subject: [PATCH 13/35] DD4J-983 Refactor BDOC signature policy SPURI presence check --- .../validation/XadesSignatureValidator.java | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java index 7b9271cc6..c30ee6247 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/validation/XadesSignatureValidator.java @@ -48,6 +48,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; +import org.w3c.dom.Node; import java.util.ArrayList; import java.util.Arrays; @@ -173,14 +174,9 @@ private void addPolicyUriValidationErrors() { if (policy != null && !isSignaturePolicyImpliedElementPresented()) { String policyIdentifier = Helper.getIdentifier(policy.getIdentifier()); if (TmSignaturePolicyType.isTmPolicyOid(policyIdentifier)) { - String policyUrl = policy.getUri(); - if (StringUtils.equals(policyIdentifier, policyUrl)) { - // DD4J-730: Starting from DSS version 5.8, the policy URL defaults to the policy identifier OID if the URL is - // missing in the signature. Since the BDOC standard requires that the URL is always present, this workaround - // is required to identify cases when the URL is missing. - // TODO: review the usefulness and correctness of this workaround as soon as DSS is updated! - policyUrl = null; - } + // SignaturePolicy::getUri might not return the actual signature policy SPURI value, but a value copied from the + // signature policy identifier field. Extract the signature policy SPURI from the signature: + String policyUrl = getSignaturePolicyUri(); if (StringUtils.isBlank(policyUrl)) { this.addValidationError(new WrongPolicyIdentifierException("Error: The URL in signature policy is empty or not available")); } @@ -188,6 +184,18 @@ private void addPolicyUriValidationErrors() { } } + private String getSignaturePolicyUri() { + LOGGER.debug("Extracting policy identifier SPURI"); + final XAdESPath xadesPaths = getDssSignature().getXAdESPaths(); + return Optional + .of(getDssSignature().getSignatureElement()) + .map(signatureElement -> DomUtils.getElement(signatureElement, xadesPaths.getSignaturePolicyIdentifierPath())) + .map(policyIdentifier -> DomUtils.getElement(policyIdentifier, xadesPaths.getCurrentSignaturePolicySPURI())) + .map(Node::getTextContent) + .map(StringUtils::trim) + .orElse(null); + } + private void addPolicyIdentifierQualifierValidationErrors() { LOGGER.debug("Extracting policy identifier qualifier validation errors"); XAdESPath xAdESPaths = getDssSignature().getXAdESPaths(); From 07edb7cee8e529b9d70eb50196a15fa08752a53b Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 1 Feb 2024 17:52:17 +0200 Subject: [PATCH 14/35] DD4J-985 Improve the behaviour of manually adding certificates to TSL --- .../asic/tsl/TSLCertificateSourceImpl.java | 76 ++++++++++++------- 1 file changed, 48 insertions(+), 28 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java index 624c34014..034f83588 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/tsl/TSLCertificateSourceImpl.java @@ -10,7 +10,9 @@ package org.digidoc4j.impl.asic.tsl; +import eu.europa.esig.dss.enumerations.AdditionalServiceInformation; import eu.europa.esig.dss.enumerations.KeyUsageBit; +import eu.europa.esig.dss.enumerations.ServiceQualification; import eu.europa.esig.dss.model.x509.CertificateToken; import eu.europa.esig.dss.spi.tsl.Condition; import eu.europa.esig.dss.spi.tsl.ConditionForQualifiers; @@ -25,6 +27,8 @@ import eu.europa.esig.dss.tsl.dto.ParsingCacheDTO; import eu.europa.esig.dss.tsl.dto.condition.KeyUsageCondition; import eu.europa.esig.dss.validation.process.qualification.EIDASUtils; +import eu.europa.esig.dss.validation.process.qualification.trust.ServiceTypeIdentifier; +import eu.europa.esig.dss.validation.process.qualification.trust.TrustServiceStatus; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; @@ -36,10 +40,8 @@ import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; -import java.util.Arrays; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Optional; @@ -50,7 +52,11 @@ public class TSLCertificateSourceImpl extends TrustedListsCertificateSource implements TSLCertificateSource { public static final String OID_TIMESTAMPING = "1.3.6.1.5.5.7.3.8"; - public static final String FOR_ESIGNATURES = "http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/ForeSignatures"; + /** + * @deprecated Deprecated for removal. Use {@link AdditionalServiceInformation#FOR_ESIGNATURES} instead. + */ + @Deprecated + public static final String FOR_ESIGNATURES = AdditionalServiceInformation.FOR_ESIGNATURES.getUri(); private static final String CUSTOM_LOTL_URL = "user_defined_LOTL"; private static final String CUSTOM_TL_URL = "user_defined_TL"; @@ -68,7 +74,9 @@ public TSLCertificateSourceImpl() { * http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC - if certificate contains "OCSPSigning" extended key usage
* http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST - if certificate contains "timeStamping" extended key usage * http://uri.etsi.org/TrstSvc/Svctype/CA/QC - otherwise
- * Qualifier will be http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/QCWithSSCD with nonRepudiation
+ * Qualifier will be:
+ * Certificate's NotBefore pre Eidas -> http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/QCWithSSCD with nonRepudiation
+ * Certificate's NotBefore post Eidas -> http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/QCWithQSCD with nonRepudiation
* ServiceStatus will be:
* Certificate's NotBefore pre Eidas -> http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision
* Certificate's NotBefore post Eidas -> http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted
@@ -80,23 +88,27 @@ public void addTSLCertificate(X509Certificate certificate) { TrustServiceProviderBuilder trustServiceProviderBuilder = new TrustServiceProviderBuilder(); trustServiceProviderBuilder.setTerritory("EU"); - trustServiceProviderBuilder.setNames(new HashMap>() {{ - put("EN", Arrays.asList(getCN(certificate))); - }}); + trustServiceProviderBuilder.setNames(Collections.singletonMap( + "EN", Collections.singletonList(getCN(certificate)) + )); - TrustServiceStatusAndInformationExtensions.TrustServiceStatusAndInformationExtensionsBuilder extensionsBuilder = new TrustServiceStatusAndInformationExtensions. - TrustServiceStatusAndInformationExtensionsBuilder(); - extensionsBuilder.setNames(new HashMap>() {{ - put("EN", Arrays.asList(getCN(certificate))); - }}); + TrustServiceStatusAndInformationExtensions.TrustServiceStatusAndInformationExtensionsBuilder extensionsBuilder = + new TrustServiceStatusAndInformationExtensions.TrustServiceStatusAndInformationExtensionsBuilder(); + extensionsBuilder.setNames(Collections.singletonMap( + "EN", Collections.singletonList(getCN(certificate)) + )); extensionsBuilder.setType(getServiceType(certificate)); - extensionsBuilder.setStatus(getStatus(certificate.getNotBefore())); + extensionsBuilder.setStatus(getServiceStatus(certificate.getNotBefore())); Condition condition = new KeyUsageCondition(KeyUsageBit.NON_REPUDIATION, true); - ConditionForQualifiers conditionForQualifiers = new ConditionForQualifiers(condition, Arrays.asList("http://uri.etsi.org/TrstSvc/TrustedList/SvcInfoExt/QCWithSSCD")); - extensionsBuilder.setConditionsForQualifiers(Arrays.asList(conditionForQualifiers)); - extensionsBuilder.setAdditionalServiceInfoUris(Collections.singletonList(FOR_ESIGNATURES)); + ConditionForQualifiers conditionForQualifiers = new ConditionForQualifiers(condition, Collections.singletonList( + getServiceQualification(certificate.getNotBefore()) + )); + extensionsBuilder.setConditionsForQualifiers(Collections.singletonList(conditionForQualifiers)); + extensionsBuilder.setAdditionalServiceInfoUris(Collections.singletonList( + AdditionalServiceInformation.FOR_ESIGNATURES.getUri() + )); extensionsBuilder.setStartDate(certificate.getNotBefore()); extensionsBuilder.setEndDate(null); @@ -107,7 +119,7 @@ public void addTSLCertificate(X509Certificate certificate) { TrustProperties trustProperties = new TrustProperties(getFirstSuitableTLInfo(), trustServiceProviderBuilder.build(), statusHistoryList); - addCertificate(new CertificateToken(certificate), Arrays.asList(trustProperties)); + addCertificate(new CertificateToken(certificate), Collections.singletonList(trustProperties)); } /** @@ -124,7 +136,7 @@ public void invalidateCache() { @Override public TLValidationJobSummary getSummary() { if (super.getSummary() == null) { - super.setSummary(new TLValidationJobSummary(Arrays.asList(createUserDefinedLOTL()), null)); + super.setSummary(new TLValidationJobSummary(Collections.singletonList(createUserDefinedLOTL()), null)); } return super.getSummary(); } @@ -145,43 +157,51 @@ private TLInfo getFirstSuitableTLInfo() { return this.getSummary().getLOTLInfos().get(0).getTLInfos().get(0); } - private LOTLInfo createUserDefinedLOTL() { + private static LOTLInfo createUserDefinedLOTL() { ParsingCacheDTO parsingInfoRecord = new ParsingCacheDTO(); parsingInfoRecord.setVersion(5); TLInfo tlInfo = new TLInfo(null, parsingInfoRecord, null, CUSTOM_TL_URL); LOTLInfo lotlInfo = new LOTLInfo(null, parsingInfoRecord, null, CUSTOM_LOTL_URL); - lotlInfo.setTlInfos(Arrays.asList(tlInfo)); + lotlInfo.setTlInfos(Collections.singletonList(tlInfo)); return lotlInfo; } - private String getCN(X509Certificate certificate) { + private static String getCN(X509Certificate certificate) { X500Name x500name = new X500Name(certificate.getSubjectX500Principal().getName()); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; return IETFUtils.valueToString(cn.getFirst().getValue()); } - private String getServiceType(X509Certificate certificate) { + private static String getServiceType(X509Certificate certificate) { try { List extendedKeyUsage = certificate.getExtendedKeyUsage(); if (extendedKeyUsage != null && certificate.getBasicConstraints() == -1) { if (extendedKeyUsage.contains(SKOnlineOCSPSource.OID_OCSP_SIGNING)) { - return "http://uri.etsi.org/TrstSvc/Svctype/Certstatus/OCSP/QC"; + return ServiceTypeIdentifier.OCSP_QC.getUri(); } if (extendedKeyUsage.contains(OID_TIMESTAMPING)) { - return "http://uri.etsi.org/TrstSvc/Svctype/TSA/QTST"; + return ServiceTypeIdentifier.TSA_QTST.getUri(); } } } catch (CertificateParsingException e) { logger.warn("Error decoding extended key usage from certificate <{}>", certificate.getSubjectDN().getName()); } - return "http://uri.etsi.org/TrstSvc/Svctype/CA/QC"; + return ServiceTypeIdentifier.CA_QC.getUri(); + } + + private static String getServiceStatus(Date startDate) { + if (EIDASUtils.isPostEIDAS(startDate)) { + return TrustServiceStatus.GRANTED.getUri(); + } else { + return TrustServiceStatus.UNDER_SUPERVISION.getUri(); + } } - private String getStatus(Date startDate) { + private static String getServiceQualification(Date startDate) { if (EIDASUtils.isPostEIDAS(startDate)) { - return "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/granted"; + return ServiceQualification.QC_WITH_QSCD.getUri(); } else { - return "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision"; + return ServiceQualification.QC_WITH_SSCD.getUri(); } } From 33b1b6acd624e3e06d350c091df900f1ea3a8670 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 8 Feb 2024 12:16:04 +0200 Subject: [PATCH 15/35] DD4J-986 Temporarily disable unit tests that fail in updated DSS because of now withdrawn timestamping service --- .../java/org/digidoc4j/impl/bdoc/ValidationTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index 5cce971c5..5c88ab598 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -163,6 +163,7 @@ public void testExpiredCertSign() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void signatureFileContainsIncorrectFileName() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_signature.asice", PROD_CONFIGURATION); @@ -241,6 +242,7 @@ public void secondSignatureFileContainsIncorrectFileName() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void manifestFileContainsIncorrectFileName() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_manifest.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -267,6 +269,7 @@ public void container_withChangedDataFileName_shouldBeInvalid() throws Exception } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void revocationAndTimeStampDifferenceTooLarge() { Container container = ContainerOpener @@ -278,6 +281,7 @@ public void revocationAndTimeStampDifferenceTooLarge() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void revocationAndTimeStampDifferenceNotTooLarge() { Configuration configuration = new Configuration(Configuration.Mode.PROD); int delta27Hours = 27 * 60; @@ -293,6 +297,7 @@ public void revocationAndTimeStampDifferenceNotTooLarge() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void signatureFileAndManifestFileContainDifferentMimeTypeForFile() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/mimetype_mismatch.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -334,6 +339,7 @@ public void missingMimeTypeFile() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void containerHasFileWhichIsNotInManifestAndNotInSignatureFile() { Container container = ContainerOpener.open( "src/test/resources/prodFiles/invalid-containers/extra_file_in_container.asice", @@ -415,6 +421,7 @@ public void noSignedPropRefTM() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void noSignedPropRefTS() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/REF-03_bdoc21-TS-no-signedpropref.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -438,6 +445,7 @@ public void multipleSignedProperties() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void incorrectSignedPropertiesReference() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/signed_properties_reference_not_found.asice", @@ -518,6 +526,7 @@ public void validBDocRsa2047_whenASN1UnsafeIntegerAllowed() { } @Test + @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void validTSRsa2047_whenASN1UnsafeIntegerAllowed() { PROD_CONFIGURATION.setAllowASN1UnsafeInteger(true); Assert.assertTrue(PROD_CONFIGURATION.isASN1UnsafeIntegerAllowed()); From 3cf49a888b6aea61f40c177eb202115701185cc9 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 12 Feb 2024 11:20:19 +0200 Subject: [PATCH 16/35] DD4J-949 Update version to 5.3.0-SNAPSHOT --- ddoc4j/pom.xml | 4 ++-- digidoc4j/pom.xml | 6 +++--- digidoc4j/src/main/java/org/digidoc4j/Version.java | 2 +- pom.xml | 2 +- publish.sh | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ddoc4j/pom.xml b/ddoc4j/pom.xml index b1a7cf3cb..5b9ee861e 100644 --- a/ddoc4j/pom.xml +++ b/ddoc4j/pom.xml @@ -5,7 +5,7 @@ ddoc4j jar - 5.2.0 + 5.3.0-SNAPSHOT DDoc4J DDoc4J is Java Library for validating DDOC documents. It's not recommended to use it directly but rather through DigiDoc4J's API. @@ -14,7 +14,7 @@ digidoc4j-parent org.digidoc4j - 5.2.0 + 5.3.0-SNAPSHOT diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index adb577178..b32f21b48 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -6,7 +6,7 @@ digidoc4j jar - 5.2.0 + 5.3.0-SNAPSHOT DigiDoc4j DigiDoc4j is a Java library for digitally signing documents and creating digital signature containers @@ -17,7 +17,7 @@ digidoc4j-parent org.digidoc4j - 5.2.0 + 5.3.0-SNAPSHOT @@ -74,7 +74,7 @@ ddoc4j org.digidoc4j - 5.2.0 + 5.3.0-SNAPSHOT diff --git a/digidoc4j/src/main/java/org/digidoc4j/Version.java b/digidoc4j/src/main/java/org/digidoc4j/Version.java index fc4a972ca..01b722c0a 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/Version.java +++ b/digidoc4j/src/main/java/org/digidoc4j/Version.java @@ -11,5 +11,5 @@ package org.digidoc4j; public class Version { - public static final String VERSION = "5.2.0"; + public static final String VERSION = "5.3.0-SNAPSHOT"; } diff --git a/pom.xml b/pom.xml index cb8cd15c4..a931022a8 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.digidoc4j digidoc4j-parent - 5.2.0 + 5.3.0-SNAPSHOT pom DigiDoc4J parent diff --git a/publish.sh b/publish.sh index 2da92e5b1..cce897b7d 100755 --- a/publish.sh +++ b/publish.sh @@ -1,6 +1,6 @@ #!/bin/bash -version="5.2.0" +version="5.3.0-SNAPSHOT" staging_url="https://oss.sonatype.org/service/local/staging/deploy/maven2/" repositoryId="ossrh" From bd37c01e0eed9088bf0f936102fc894c800b85f9 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 13 Feb 2024 11:55:12 +0200 Subject: [PATCH 17/35] DD4J-859 Fix DD4J command line utility by not packaging logback 1.3.X classes into the same JAR --- digidoc4j/pom.xml | 10 +++++++--- pom.xml | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index b32f21b48..5d07f928e 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -513,8 +513,6 @@ - - + @@ -534,6 +532,12 @@ + + + + + + diff --git a/pom.xml b/pom.xml index a931022a8..61746e99f 100644 --- a/pom.xml +++ b/pom.xml @@ -144,7 +144,7 @@ 1.76 1.16.0 - 2.0.11 + 2.0.12 8.3.1 0.8.10 From d2539913bde192c14ecc9445e4a3f46598074aa4 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 15 Feb 2024 13:18:19 +0200 Subject: [PATCH 18/35] DD4J-986 Improve tests in preparation for refactoring XadesValidationReportProcessor --- .../test/java/org/digidoc4j/AiaOcspTest.java | 5 +- .../org/digidoc4j/SignatureBuilderTest.java | 4 +- .../bdoc/EmptyDataFilesBdocContainerTest.java | 14 +- .../digidoc4j/impl/bdoc/UriEncodingTest.java | 6 + .../digidoc4j/impl/bdoc/ValidationTest.java | 31 +- .../EmptyDataFilesAsicEContainerTest.java | 28 +- .../XadesValidationReportProcessorTest.java | 752 ++++++++++++++---- .../org/digidoc4j/main/DigiDoc4JTest.java | 2 +- .../java/org/digidoc4j/test/TestAssert.java | 6 +- .../test/{ => matcher}/ContainsPattern.java | 2 +- .../test/matcher/IsDigiDoc4JException.java | 46 ++ .../matcher/IsSimpleReportXmlMessage.java | 72 ++ .../test/matcher/ThrowableMatcher.java | 59 ++ 13 files changed, 843 insertions(+), 184 deletions(-) rename digidoc4j/src/test/java/org/digidoc4j/test/{ => matcher}/ContainsPattern.java (96%) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsDigiDoc4JException.java create mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsSimpleReportXmlMessage.java create mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/matcher/ThrowableMatcher.java diff --git a/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java b/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java index d6e651994..b3bb17ff4 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java @@ -1,5 +1,6 @@ package org.digidoc4j; +import org.digidoc4j.test.TestAssert; import org.junit.Ignore; import org.junit.Test; @@ -70,7 +71,9 @@ public void signAsiceContainerWithEsteid2018UsingAiaOcsp() { .withConfiguration(configuration) .build(); this.createSignatureBy(container, pkcs12Esteid2018SignatureToken); - assertTrue(container.validate().isValid()); + ContainerValidationResult validationResult = container.validate(); + TestAssert.assertContainerIsValid(validationResult); + assertHasNoWarnings(validationResult); assertEquals("C=EE, O=SK ID Solutions AS, OU=OCSP, CN=DEMO of ESTEID-SK 2018 AIA OCSP RESPONDER 2018", container.getSignatures().get(0).getOCSPCertificate().getSubjectName()); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java index c92f7a012..73b9f1c87 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java @@ -326,7 +326,9 @@ public void signWith2EccCertificate() { assertTrue(signature.validateSignature().isValid()); assertThat(signature.getSignatureMethod(), containsString("ecdsa")); container.addSignature(signature); - assertTrue(container.validate().isValid()); + ContainerValidationResult validationResult = container.validate(); + TestAssert.assertContainerIsValid(validationResult); + assertHasNoWarnings(validationResult); } @Test diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java index 80e990b56..bddd80da2 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/EmptyDataFilesBdocContainerTest.java @@ -46,13 +46,15 @@ public void testValidateSignedContainerWithEmptyDataFiles() { assertTrue(validationResult.isValid()); assertNotNull(validationResult.getWarnings()); - assertEquals(2, validationResult.getWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); assertNotNull(validationResult.getContainerWarnings()); - assertEquals(2, validationResult.getContainerWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getContainerWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getContainerWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getContainerWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); } @Test diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java index 7d5c6bec0..1c231ce58 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/UriEncodingTest.java @@ -73,6 +73,7 @@ public void validateContainer_withSpaceInDataFileNamePercentEncodedInSignature_s ); ContainerValidationResult validationResult = container.validate(); TestAssert.assertContainerIsValid(validationResult); + assertHasNoWarnings(validationResult); } @Test @@ -83,6 +84,7 @@ public void validateContainer_withPlusInDataFileNamePercentEncodedInSignature_sh ); ContainerValidationResult validationResult = container.validate(); TestAssert.assertContainerIsValid(validationResult); + assertHasNoWarnings(validationResult); } @Test @@ -97,6 +99,9 @@ public void validateContainer_withSpaceInDataFileNameEncodedAsPlusInSignature_sh "The current time is not in the validity range of the signer's certificate!", "The certificate validation is not conclusive!" ); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "The signature/seal is an INDETERMINATE AdES digital signature!" + ); } @Test @@ -107,6 +112,7 @@ public void validateContainer_withPlusInDataFileNameNotEncodedInSignature_should ); ContainerValidationResult validationResult = container.validate(); TestAssert.assertContainerIsValid(validationResult); + assertHasNoWarnings(validationResult); } /* diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index 5c88ab598..362fbe168 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -51,6 +51,10 @@ import java.security.cert.X509Certificate; import java.util.List; +import static org.digidoc4j.test.matcher.IsDigiDoc4JException.digiDoc4JExceptionMessageContainsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThrows; public class ValidationTest extends AbstractTest { @@ -124,9 +128,10 @@ public void testValidateBeforeAndAfterContainerChange() { this.createSignatureBy(container, pkcs12SignatureToken); ContainerValidationResult result = container.validate(); - Assert.assertTrue(result.isValid()); + TestAssert.assertContainerIsValid(result); Assert.assertEquals(1, result.getReports().size()); Assert.assertEquals("O’CONNEŽ-ŠUSLIK TESTNUMBER,MARY ÄNN,60001013739", result.getReports().get(0).getSignedBy()); + assertHasNoWarnings(result); this.createSignatureBy(container, pkcs12Esteid2018SignatureToken); result = container.validate(); @@ -135,6 +140,7 @@ public void testValidateBeforeAndAfterContainerChange() { Assert.assertEquals(2, result.getReports().size()); Assert.assertEquals("O’CONNEŽ-ŠUSLIK TESTNUMBER,MARY ÄNN,60001013739", result.getReports().get(0).getSignedBy()); Assert.assertEquals("JÕEORG,JAAK-KRISTJAN,38001085718", result.getReports().get(1).getSignedBy()); + assertHasNoWarnings(result); } @Test(expected = UnsupportedFormatException.class) @@ -644,8 +650,9 @@ public void asiceLT_noAdditionalCertificatesInSignature_shouldBeValid() { fromExistingFile("src/test/resources/testFiles/valid-containers/NoAdditionalCertificates_LT.asice"). withConfiguration(configuration) .build(); - ContainerValidationResult test = container.validate(); - Assert.assertTrue(test.isValid()); + ContainerValidationResult result = container.validate(); + TestAssert.assertContainerIsValid(result); + assertHasNoWarnings(result); } @Test @@ -869,9 +876,10 @@ public void prodContainerWithSignatureWarningOfTrustedCertificateNotMatchingWith withConfiguration(PROD_CONFIGURATION).build(); ContainerValidationResult validationResult = container.validate(); TestAssert.assertContainerIsValid(validationResult); - Assert.assertTrue(validationResult.getErrors().isEmpty()); I18nProvider i18nProvider = new I18nProvider(); - Assert.assertFalse(validationResult.getWarnings().contains(i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2))); + assertThat(validationResult.getWarnings(), not(hasItem( + digiDoc4JExceptionMessageContainsString(i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1)) + ))); } @Test @@ -883,10 +891,11 @@ public void testContainerWithSignatureWarningOfTrustedCertificateNotMatchingWith .build(); TestTSLUtil.addCertificateFromFileToTsl(configuration, "src/test/resources/testFiles/certs/ESTEID-SK_2007_prod.pem.crt"); ContainerValidationResult validationResult = container.validate(); - Assert.assertTrue(validationResult.isValid()); - Assert.assertTrue(validationResult.getErrors().isEmpty()); + TestAssert.assertContainerIsValid(validationResult); I18nProvider i18nProvider = new I18nProvider(); - Assert.assertFalse(validationResult.getWarnings().contains(i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2))); + assertThat(validationResult.getWarnings(), not(hasItem( + digiDoc4JExceptionMessageContainsString(i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2)) + ))); } @Test @@ -927,6 +936,9 @@ public void container_withExpiredAIAOCSP_LT_shouldBeInvalid() { "No acceptable revocation data for the certificate!", "The revocation data is not consistent!" ); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "The signature/seal is an INDETERMINATE AdES digital signature!" + ); } @Test @@ -939,6 +951,9 @@ public void container_withExpiredAIAOCSP_LTA_shouldBeInvalid() { "No acceptable revocation data for the certificate!", "The revocation data is not consistent!" ); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "The signature/seal is an INDETERMINATE AdES digital signature!" + ); } @Test diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java index 7d7cd5089..67ab3d6dd 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/EmptyDataFilesAsicEContainerTest.java @@ -44,13 +44,15 @@ public void testValidateUnsignedContainerWithEmptyDataFiles() { Assert.assertTrue(validationResult.isValid()); Assert.assertNotNull(validationResult.getWarnings()); - Assert.assertEquals(2, validationResult.getWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); Assert.assertNotNull(validationResult.getContainerWarnings()); - Assert.assertEquals(2, validationResult.getContainerWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getContainerWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getContainerWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getContainerWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); } @Test @@ -61,13 +63,15 @@ public void testValidateSignedContainerWithEmptyDataFiles() { Assert.assertTrue(validationResult.isValid()); Assert.assertNotNull(validationResult.getWarnings()); - Assert.assertEquals(2, validationResult.getWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); Assert.assertNotNull(validationResult.getContainerWarnings()); - Assert.assertEquals(2, validationResult.getContainerWarnings().size()); - TestAssert.assertContainsError("Data file 'empty-file-2.txt' is empty", validationResult.getContainerWarnings()); - TestAssert.assertContainsError("Data file 'empty-file-4.txt' is empty", validationResult.getContainerWarnings()); + TestAssert.assertContainsExactSetOfErrors(validationResult.getContainerWarnings(), + "Data file 'empty-file-2.txt' is empty", + "Data file 'empty-file-4.txt' is empty" + ); } @Test diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java index 5463c9cba..26f988d7c 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java @@ -21,166 +21,612 @@ import eu.europa.esig.dss.simplereport.jaxb.XmlToken; import eu.europa.esig.dss.validation.reports.Reports; import org.digidoc4j.impl.asic.xades.XadesValidationReportProcessor; +import org.digidoc4j.test.matcher.IsSimpleReportXmlMessage; +import org.hamcrest.Matcher; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.when; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInRelativeOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.doReturn; public class XadesValidationReportProcessorTest { - private static final I18nProvider i18nProvider = new I18nProvider(); - - @Test - public void organizationNameMissingWarningRemoved() { - XmlSignature signature = mockSignatureWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES), - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) - ); - XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); - - Reports validationReports = Mockito.mock(Reports.class); - when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); - - assertSame(2, signature.getAdESValidationDetails().getWarning().size()); - assertSame(2, signature.getQualificationDetails().getWarning().size()); - XadesValidationReportProcessor.process(validationReports); - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - } - - @Test - public void organizationNameMissingWarningRemovedFromTimestamp() { - XmlTimestamp timestamp = mockTimestampWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES), - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) - ); - XmlSignature signature = mockSignatureWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES) - ); - mockSignatureTimestamps(signature, timestamp); - XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); - - Reports validationReports = Mockito.mock(Reports.class); - when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); - - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - assertSame(2, timestamp.getAdESValidationDetails().getWarning().size()); - assertSame(2, timestamp.getQualificationDetails().getWarning().size()); - XadesValidationReportProcessor.process(validationReports); - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - assertSame(1, timestamp.getAdESValidationDetails().getWarning().size()); - assertSame(1, timestamp.getQualificationDetails().getWarning().size()); - } - - @Test - public void trustedCertificateNotMatchingWithTrustedServiceWarningRemoved() { - XmlSignature signature = mockSignatureWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES), - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) - ); - XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); - - Reports validationReports = Mockito.mock(Reports.class); - when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); - - assertSame(2, signature.getAdESValidationDetails().getWarning().size()); - assertSame(2, signature.getQualificationDetails().getWarning().size()); - XadesValidationReportProcessor.process(validationReports); - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - } - - @Test - public void trustedCertificateNotMatchingWithTrustedServiceWarningRemovedFromTimestamp() { - XmlTimestamp timestamp = mockTimestampWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES), - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) - ); - XmlSignature signature = mockSignatureWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES) - ); - mockSignatureTimestamps(signature, timestamp); - XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); - - Reports validationReports = Mockito.mock(Reports.class); - when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); - - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - assertSame(2, timestamp.getAdESValidationDetails().getWarning().size()); - assertSame(2, timestamp.getQualificationDetails().getWarning().size()); - XadesValidationReportProcessor.process(validationReports); - assertSame(1, signature.getAdESValidationDetails().getWarning().size()); - assertSame(1, signature.getQualificationDetails().getWarning().size()); - assertSame(1, timestamp.getAdESValidationDetails().getWarning().size()); - assertSame(1, timestamp.getQualificationDetails().getWarning().size()); - } - - @Test - public void noWarningRemoved() { - XmlSignature signature = mockSignatureWithWarnings( - i18nProvider.getMessage(MessageTag.QUAL_IS_ADES), - i18nProvider.getMessage(MessageTag.QUAL_CERT_TYPE_AT_CC) - ); - XmlSimpleReport simpleReport = new XmlSimpleReport(); - simpleReport.getSignatureOrTimestampOrEvidenceRecord().add(signature); - - Reports validationReports = Mockito.mock(Reports.class); - when(validationReports.getSimpleReportJaxb()).thenReturn(simpleReport); - - assertSame(2, signature.getAdESValidationDetails().getWarning().size()); - assertSame(2, signature.getQualificationDetails().getWarning().size()); - XadesValidationReportProcessor.process(validationReports); - assertSame(2, signature.getAdESValidationDetails().getWarning().size()); - assertSame(2, signature.getQualificationDetails().getWarning().size()); - } - - private static void mockSignatureTimestamps(XmlSignature signatureMock, XmlTimestamp... timestamps) { - XmlTimestamps timestampsWrapper = Mockito.mock(XmlTimestamps.class); - ArrayList timestampsList = Stream.of(timestamps) - .collect(Collectors.toCollection(ArrayList::new)); - when(timestampsWrapper.getTimestamp()).thenReturn(timestampsList); - when(signatureMock.getTimestamps()).thenReturn(timestampsWrapper); - } - - private static void mockTokenWarnings(XmlToken tokenMock, String... warnings) { - XmlDetails adESDetails = mockDetailsWithWarnings(warnings); - when(tokenMock.getAdESValidationDetails()).thenReturn(adESDetails); - XmlDetails qualificationDetails = mockDetailsWithWarnings(warnings); - when(tokenMock.getQualificationDetails()).thenReturn(qualificationDetails); - } - - private static XmlSignature mockSignatureWithWarnings(String... warnings) { - XmlSignature signature = Mockito.mock(XmlSignature.class); - mockTokenWarnings(signature, warnings); - return signature; - } - - private static XmlTimestamp mockTimestampWithWarnings(String... warnings) { - XmlTimestamp timestamp = Mockito.mock(XmlTimestamp.class); - mockTokenWarnings(timestamp, warnings); - return timestamp; - } - - private static XmlDetails mockDetailsWithWarnings(String... warnings) { - XmlDetails details = Mockito.mock(XmlDetails.class); - ArrayList warningsList = Stream.of(warnings).map(w -> { - XmlMessage message = Mockito.mock(XmlMessage.class); - when(message.getValue()).thenReturn(w); - return message; - }).collect(Collectors.toCollection(ArrayList::new)); - when(details.getWarning()).thenReturn(warningsList); - return details; + + private static final I18nProvider i18nProvider = new I18nProvider(); + + @Test + public void process_WhenSignatureContainsOrganizationNameMissingWarnings_WarningsRemoved() { + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.BBB_XCV_ISSSC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1 + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_HAS_CONSISTENT_BY_QC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1 + )) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_ISSSC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(2)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CONSISTENT_BY_QC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_ISSSC_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CONSISTENT_BY_QC_ANS) + )); + } + + @Test + public void process_WhenTimestampContainsOrganizationNameMissingWarnings_WarningsRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.ADEST_IBSVPTC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1 + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_HAS_CONSISTENT_BY_QSCD_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1 + )) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b.warnings(MessageTag.BBB_XCV_ISNSSC_ANS)) + .qualificationDetails(b -> b.warnings(MessageTag.QUAL_HAS_VALID_CAQC_ANS)) + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_ISNSSC_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_VALID_CAQC_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IBSVPTC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CONSISTENT_BY_QSCD_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_ISNSSC_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_VALID_CAQC_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IBSVPTC_ANS) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CONSISTENT_BY_QSCD_ANS) + )); + } + + @Test + public void process_WhenSignatureContainsTrustedCertificateNotMatchingTrustedServiceWarnings_WarningsRemoved() { + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.BBB_XCV_IRDC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_HAS_CERT_TYPE_COVERAGE_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + )) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_IRDC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(2)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CERT_TYPE_COVERAGE_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_XCV_IRDC_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_CERT_TYPE_COVERAGE_ANS) + )); + } + + @Test + public void process_WhenTimestampContainsTrustedCertificateNotMatchingTrustedServiceWarnings_WarningsRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.ADEST_IBSVPTADC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_QC_AT_CC_ANS, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + )) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b.warnings(MessageTag.ADEST_IRTPTBST_ANS)) + .qualificationDetails(b -> b.warnings(MessageTag.QUAL_QC_AT_ST_ANS)) + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IRTPTBST_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_QC_AT_ST_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IBSVPTADC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_QC_AT_CC_ANS), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IRTPTBST_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_QC_AT_ST_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_IBSVPTADC_ANS) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_QC_AT_CC_ANS) + )); + } + + @Test + public void process_WhenSignatureNorTimestampContainsNoFilterableWarnings_NoWarningsRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.BBB_ACCEPT_ANS + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_HAS_QTST_ANS + )) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b.warnings( + MessageTag.ADEST_VFDTAOCST_ANS + )) + .qualificationDetails(b -> b.warnings( + MessageTag.QUAL_CERT_TYPE_AT_CC_ANS + )) + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_VFDTAOCST_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_CERT_TYPE_AT_CC_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_ACCEPT_ANS) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_QTST_ANS) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.ADEST_VFDTAOCST_ANS) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_CERT_TYPE_AT_CC_ANS) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.BBB_ACCEPT_ANS) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_QTST_ANS) + )); + } + + @Test + public void process_WhenSignatureAndTimestampContainFilterableWarningsButAsErrorsAndInfo_NoErrorsNorInfoRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .adesValidationDetails(b -> b + .errors( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ).infos( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ) + ) + .qualificationDetails(b -> b + .errors( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ).infos( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ) + ) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b + .errors( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ).infos( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ) + ) + .qualificationDetails(b -> b + .errors( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ).infos( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1, + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2 + ) + ) + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getWarning(), empty()); + assertThat(signature.getAdESValidationDetails().getError(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getAdESValidationDetails().getInfo(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getQualificationDetails().getWarning(), empty()); + assertThat(signature.getQualificationDetails().getError(), hasSize(2)); + assertThat(signature.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getQualificationDetails().getInfo(), hasSize(2)); + assertThat(signature.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), empty()); + assertThat(timestamp.getAdESValidationDetails().getError(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getAdESValidationDetails().getInfo(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), empty()); + assertThat(timestamp.getQualificationDetails().getError(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getQualificationDetails().getInfo(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getWarning(), empty()); + assertThat(signature.getAdESValidationDetails().getError(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getAdESValidationDetails().getInfo(), hasSize(2)); + assertThat(signature.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getQualificationDetails().getWarning(), empty()); + assertThat(signature.getQualificationDetails().getError(), hasSize(2)); + assertThat(signature.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(signature.getQualificationDetails().getInfo(), hasSize(2)); + assertThat(signature.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), empty()); + assertThat(timestamp.getAdESValidationDetails().getError(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getAdESValidationDetails().getInfo(), hasSize(2)); + assertThat(timestamp.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getQualificationDetails().getWarning(), empty()); + assertThat(timestamp.getQualificationDetails().getError(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + assertThat(timestamp.getQualificationDetails().getInfo(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), + messageOf(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) + )); + } + + private static Reports mockReports(XmlSignature... signatures) { + XmlSimpleReport simpleReport = new XmlSimpleReport(); + Arrays.stream(signatures).forEach(simpleReport.getSignatureOrTimestampOrEvidenceRecord()::add); + + Reports validationReports = Mockito.mock(Reports.class); + doReturn(simpleReport).when(validationReports).getSimpleReportJaxb(); + return validationReports; + } + + private static Matcher messageOf(MessageTag messageTag, Object... args) { + XmlMessage xmlMessage = toMessage(messageTag, args); + return IsSimpleReportXmlMessage.messageWithKeyAndValue(xmlMessage.getKey(), xmlMessage.getValue()); + } + + private static XmlMessage toMessage(MessageTag messageTag, Object... args) { + return new MessageBuilder().with(messageTag, args).build(); + } + + private static List toMessages(MessageTag... messageTags) { + return Arrays.stream(messageTags) + .map(XadesValidationReportProcessorTest::toMessage) + .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); + } + + private static class DetailsBuilder { + + private List errors; + private List warnings; + private List infos; + + public DetailsBuilder errors(List errors) { + this.errors = errors; + return this; + } + + public DetailsBuilder errors(XmlMessage... errors) { + return errors(new ArrayList<>(Arrays.asList(errors))); + } + + public DetailsBuilder errors(MessageTag... errors) { + return errors(toMessages(errors)); + } + + public DetailsBuilder warnings(List warnings) { + this.warnings = warnings; + return this; + } + + public DetailsBuilder warnings(XmlMessage... warnings) { + return warnings(new ArrayList<>(Arrays.asList(warnings))); + } + + public DetailsBuilder warnings(MessageTag... warnings) { + return warnings(toMessages(warnings)); + } + + public DetailsBuilder infos(List infos) { + this.infos = infos; + return this; + } + + public DetailsBuilder infos(XmlMessage... infos) { + return infos(new ArrayList<>(Arrays.asList(infos))); + } + + public DetailsBuilder infos(MessageTag... infos) { + return infos(toMessages(infos)); } + public XmlDetails build() { + XmlDetails details = new XmlDetails(); + Optional.ofNullable(errors).ifPresent(details.getError()::addAll); + Optional.ofNullable(warnings).ifPresent(details.getWarning()::addAll); + Optional.ofNullable(infos).ifPresent(details.getInfo()::addAll); + return details; + } + + } + + private static class MessageBuilder { + + private String key; + private String value; + + public MessageBuilder key(String key) { + this.key = key; + return this; + } + + public MessageBuilder key(MessageTag messageTag) { + return key(messageTag.getId()); + } + + public MessageBuilder value(String value) { + this.value = value; + return this; + } + + public MessageBuilder value(MessageTag messageTag, Object... args) { + return value(i18nProvider.getMessage(messageTag, args)); + } + + public MessageBuilder with(MessageTag messageTag, Object... args) { + return key(messageTag).value(messageTag, args); + } + + public XmlMessage build() { + XmlMessage message = new XmlMessage(); + Optional.ofNullable(key).ifPresent(message::setKey); + Optional.ofNullable(value).ifPresent(message::setValue); + return message; + } + + } + + private abstract static class MockTokenBuilder> { + + private final Class tokenType; + private XmlDetails adesValidationDetails; + private XmlDetails qualificationDetails; + + protected MockTokenBuilder(Class tokenType) { + this.tokenType = Objects.requireNonNull(tokenType); + } + + @SuppressWarnings("unchecked") + public B adesValidationDetails(XmlDetails details) { + adesValidationDetails = details; + return (B) this; + } + + public B adesValidationDetails(Consumer builderConsumer) { + DetailsBuilder detailsBuilder = new DetailsBuilder(); + builderConsumer.accept(detailsBuilder); + return adesValidationDetails(detailsBuilder.build()); + } + + @SuppressWarnings("unchecked") + public B qualificationDetails(XmlDetails details) { + qualificationDetails = details; + return (B) this; + } + + public B qualificationDetails(Consumer builderConsumer) { + DetailsBuilder detailsBuilder = new DetailsBuilder(); + builderConsumer.accept(detailsBuilder); + return qualificationDetails(detailsBuilder.build()); + } + + public T build() { + T tokenMock = Mockito.mock(tokenType); + if (adesValidationDetails != null) { + doReturn(adesValidationDetails).when(tokenMock).getAdESValidationDetails(); + } + if (qualificationDetails != null) { + doReturn(qualificationDetails).when(tokenMock).getQualificationDetails(); + } + return tokenMock; + } + + } + + private static class MockSignatureBuilder extends MockTokenBuilder { + + private XmlTimestamps timestamps; + + public MockSignatureBuilder() { + super(XmlSignature.class); + } + + public MockSignatureBuilder timestamps(XmlTimestamps timestamps) { + this.timestamps = timestamps; + return this; + } + + public MockSignatureBuilder timestamps(XmlTimestamp... timestamps) { + XmlTimestamps xmlTimestamps = new XmlTimestamps(); + xmlTimestamps.getTimestamp().addAll(Arrays.asList(timestamps)); + return timestamps(xmlTimestamps); + } + + @Override + public XmlSignature build() { + XmlSignature signatureMock = super.build(); + if (timestamps != null) { + doReturn(timestamps).when(signatureMock).getTimestamps(); + } + return signatureMock; + } + + } + + private static class MockTimestampBuilder extends MockTokenBuilder { + + public MockTimestampBuilder() { + super(XmlTimestamp.class); + } + + } + } diff --git a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java index 3700c3ef2..2cd81ff3f 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java @@ -37,7 +37,7 @@ import java.nio.file.Paths; import static org.digidoc4j.main.DigiDoc4J.isWarning; -import static org.digidoc4j.test.ContainsPattern.containsPattern; +import static org.digidoc4j.test.matcher.ContainsPattern.containsPattern; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java b/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java index cda96d81a..489b3c156 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/TestAssert.java @@ -162,8 +162,12 @@ public static void assertContainerIsValid(Container container) { assertContainerIsValid(container.validate()); } + public static void assertContainerIsInvalid(ContainerValidationResult containerValidationResult) { + Assert.assertFalse("Container is valid", containerValidationResult.isValid()); + } + public static void assertContainerIsInvalid(Container container) { - Assert.assertFalse("Container is valid", container.validate().isValid()); + assertContainerIsInvalid(container.validate()); } public static void assertContainerIsOpened(Container container, Container.DocumentType documentType) { diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/ContainsPattern.java similarity index 96% rename from digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java rename to digidoc4j/src/test/java/org/digidoc4j/test/matcher/ContainsPattern.java index d967aee29..960dcf9b1 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/ContainsPattern.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/ContainsPattern.java @@ -8,7 +8,7 @@ * Version 2.1, February 1999 */ -package org.digidoc4j.test; +package org.digidoc4j.test.matcher; import org.hamcrest.Description; import org.hamcrest.Matcher; diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsDigiDoc4JException.java b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsDigiDoc4JException.java new file mode 100644 index 000000000..c0bc193f9 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsDigiDoc4JException.java @@ -0,0 +1,46 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.test.matcher; + +import org.digidoc4j.exceptions.DigiDoc4JException; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; + +public class IsDigiDoc4JException extends ThrowableMatcher { + + public IsDigiDoc4JException( + Class expectedType, + Matcher messageMatcher, + Matcher causeMatcher + ) { + super(expectedType, messageMatcher, causeMatcher); + } + + public static Matcher digiDoc4JExceptionOfTypeWithMessage( + Class expectedType, + Matcher messageMatcher + ) { + return new IsDigiDoc4JException<>(expectedType, messageMatcher, null); + } + + public static Matcher digiDoc4JExceptionWithMessage(Matcher messageMatcher) { + return digiDoc4JExceptionOfTypeWithMessage(DigiDoc4JException.class, messageMatcher); + } + + public static Matcher digiDoc4JExceptionWithMessage(String message) { + return digiDoc4JExceptionWithMessage(Matchers.equalTo(message)); + } + + public static Matcher digiDoc4JExceptionMessageContainsString(String messageSubstring) { + return digiDoc4JExceptionWithMessage(Matchers.containsString(messageSubstring)); + } + +} diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsSimpleReportXmlMessage.java b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsSimpleReportXmlMessage.java new file mode 100644 index 000000000..dc85f4f56 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/IsSimpleReportXmlMessage.java @@ -0,0 +1,72 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.test.matcher; + +import eu.europa.esig.dss.simplereport.jaxb.XmlMessage; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.Matchers; +import org.hamcrest.TypeSafeDiagnosingMatcher; + +import java.util.Objects; +import java.util.Optional; + +public class IsSimpleReportXmlMessage extends TypeSafeDiagnosingMatcher { + + private static final String TYPE_NAME = XmlMessage.class.getSimpleName(); + + private final Matcher keyMatcher; + private final Matcher valueMatcher; + + public IsSimpleReportXmlMessage(Matcher keyMatcher, Matcher valueMatcher) { + super(XmlMessage.class); + this.keyMatcher = Objects.requireNonNull(keyMatcher); + this.valueMatcher = Objects.requireNonNull(valueMatcher); + } + + @Override + protected boolean matchesSafely(XmlMessage item, Description mismatchDescription) { + boolean result = true; + if (!keyMatcher.matches(item.getKey())) { + mismatchDescription.appendText(TYPE_NAME + " key "); + keyMatcher.describeMismatch(item.getKey(), mismatchDescription); + result = false; + } + if (!valueMatcher.matches(item.getValue())) { + if (result) { + mismatchDescription.appendText(TYPE_NAME + " value "); + } else { + mismatchDescription.appendText(" and value "); + } + valueMatcher.describeMismatch(item.getValue(), mismatchDescription); + result = false; + } + return result; + } + + @Override + public void describeTo(Description description) { + description.appendText(TYPE_NAME + " with key ").appendDescriptionOf(keyMatcher) + .appendText(" and value ").appendDescriptionOf(valueMatcher); + } + + public static Matcher messageWithKeyAndValue(Matcher keyMatcher, Matcher valueMatcher) { + return new IsSimpleReportXmlMessage(keyMatcher, valueMatcher); + } + + public static Matcher messageWithKeyAndValue(String key, String value) { + return messageWithKeyAndValue( + Optional.ofNullable(key).map(Matchers::equalTo).orElseGet(() -> Matchers.nullValue(String.class)), + Optional.ofNullable(value).map(Matchers::equalTo).orElseGet(() -> Matchers.nullValue(String.class)) + ); + } + +} diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/matcher/ThrowableMatcher.java b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/ThrowableMatcher.java new file mode 100644 index 000000000..cd97b9800 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/test/matcher/ThrowableMatcher.java @@ -0,0 +1,59 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.test.matcher; + +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeDiagnosingMatcher; + +import java.util.Objects; + +public abstract class ThrowableMatcher extends TypeSafeDiagnosingMatcher { + + protected final Matcher messageMatcher; + protected final Matcher causeMatcher; + protected final String typeName; + + protected ThrowableMatcher( + Class expectedType, + Matcher messageMatcher, + Matcher causeMatcher + ) { + super(Objects.requireNonNull(expectedType)); + this.messageMatcher = Objects.requireNonNull(messageMatcher); + this.causeMatcher = causeMatcher; + this.typeName = expectedType.getSimpleName(); + } + + @Override + protected boolean matchesSafely(T item, Description mismatchDescription) { + if (!messageMatcher.matches(item.getMessage())) { + mismatchDescription.appendText(typeName + " message "); + messageMatcher.describeMismatch(item, mismatchDescription); + return false; + } + if (causeMatcher != null && !causeMatcher.matches(item.getCause())) { + mismatchDescription.appendText(typeName + " cause "); + causeMatcher.describeMismatch(item, mismatchDescription); + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText(typeName + " with message ").appendDescriptionOf(messageMatcher); + if (causeMatcher != null) { + description.appendText(" and with cause ").appendDescriptionOf(causeMatcher); + } + } + +} From b7b7711c065035593823041dc7e7482e82529437 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 15 Feb 2024 16:28:17 +0200 Subject: [PATCH 19/35] DD4J-986 Refactor XadesValidationReportProcessor for more flexibility --- .../xades/XadesValidationReportProcessor.java | 144 +++++++++++++----- 1 file changed, 107 insertions(+), 37 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java index 880aa59c1..8b3eae2ec 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java @@ -10,77 +10,147 @@ package org.digidoc4j.impl.asic.xades; -import eu.europa.esig.dss.i18n.I18nProvider; import eu.europa.esig.dss.i18n.MessageTag; import eu.europa.esig.dss.simplereport.jaxb.XmlDetails; import eu.europa.esig.dss.simplereport.jaxb.XmlMessage; import eu.europa.esig.dss.simplereport.jaxb.XmlSignature; +import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamp; +import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamps; import eu.europa.esig.dss.simplereport.jaxb.XmlToken; import eu.europa.esig.dss.validation.reports.Reports; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; public class XadesValidationReportProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(XadesValidationReportProcessor.class); - private static final I18nProvider i18nProvider = new I18nProvider(); - private static final List WARNING_MESSAGES_TO_IGNORE = Arrays.asList( - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1), // DD4J - 404 - i18nProvider.getMessage(MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2) // DD4J - 404 - ); + + private static final List WARNING_MESSAGES_TO_IGNORE = Collections.unmodifiableList(Arrays.asList( + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1.getId(), // DD4J-404 + MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2.getId() // DD4J-404 + )); + + private static final List TOKEN_PROCESSORS = Collections.unmodifiableList(Arrays.asList( + /* + * DD4J-404 + * Remove warning messages from DSS reports that are considered false-positive by DDJ4 or uncorrectable + * at the given time. + * Messages are removed from both AdESValidationDetails and QualificationDetails blocks of both signatures + * and their timestamps. + */ + new MessageRemovingSignatureAndTimestampProcessor( + Collections.unmodifiableList(Arrays.asList( + XmlToken::getAdESValidationDetails, + XmlToken::getQualificationDetails + )), + Collections.singletonList(XmlDetails::getWarning), + m -> WARNING_MESSAGES_TO_IGNORE.contains(m.getKey()) + ) + )); public static void process(Reports validationReports) { - removeFalsePositiveWarningsFromValidationReports(validationReports); + processTokensInSimpleReport(validationReports.getSimpleReportJaxb()); } - /** - * DD4J-404 - * Removing warning messages from DSS reports that are considered false-positive by DDJ4 or - * uncorrectable at the given time. - * TODO: Not recommended to add anything new here and should be removed at some point - * - * @param validationReports - */ - private static void removeFalsePositiveWarningsFromValidationReports(Reports validationReports) { - for (XmlToken xmlToken : validationReports.getSimpleReportJaxb().getSignatureOrTimestampOrEvidenceRecord()) { - if (xmlToken instanceof XmlSignature) { - removeFalsePositiveWarningsFromSignatureResult((XmlSignature) xmlToken); + private static void processTokensInSimpleReport(XmlSimpleReport simpleReport) { + for (final XmlToken token : simpleReport.getSignatureOrTimestampOrEvidenceRecord()) { + for (final TokenProcessor tokenProcessor : TOKEN_PROCESSORS) { + tokenProcessor.processToken(token); } } } - private static void removeFalsePositiveWarningsFromSignatureResult(XmlSignature signatureResult) { - removeFalsePositiveWarningsFromToken(signatureResult); - if (signatureResult.getTimestamps() != null && CollectionUtils.isNotEmpty(signatureResult.getTimestamps().getTimestamp())) { - for (XmlTimestamp timestampResult : signatureResult.getTimestamps().getTimestamp()) { - if (timestampResult != null) { - removeFalsePositiveWarningsFromToken(timestampResult); + private static void forEachSignatureTimestamp(XmlSignature signature, Consumer timestampProcessor) { + Optional + .ofNullable(signature.getTimestamps()) + .map(XmlTimestamps::getTimestamp) + .orElseGet(Collections::emptyList) + .forEach(timestampProcessor); + } + + @FunctionalInterface + private interface TokenProcessor { + void processToken(XmlToken token); + } + + private abstract static class MessageRemovingTokenProcessor implements TokenProcessor { + + private final List> detailsExtractors; + private final List>> messageListExtractors; + private final Predicate messageMatcher; + + protected MessageRemovingTokenProcessor( + List> detailsExtractors, + List>> messageListExtractors, + Predicate messageMatcher + ) { + this.detailsExtractors = Objects.requireNonNull(detailsExtractors); + this.messageListExtractors = Objects.requireNonNull(messageListExtractors); + this.messageMatcher = Objects.requireNonNull(messageMatcher); + } + + @Override + public void processToken(final XmlToken token) { + for (final Function detailsExtractor : detailsExtractors) { + final XmlDetails details = detailsExtractor.apply(token); + if (details != null) { + processDetails(details); } } } - } - private static void removeFalsePositiveWarningsFromToken(XmlToken token) { - if (token.getAdESValidationDetails() != null) { - removeFalsePositiveWarningsFromDetails(token.getAdESValidationDetails()); + private void processDetails(final XmlDetails details) { + for (final Function> messageListExtractor : messageListExtractors) { + final List messageList = messageListExtractor.apply(details); + if (CollectionUtils.isNotEmpty(messageList)) { + processMessageList(messageList); + } + } } - if (token.getQualificationDetails() != null) { - removeFalsePositiveWarningsFromDetails(token.getQualificationDetails()); + + private void processMessageList(final List messageList) { + final Iterator messageIterator = messageList.iterator(); + while (messageIterator.hasNext()) { + final XmlMessage message = messageIterator.next(); + if (messageMatcher.test(message)) { + messageIterator.remove(); + LOGGER.debug("Removed false-positive message: \"{}\":\"{}\"", message.getKey(), message.getValue()); + } + } } + } - private static void removeFalsePositiveWarningsFromDetails(XmlDetails details) { - for (XmlMessage warning : new ArrayList<>(details.getWarning())) { - if (WARNING_MESSAGES_TO_IGNORE.contains(warning.getValue())) { - details.getWarning().remove(warning); - LOGGER.debug("Removed false-positive warning message: \"{}\":\"{}\"", warning.getKey(), warning.getValue()); + private static class MessageRemovingSignatureAndTimestampProcessor extends MessageRemovingTokenProcessor { + + public MessageRemovingSignatureAndTimestampProcessor( + List> detailsExtractors, + List>> messageListExtractors, + Predicate messageMatcher + ) { + super(detailsExtractors, messageListExtractors, messageMatcher); + } + + @Override + public void processToken(final XmlToken token) { + if (token instanceof XmlSignature) { + super.processToken(token); + forEachSignatureTimestamp((XmlSignature) token, super::processToken); } } + } + } From a3acbee66dddee63b74e09a4585d6f48ad8054a4 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Fri, 16 Feb 2024 16:16:28 +0200 Subject: [PATCH 20/35] DD4J-986 Remove signature timestamp granted at timestamp POE time validation errors --- .../xades/XadesValidationReportProcessor.java | 37 ++++ .../digidoc4j/impl/bdoc/ValidationTest.java | 9 - .../XadesValidationReportProcessorTest.java | 190 ++++++++++++++++++ 3 files changed, 227 insertions(+), 9 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java index 8b3eae2ec..83cdb3bdd 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/xades/XadesValidationReportProcessor.java @@ -10,6 +10,7 @@ package org.digidoc4j.impl.asic.xades; +import eu.europa.esig.dss.i18n.I18nProvider; import eu.europa.esig.dss.i18n.MessageTag; import eu.europa.esig.dss.simplereport.jaxb.XmlDetails; import eu.europa.esig.dss.simplereport.jaxb.XmlMessage; @@ -20,6 +21,7 @@ import eu.europa.esig.dss.simplereport.jaxb.XmlToken; import eu.europa.esig.dss.validation.reports.Reports; import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,10 +39,12 @@ public class XadesValidationReportProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(XadesValidationReportProcessor.class); + private static final I18nProvider I18N_PROVIDER = new I18nProvider(); private static final List WARNING_MESSAGES_TO_IGNORE = Collections.unmodifiableList(Arrays.asList( MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS1.getId(), // DD4J-404 MessageTag.QUAL_IS_TRUST_CERT_MATCH_SERVICE_ANS2.getId() // DD4J-404 )); + private static final String TST_POE_TIME_MESSAGE = I18N_PROVIDER.getMessage(MessageTag.VT_TST_POE_TIME); // DD4J-986 private static final List TOKEN_PROCESSORS = Collections.unmodifiableList(Arrays.asList( /* @@ -57,6 +61,20 @@ public class XadesValidationReportProcessor { )), Collections.singletonList(XmlDetails::getWarning), m -> WARNING_MESSAGES_TO_IGNORE.contains(m.getKey()) + ), + /* + * DD4J-986 + * Remove timestamping service status at POE time error messages that are considered false-positives in + * Estonian context. + * Messages are removed from the QualificationDetails block of signature timestamps. + * Messages are matched by first matching the message key to "QUAL_HAS_GRANTED_AT_ANS" and then checking + * whether the message value contains the value of "VT_TST_POE_TIME". + */ + new MessageRemovingSignatureTimestampProcessor( + Collections.singletonList(XmlToken::getQualificationDetails), + Collections.singletonList(XmlDetails::getError), + m -> MessageTag.QUAL_HAS_GRANTED_AT_ANS.getId().equals(m.getKey()) + && StringUtils.contains(m.getValue(), TST_POE_TIME_MESSAGE) ) )); @@ -153,4 +171,23 @@ public void processToken(final XmlToken token) { } + private static class MessageRemovingSignatureTimestampProcessor extends MessageRemovingTokenProcessor { + + public MessageRemovingSignatureTimestampProcessor( + List> detailsExtractors, + List>> messageListExtractors, + Predicate messageMatcher + ) { + super(detailsExtractors, messageListExtractors, messageMatcher); + } + + @Override + public void processToken(final XmlToken token) { + if (token instanceof XmlSignature) { + forEachSignatureTimestamp((XmlSignature) token, super::processToken); + } + } + + } + } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java index 362fbe168..a93c71e61 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/ValidationTest.java @@ -169,7 +169,6 @@ public void testExpiredCertSign() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void signatureFileContainsIncorrectFileName() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_signature.asice", PROD_CONFIGURATION); @@ -248,7 +247,6 @@ public void secondSignatureFileContainsIncorrectFileName() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void manifestFileContainsIncorrectFileName() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/filename_mismatch_manifest.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -275,7 +273,6 @@ public void container_withChangedDataFileName_shouldBeInvalid() throws Exception } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void revocationAndTimeStampDifferenceTooLarge() { Container container = ContainerOpener @@ -287,7 +284,6 @@ public void revocationAndTimeStampDifferenceTooLarge() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void revocationAndTimeStampDifferenceNotTooLarge() { Configuration configuration = new Configuration(Configuration.Mode.PROD); int delta27Hours = 27 * 60; @@ -303,7 +299,6 @@ public void revocationAndTimeStampDifferenceNotTooLarge() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void signatureFileAndManifestFileContainDifferentMimeTypeForFile() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/mimetype_mismatch.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -345,7 +340,6 @@ public void missingMimeTypeFile() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void containerHasFileWhichIsNotInManifestAndNotInSignatureFile() { Container container = ContainerOpener.open( "src/test/resources/prodFiles/invalid-containers/extra_file_in_container.asice", @@ -427,7 +421,6 @@ public void noSignedPropRefTM() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void noSignedPropRefTS() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/REF-03_bdoc21-TS-no-signedpropref.asice", PROD_CONFIGURATION_WITH_TEST_POLICY); @@ -451,7 +444,6 @@ public void multipleSignedProperties() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void incorrectSignedPropertiesReference() { Container container = ContainerOpener .open("src/test/resources/prodFiles/invalid-containers/signed_properties_reference_not_found.asice", @@ -532,7 +524,6 @@ public void validBDocRsa2047_whenASN1UnsafeIntegerAllowed() { } @Test - @Ignore("DD4J-986 Now withdrawn timestamping service causes signature error") public void validTSRsa2047_whenASN1UnsafeIntegerAllowed() { PROD_CONFIGURATION.setAllowASN1UnsafeInteger(true); Assert.assertTrue(PROD_CONFIGURATION.isASN1UnsafeIntegerAllowed()); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java index 26f988d7c..98c9b69f8 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/xades/XadesValidationReportProcessorTest.java @@ -20,6 +20,7 @@ import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamps; import eu.europa.esig.dss.simplereport.jaxb.XmlToken; import eu.europa.esig.dss.validation.reports.Reports; +import org.apache.commons.lang3.StringUtils; import org.digidoc4j.impl.asic.xades.XadesValidationReportProcessor; import org.digidoc4j.test.matcher.IsSimpleReportXmlMessage; import org.hamcrest.Matcher; @@ -32,6 +33,8 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInRelativeOrder; @@ -429,6 +432,193 @@ public void process_WhenSignatureAndTimestampContainFilterableWarningsButAsError )); } + @Test + public void process_WhenSignatureTimestampContainsTstPoeTimeStatusErrorInQualificationDetails_ErrorRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .qualificationDetails(b -> b.errors( + toMessage(MessageTag.QUAL_HAS_QTST_ANS), + toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(timestamp.getQualificationDetails().getError(), hasSize(2)); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_QTST_ANS), + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(timestamp.getQualificationDetails().getError(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_QTST_ANS) + )); + } + + @Test + public void process_WhenSignatureTimestampContainsOtherStatusErrorsInQualificationDetails_NoErrorsRemoved() { + List validationTimes = Stream.concat( + Stream.of(MessageTag.values()) + .filter(mt -> StringUtils.startsWith(mt.getId(), "VT_")) + .filter(mt -> !MessageTag.VT_TST_POE_TIME.equals(mt)), + Stream.of("some custom validation time") + ).collect(Collectors.toList()); + XmlTimestamp timestamp = new MockTimestampBuilder() + .qualificationDetails(b -> b.errors( + validationTimes.stream() + .map(vt -> toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, vt)) + .collect(Collectors.toList()) + )) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(timestamp.getQualificationDetails().getError(), hasSize(validationTimes.size())); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + validationTimes.stream() + .map(vt -> messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, vt)) + .collect(Collectors.toList()) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(timestamp.getQualificationDetails().getError(), hasSize(validationTimes.size())); + assertThat(timestamp.getQualificationDetails().getError(), containsInRelativeOrder( + validationTimes.stream() + .map(vt -> messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, vt)) + .collect(Collectors.toList()) + )); + } + + @Test + public void process_WhenSignatureOrTimestampContainsTstPoeTimeStatusErrorInAnywhereElseThanTimestampQualificationDetailsAsError_NothingRemoved() { + XmlTimestamp timestamp = new MockTimestampBuilder() + .adesValidationDetails(b -> b + .errors(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .warnings(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .infos(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + ) + .qualificationDetails(b -> b + .warnings(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .infos(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + ) + .build(); + XmlSignature signature = new MockSignatureBuilder() + .adesValidationDetails(b -> b + .errors(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .warnings(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .infos(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + ) + .qualificationDetails(b -> b + .errors(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .warnings(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + .infos(toMessage(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME)) + ) + .timestamps(timestamp) + .build(); + + Reports validationReports = mockReports(signature); + assertThat(signature.getAdESValidationDetails().getError(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getAdESValidationDetails().getInfo(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getError(), hasSize(1)); + assertThat(signature.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getInfo(), hasSize(1)); + assertThat(signature.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getError(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getInfo(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getQualificationDetails().getError(), empty()); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getQualificationDetails().getInfo(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + + XadesValidationReportProcessor.process(validationReports); + + assertThat(signature.getAdESValidationDetails().getError(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getAdESValidationDetails().getInfo(), hasSize(1)); + assertThat(signature.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getError(), hasSize(1)); + assertThat(signature.getQualificationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(signature.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(signature.getQualificationDetails().getInfo(), hasSize(1)); + assertThat(signature.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getError(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getError(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getAdESValidationDetails().getInfo(), hasSize(1)); + assertThat(timestamp.getAdESValidationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getQualificationDetails().getError(), empty()); + assertThat(timestamp.getQualificationDetails().getWarning(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getWarning(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + assertThat(timestamp.getQualificationDetails().getInfo(), hasSize(1)); + assertThat(timestamp.getQualificationDetails().getInfo(), containsInRelativeOrder( + messageOf(MessageTag.QUAL_HAS_GRANTED_AT_ANS, MessageTag.VT_TST_POE_TIME) + )); + } + private static Reports mockReports(XmlSignature... signatures) { XmlSimpleReport simpleReport = new XmlSimpleReport(); Arrays.stream(signatures).forEach(simpleReport.getSignatureOrTimestampOrEvidenceRecord()::add); From daaad9cdeb998d6f50abbe660796ca0d7f2e0363 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 19 Feb 2024 14:35:04 +0200 Subject: [PATCH 21/35] DD4J-922 Enable 'prefer AIA OCSP' by default --- .../java/org/digidoc4j/Configuration.java | 4 +-- .../test/java/org/digidoc4j/AbstractTest.java | 12 +++++-- .../test/java/org/digidoc4j/AiaOcspTest.java | 22 ++++++++---- .../CertificateValidatorBuilderTest.java | 4 ++- .../java/org/digidoc4j/ConfigurationTest.java | 12 +++---- .../org/digidoc4j/SignatureBuilderTest.java | 2 ++ .../java/org/digidoc4j/SignatureTest.java | 4 ++- .../impl/SKOnlineOCSPSourceTest.java | 35 ++++++++++--------- .../impl/bdoc/BDocSerializationTest.java | 1 + .../bdoc/asic/AsicSignatureFinalizerTest.java | 11 ++++++ .../test/util/TestDataBuilderUtil.java | 32 ++++++++++------- 11 files changed, 93 insertions(+), 46 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/Configuration.java b/digidoc4j/src/main/java/org/digidoc4j/Configuration.java index 5c617690c..9040e6f9f 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/Configuration.java +++ b/digidoc4j/src/main/java/org/digidoc4j/Configuration.java @@ -2167,7 +2167,7 @@ private void initDefaultValues() { this.setDDoc4JParameter("SIGN_OCSP_REQUESTS", "false"); setDDoc4JParameter("ALLOWED_OCSP_RESPONDERS_FOR_TM", StringUtils.join(Constant.Test.DEFAULT_OCSP_RESPONDERS, ",")); this.setConfigurationParameter(ConfigurationParameter.AllowedOcspRespondersForTM, Constant.Test.DEFAULT_OCSP_RESPONDERS); - this.setConfigurationParameter(ConfigurationParameter.preferAiaOcsp, "false"); + this.setConfigurationParameter(ConfigurationParameter.preferAiaOcsp, "true"); this.loadYamlAiaOCSPs(loadYamlFromResource("defaults/demo_aia_ocsp.yaml"), true); } else { this.setConfigurationParameter(ConfigurationParameter.TspSource, Constant.Production.TSP_SOURCE); @@ -2183,7 +2183,7 @@ private void initDefaultValues() { this.setDDoc4JParameter("SIGN_OCSP_REQUESTS", "false"); setDDoc4JParameter("ALLOWED_OCSP_RESPONDERS_FOR_TM", StringUtils.join(Constant.Production.DEFAULT_OCSP_RESPONDERS, ",")); this.setConfigurationParameter(ConfigurationParameter.AllowedOcspRespondersForTM, Constant.Production.DEFAULT_OCSP_RESPONDERS); - this.setConfigurationParameter(ConfigurationParameter.preferAiaOcsp, "false"); + this.setConfigurationParameter(ConfigurationParameter.preferAiaOcsp, "true"); this.loadYamlAiaOCSPs(loadYamlFromResource("defaults/live_aia_ocsp.yaml"), true); } LOGGER.debug("{} configuration: {}", this.mode, this.registry); diff --git a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java index 983b8f936..acc385c23 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AbstractTest.java @@ -414,14 +414,22 @@ protected T createSignatureBy(Container.DocumentType type, SignatureToken si return this.createSignatureBy(type, null, signatureToken, mode); } + protected T createSignatureBy(Container.DocumentType type, SignatureToken signatureToken, Configuration configuration) { + return this.createSignatureBy(type, null, signatureToken, configuration); + } + protected T createSignatureBy(Container.DocumentType type, SignatureProfile signatureProfile, SignatureToken signatureToken) { return this.createSignatureBy(type, signatureProfile, signatureToken, Configuration.Mode.TEST); } - @SuppressWarnings("unchecked") protected T createSignatureBy(Container.DocumentType type, SignatureProfile signatureProfile, SignatureToken signatureToken, Configuration.Mode mode) { + return createSignatureBy(type, signatureProfile, signatureToken, Configuration.of(mode)); + } + + @SuppressWarnings("unchecked") + protected T createSignatureBy(Container.DocumentType type, SignatureProfile signatureProfile, SignatureToken signatureToken, Configuration configuration) { try { - SignatureBuilder builder = SignatureBuilder.aSignature(TestDataBuilderUtil.createContainerWithFile(this.testFolder, type, mode)); + SignatureBuilder builder = SignatureBuilder.aSignature(TestDataBuilderUtil.createContainerWithFile(this.testFolder, type, configuration)); if (signatureProfile != null) { builder.withSignatureProfile(signatureProfile); } diff --git a/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java b/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java index b3bb17ff4..e6c589cd9 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/AiaOcspTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j; import org.digidoc4j.test.TestAssert; @@ -18,7 +28,7 @@ public class AiaOcspTest extends AbstractTest { @Test public void signAsiceContainerWithoutAiaOcsp() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - assertFalse(configuration.isAiaOcspPreferred()); + configuration.setPreferAiaOcsp(false); File testFile1 = this.createTemporaryFileBy("testFile.txt", "TEST"); Container container = ContainerBuilder.aContainer() @@ -36,7 +46,7 @@ public void signAsiceContainerWithoutAiaOcsp() { @Test public void signAsiceContainerUsingAiaOcsp() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - configuration.setPreferAiaOcsp(true); + assertTrue(configuration.isAiaOcspPreferred()); File testFile1 = this.createTemporaryFileBy("testFile.txt", "TEST"); Container container = ContainerBuilder.aContainer() .withDataFile(testFile1.getPath(), "text/plain") @@ -50,7 +60,7 @@ public void signAsiceContainerUsingAiaOcsp() { @Test public void signAsiceContainerWithEccTokenUsingAiaOcsp() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - configuration.setPreferAiaOcsp(true); + assertTrue(configuration.isAiaOcspPreferred()); File testFile1 = this.createTemporaryFileBy("testFile.txt", "TEST"); Container container = ContainerBuilder.aContainer() .withDataFile(testFile1.getPath(), "text/plain") @@ -64,7 +74,7 @@ public void signAsiceContainerWithEccTokenUsingAiaOcsp() { @Test public void signAsiceContainerWithEsteid2018UsingAiaOcsp() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - configuration.setPreferAiaOcsp(true); + assertTrue(configuration.isAiaOcspPreferred()); File testFile1 = this.createTemporaryFileBy("testFile.txt", "TEST"); Container container = ContainerBuilder.aContainer() .withDataFile(testFile1.getPath(), "text/plain") @@ -80,7 +90,7 @@ public void signAsiceContainerWithEsteid2018UsingAiaOcsp() { @Test public void signAsiceContainerWithManuallyConfiguredAiaOcsp() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - assertFalse(configuration.isAiaOcspPreferred()); + configuration.setPreferAiaOcsp(false); configuration.setOcspSource("http://aia.demo.sk.ee/esteid2015"); configuration.setUseOcspNonce(false); @@ -98,7 +108,7 @@ public void signAsiceContainerWithManuallyConfiguredAiaOcsp() { @Ignore("Fix by adding AdditionalServiceInformation to TEST of ESTEID-SK 2015 in test TSL") public void signAsiceContainerWithManuallyConfiguredOlderAiaOcsp_whileUsingOcspNonce_thenOcspRetrievalShouldFail() { Configuration configuration = new Configuration(Configuration.Mode.TEST); - assertFalse(configuration.isAiaOcspPreferred()); + configuration.setPreferAiaOcsp(false); configuration.setOcspSource("http://aia.demo.sk.ee/esteid2015"); File testFile1 = this.createTemporaryFileBy("testFile.txt", "TEST"); diff --git a/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java index ebf9eca53..17fcb1ca9 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/CertificateValidatorBuilderTest.java @@ -83,7 +83,9 @@ public void validate_WhenCertificateIsNotTrusted_ValidationExceptionWithUntruste @Test public void validate_WhenCertificateIsRevoked_ValidationExceptionWithRevokedStatusIsThrown() { - CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(this.configuration).build(); + Configuration configuration = Configuration.of(Configuration.Mode.TEST); + configuration.setPreferAiaOcsp(false); + CertificateValidator validator = new CertificateValidatorBuilder().withConfiguration(configuration).build(); validator.getCertificateSource().addCertificate(openCertificateToken("src/test/resources/testFiles/certs/TESTofESTEID-SK2011.crt")); X509Certificate certificateToTest = openX509Certificate("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer"); diff --git a/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java b/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java index a409c7e2a..f2f21e63e 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/ConfigurationTest.java @@ -1454,14 +1454,14 @@ public void loadEmptyRequiredTerritoriesFromConf() throws Exception { } @Test - public void aiaOcspNotPreferredByDefault_defaultTest() { - Assert.assertFalse(configuration.isAiaOcspPreferred()); + public void aiaOcspPreferredByDefault_defaultTest() { + Assert.assertTrue(configuration.isAiaOcspPreferred()); } - @Test - public void aiaOcspNotPreferredByDefault_defaultProd() { - Assert.assertFalse(Configuration.of(Configuration.Mode.PROD).isAiaOcspPreferred()); - } + @Test + public void aiaOcspPreferredByDefault_defaultProd() { + Assert.assertTrue(Configuration.of(Configuration.Mode.PROD).isAiaOcspPreferred()); + } @Test public void getAiaOcspSourceByCN_defaultTest() { diff --git a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java index 73b9f1c87..cf3339845 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/SignatureBuilderTest.java @@ -1379,6 +1379,7 @@ public void claimedSigningTimeInitializedDuringDataToSignBuilding() { @Test public void invokeSigning_networkExceptionIsNotCaught() { Configuration configuration = Configuration.of(TEST); + configuration.setPreferAiaOcsp(false); configuration.setOcspSource("http://invalid.ocsp.url"); expectedException.expect(ServiceUnreachableException.class); @@ -1395,6 +1396,7 @@ public void invokeSigning_networkExceptionIsNotCaught() { @Test public void dataToSignFinalize_networkExceptionIsNotCaught() { Configuration configuration = Configuration.of(TEST); + configuration.setPreferAiaOcsp(false); configuration.setOcspSource("http://invalid.ocsp.url"); expectedException.expect(ServiceUnreachableException.class); diff --git a/digidoc4j/src/test/java/org/digidoc4j/SignatureTest.java b/digidoc4j/src/test/java/org/digidoc4j/SignatureTest.java index f30809aca..b4c0394e5 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/SignatureTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/SignatureTest.java @@ -171,7 +171,9 @@ public void testGetOCSPCertificateForExistingBDoc() throws CertificateEncodingEx @Test public void testGetOCSPCertificateForNewBDoc() { - Signature signature = createSignatureBy(Container.DocumentType.BDOC, pkcs12SignatureToken); + Configuration configuration = Configuration.of(Configuration.Mode.TEST); + configuration.setPreferAiaOcsp(false); + Signature signature = createSignatureBy(Container.DocumentType.BDOC, pkcs12SignatureToken, configuration); assertThat( signature.getOCSPCertificate().getSubjectName(X509Cert.SubjectName.CN), matchesRegex("TEST of ESTEID-SK 2015 AIA OCSP RESPONDER 202[3-9][0-1][0-9]") diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java index 46ac0f04b..7837d5125 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java @@ -50,6 +50,7 @@ import static org.digidoc4j.Configuration.Mode.TEST; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -87,6 +88,7 @@ public void getRevokedCertificateOCSPToken_thenThrowRevokedCertificateValidation X509Certificate subjectCertificate = openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofStatusRevoked.cer")); CertificateToken issuerCertificateToken = getIssuerCertificateToken(subjectCertificate, certificateSource); + configuration.setPreferAiaOcsp(false); SKOnlineOCSPSource ocspSource = constructOCSPSource(); try { ocspSource.getRevocationToken(new CertificateToken(subjectCertificate), issuerCertificateToken); @@ -182,8 +184,8 @@ public void getOCSPToken_malformedOCSPRequest_thenThrowTechnicalCertificateValid ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw CertificateValidationException"); } catch (CertificateValidationException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); assertSame(CertificateValidationStatus.TECHNICAL, e.getCertificateStatus()); assertEquals("OCSP request malformed", e.getMessage()); } @@ -199,8 +201,8 @@ public void getOCSPToken_ocspServiceInternalError_thenThrowTechnicalCertificateV ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw CertificateValidationException"); } catch (CertificateValidationException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); assertSame(CertificateValidationStatus.TECHNICAL, e.getCertificateStatus()); assertEquals("OCSP service internal error", e.getMessage()); } @@ -216,9 +218,9 @@ public void getOCSPToken_ocspResponseTryLater_thenThrowServiceUnavailableExcepti ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw ServiceUnavailableException"); } catch (ServiceUnavailableException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); - assertEquals("Connection to OCSP service <" + configuration.getOcspSource() + "> is unavailable, try again later", e.getMessage()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertEquals("Connection to AIA_OCSP service <" + e.getServiceUrl() + "> is unavailable, try again later", e.getMessage()); } } @@ -232,8 +234,8 @@ public void getOCSPToken_ocspRequestNotSigned_thenThrowTechnicalCertificateValid ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw CertificateValidationException"); } catch (CertificateValidationException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); assertSame(CertificateValidationStatus.TECHNICAL, e.getCertificateStatus()); assertEquals("OCSP request not signed", e.getMessage()); } @@ -249,9 +251,9 @@ public void getOCSPToken_whenOCSPResponseIsUnauthorized_thenThrowAccessDeniedExc ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw ServiceAccessDeniedException"); } catch (ServiceAccessDeniedException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); - assertEquals("Access denied to OCSP service <" + configuration.getOcspSource() + ">", e.getMessage()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertEquals("Access denied to AIA_OCSP service <" + e.getServiceUrl() + ">", e.getMessage()); } } @@ -265,8 +267,8 @@ public void getOCSPToken_unhandledOcspResponseStatus_thenThrowTechnicalCertifica ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw CertificateValidationException"); } catch (CertificateValidationException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); assertSame(CertificateValidationStatus.TECHNICAL, e.getCertificateStatus()); assertEquals("OCSP service responded with unknown status <7>", e.getMessage()); } @@ -283,8 +285,8 @@ public void getOCSPToken_failedToParseOCSPResponse_thenThrowTechnicalCertificate ocspSource.getRevocationToken(new CertificateToken(TestSigningUtil.SIGN_CERT), new CertificateToken(this.issuerCert)); fail("Expected to throw CertificateValidationException"); } catch (CertificateValidationException e) { - assertSame(ServiceType.OCSP, e.getServiceType()); - assertEquals(configuration.getOcspSource(), e.getServiceUrl()); + assertSame(ServiceType.AIA_OCSP, e.getServiceType()); + assertNotEquals(configuration.getOcspSource(), e.getServiceUrl()); assertSame(CertificateValidationStatus.TECHNICAL, e.getCertificateStatus()); assertEquals("Failed to parse OCSP response", e.getMessage()); } @@ -294,6 +296,7 @@ public void getOCSPToken_failedToParseOCSPResponse_thenThrowTechnicalCertificate public void getOCSPToken_nonceValidationFailed_thenThrowUntrustedCertificateValidationException() { String response = "MIIG+woBAKCCBvQwggbwBgkrBgEFBQcwAQEEggbhMIIG3TCCAS+hgYYwgYMxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMQ0wCwYDVQQLDARPQ1NQMScwJQYDVQQDDB5URVNUIG9mIFNLIE9DU1AgUkVTUE9OREVSIDIwMTExGDAWBgkqhkiG9w0BCQEWCXBraUBzay5lZRgPMjAxOTA2MTYyMTQ3MTBaMGAwXjBJMAkGBSsOAwIaBQAEFFM9O8j1sQrsw3y2Z1e/2ZiukwOJBBQS8lo+6lYcv80GrPHxJcmpS9QUmQIQKVKTqv2MxtRNgzCjwmRRDYAAGA8yMDE5MDYxNjIxNDcxMFqhMTAvMC0GCSsGAQUFBzABAgQgMFH97/J8r9UBJdCv4ttX1DNXBa8x7prf+L8nBOIAhnIwDQYJKoZIhvcNAQELBQADggEBACXNXoMb3ZVvrgkR4YbhHG35cKWzf3N6N80v4H+bu8eEH25V9kBiFE81kC2WkjHbJlMpDt7JFdE6JNZS4y+yo25HBAcWKuwtUvfKpNtJV7ueHvXDmOIgl+VVhhCY9h2NJzbUbgxn7i9cIjMM2RA8Nz+ha7YM6BIACQcUL4VbD93bKYpLUuMDi9beNhCRpdKy3ZMoUbx/aUFj5SEaTqEW2Xf47J0jjJ2Bz6aIG8s9RooRbUqrXwUeFhrWtoC7wMiQzr0v8JsOGbfN8u2GftRzctlZvtf8RPbS/J4NIoAOkotjiNt0qErJB0gPfsO6WJj5JbWpoyYtA90ceEv9IQNXVX2gggSSMIIEjjCCBIowggNyoAMCAQICEGiPMegZ2nGHTXTcJWJ5/5swDQYJKoZIhvcNAQEFBQAwfTELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMxMDAuBgNVBAMMJ1RFU1Qgb2YgRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMB4XDTExMDMwNzEzMjI0NVoXDTI0MDkwNzEyMjI0NVowgYMxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMQ0wCwYDVQQLDARPQ1NQMScwJQYDVQQDDB5URVNUIG9mIFNLIE9DU1AgUkVTUE9OREVSIDIwMTExGDAWBgkqhkiG9w0BCQEWCXBraUBzay5lZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANHMOgo2tewW2Gx4un68HHAyOASEC5P34ghPC+OaLNMYT4BBkfhBxPCzwiKqHz4H+IMDdbwxOnEDVJStDnflLId/YvWeOXrJ36Rqvth7AyWhZha+frgtTBM+Sp9U2sxLym0Y5Bp0kPQXq7ZRnq9gZVP5KjpOagOUbSX4U9KbHNYsSnT4qb+fcJ3/px8dfk/nz1p3V1WS6A4OLd8PJSLyBPyoTkjJRK7wSByACle8h9YTscnhi4IaszIgJ91HkxDoKDkvVEb9Av0+Qt5h/mP7mpDEsYzbs+NT53opgs2xCWSUYhGjCI/KjwLm3Gy/BrWNNzFpnzbV+v8IerukzH1vEtsCAwEAAaOB/jCB+zAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCTAdBgNVHQ4EFgQUff+QrkaJBIBoqks2LmRmAKIJfE8wgaAGA1UdIASBmDCBlTCBkgYKKwYBBAHOHwMBATCBgzBYBggrBgEFBQcCAjBMHkoAQQBpAG4AdQBsAHQAIAB0AGUAcwB0AGkAbQBpAHMAZQBrAHMALgAgAE8AbgBsAHkAIABmAG8AcgAgAHQAZQBzAHQAaQBuAGcALjAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5zay5lZS9hamF0ZW1wZWwvMB8GA1UdIwQYMBaAFLU0Cp2lLxDF5yEOvsSxZUcbA3b+MA0GCSqGSIb3DQEBBQUAA4IBAQAG2o+5E67kwDx6k6MnvWbQXWidxWY4iroPf+UY7DMA6TnqhQ6gqKy3fgwSOLYHbtIOJYWiN2lZynUQZBldfJKqfOLlPeyURVkBH+h/IaSfZPy8wAApD97Q/tMpvpned9plfp0c9SY/kTywFJPcWDFeyj3M2TdcZ5dsGQycAW0KXElR9Q45Wb97RSxwSyGE0uqjiuEsUrXIEauynUXM31upn180wkVjNxvZ5g3ouUN/l0xA+NY/LM0VoJc2H+szr+HY5I2uuFmK2kOc2+MfF4e6kwpOlLqWe43vtKEX7s9If988kXY3ET5I5aEqUKfzRvEZq3J6/O+KfHfX3cAq0SO1"; when(dataLoader.post(anyString(), any(byte[].class))).thenReturn(Base64.decode(response)); + configuration.setPreferAiaOcsp(false); SKOnlineOCSPSource ocspSource = constructOCSPSource(); ocspSource.setDataLoader(dataLoader); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java index 75afa7a06..bf20c1335 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/BDocSerializationTest.java @@ -74,6 +74,7 @@ public void changeConfigurationAfterDeserializationToInvalidOcspAndThrowConnecti this.serialize(container, this.serializedContainerLocation); this.serialize(originalDataToSign, serializedDataToSignPath); DataToSign deserializedDataToSign = this.deserializer(serializedDataToSignPath); + deserializedDataToSign.getConfiguration().setPreferAiaOcsp(false); deserializedDataToSign.getConfiguration().setOcspSource("http://invalid.ocsp.url"); byte[] signatureValue = this.sign(deserializedDataToSign.getDataToSign(), deserializedDataToSign.getDigestAlgorithm()); diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java index 9580e456e..b134c297e 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/AsicSignatureFinalizerTest.java @@ -1,3 +1,13 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + package org.digidoc4j.impl.bdoc.asic; import eu.europa.esig.dss.service.http.commons.CommonsDataLoader; @@ -106,6 +116,7 @@ public void testCustomTspDataLoaderUsedForSigning() { @Test public void testCustomOcspDataLoaderUsedForSigning() { configuration = Configuration.of(Configuration.Mode.TEST); + configuration.setPreferAiaOcsp(false); SkOCSPDataLoader ocspDataLoader = new SkOCSPDataLoader(configuration); ocspDataLoader.setUserAgent("custom-user-agent-string"); DataLoader dataLoaderSpy = Mockito.spy(ocspDataLoader); diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDataBuilderUtil.java b/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDataBuilderUtil.java index 13bea7489..9cf9acd76 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDataBuilderUtil.java +++ b/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDataBuilderUtil.java @@ -1,12 +1,12 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.test.util; @@ -37,11 +37,19 @@ public static Container createContainerWithFile(TemporaryFolder folder, String c } public static Container createContainerWithFile(TemporaryFolder folder, String containerType, Configuration.Mode mode) throws IOException { - return TestDataBuilderUtil.populateContainerBuilderWithFile(ContainerBuilder.aContainer(containerType), folder, mode); + return TestDataBuilderUtil.createContainerWithFile(folder, containerType, Configuration.of(mode)); + } + + public static Container createContainerWithFile(TemporaryFolder folder, String containerType, Configuration configuration) throws IOException { + return TestDataBuilderUtil.populateContainerBuilderWithFile(ContainerBuilder.aContainer(containerType), folder, configuration); } public static Container createContainerWithFile(TemporaryFolder folder, Container.DocumentType type, Configuration.Mode mode) throws IOException { - return TestDataBuilderUtil.populateContainerBuilderWithFile(ContainerBuilder.aContainer(type), folder, mode); + return TestDataBuilderUtil.createContainerWithFile(folder, type, Configuration.of(mode)); + } + + public static Container createContainerWithFile(TemporaryFolder folder, Container.DocumentType type, Configuration configuration) throws IOException { + return TestDataBuilderUtil.populateContainerBuilderWithFile(ContainerBuilder.aContainer(type), folder, configuration); } public static Container createContainerWithFile(String dataFilePath) { @@ -89,9 +97,9 @@ public static Container open(String path) { return ContainerBuilder.aContainer().fromExistingFile(path).build(); } - private static Container populateContainerBuilderWithFile(ContainerBuilder builder, TemporaryFolder testFolder, Configuration.Mode mode) throws IOException { + private static Container populateContainerBuilderWithFile(ContainerBuilder builder, TemporaryFolder testFolder, Configuration configuration) throws IOException { File testFile = TestDataBuilderUtil.createTestFile(testFolder); - return builder.withConfiguration(new Configuration(mode)).withDataFile(testFile.getPath(), "text/plain").build(); + return builder.withConfiguration(configuration).withDataFile(testFile.getPath(), "text/plain").build(); } private static SignatureBuilder prepareDataToSign(Container container) { From 9df15fa710f6d66223c92db6cb38a0e5033cd759 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 19 Feb 2024 16:11:33 +0200 Subject: [PATCH 22/35] DD4J-922 Deprecate '-aiaocsp' option for command line utility and add new '-noaiaocsp' option to disable AIA OCSP preference --- .../digidoc4j/main/CommandLineExecutor.java | 35 +++++++++--------- .../java/org/digidoc4j/main/DigiDoc4J.java | 26 ++++++------- .../xades/DetachedXadesSignatureExecutor.java | 37 ++++++++++++++----- 3 files changed, 59 insertions(+), 39 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/main/CommandLineExecutor.java b/digidoc4j/src/main/java/org/digidoc4j/main/CommandLineExecutor.java index f9363e170..b14b0c8b6 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/main/CommandLineExecutor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/main/CommandLineExecutor.java @@ -10,25 +10,14 @@ package org.digidoc4j.main; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.cert.X509Certificate; -import java.util.Arrays; - +import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import eu.europa.esig.dss.spi.DSSUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.digidoc4j.Configuration; import org.digidoc4j.Container; import org.digidoc4j.ContainerBuilder; import org.digidoc4j.ContainerOpener; -import org.digidoc4j.SignatureValidationResult; import org.digidoc4j.DataFile; import org.digidoc4j.DataToSign; import org.digidoc4j.EncryptionAlgorithm; @@ -36,6 +25,7 @@ import org.digidoc4j.SignatureBuilder; import org.digidoc4j.SignatureProfile; import org.digidoc4j.SignatureToken; +import org.digidoc4j.SignatureValidationResult; import org.digidoc4j.exceptions.DataFileNotFoundException; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.impl.asic.AsicContainer; @@ -49,8 +39,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import eu.europa.esig.dss.spi.DSSUtils; -import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.cert.X509Certificate; +import java.util.Arrays; /** * Class for managing digidoc4j-util parameters. @@ -449,9 +448,11 @@ private void updateEncryptionAlgorithm(SignatureBuilder signatureBuilder) { } private void useAiaOcsp(Container container) { - if (this.context.getCommandLine().hasOption("aiaocsp")) { + if (this.context.getCommandLine().hasOption("noaiaocsp")) { Configuration configuration = container.getConfiguration(); - configuration.setPreferAiaOcsp(true); + configuration.setPreferAiaOcsp(false); + } else if (this.context.getCommandLine().hasOption("aiaocsp")) { + LOGGER.warn("Option 'aiaocsp' is deprecated; preference to use AIA OCSP is enabled by default"); } } diff --git a/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java b/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java index 38f59ce5a..8f4232103 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java +++ b/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java @@ -1,17 +1,15 @@ /* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ package org.digidoc4j.main; -import java.util.List; - import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; @@ -21,13 +19,14 @@ import org.apache.commons.cli.ParseException; import org.digidoc4j.Container; import org.digidoc4j.Version; +import org.digidoc4j.ddoc.DigiDocException; +import org.digidoc4j.ddoc.SignedDoc; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.main.xades.DetachedXadesSignatureExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.digidoc4j.ddoc.DigiDocException; -import org.digidoc4j.ddoc.SignedDoc; +import java.util.List; /** * Client commandline tool for DigiDoc4J library. @@ -219,7 +218,8 @@ private static Options createParameters() { options.addOption("version", "version", false, "show version"); options.addOption("tst", "timestamp", false, "adds timestamp token to container"); options.addOption("err", "showerrors", false, "show container errors [deprecated]"); - options.addOption("aiaocsp", "aiaocsp", false, "prefer AIA OCSP in case of LT,LTA signature profiles"); + options.addOption("aiaocsp", "aiaocsp", false, "prefer to use AIA OCSP for signing [deprecated]"); + options.addOption("noaiaocsp", "noaiaocsp", false, "disable AIA OCSP preference for signing"); options.addOption(DigiDoc4J.type()); options.addOption(DigiDoc4J.inputFile()); options.addOption(DigiDoc4J.inputDir()); diff --git a/digidoc4j/src/main/java/org/digidoc4j/main/xades/DetachedXadesSignatureExecutor.java b/digidoc4j/src/main/java/org/digidoc4j/main/xades/DetachedXadesSignatureExecutor.java index 940689be3..c6ff95d46 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/main/xades/DetachedXadesSignatureExecutor.java +++ b/digidoc4j/src/main/java/org/digidoc4j/main/xades/DetachedXadesSignatureExecutor.java @@ -1,16 +1,27 @@ -package org.digidoc4j.main.xades; +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; +package org.digidoc4j.main.xades; import org.apache.commons.cli.CommandLine; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; -import org.digidoc4j.*; +import org.digidoc4j.Configuration; +import org.digidoc4j.DetachedXadesSignatureBuilder; +import org.digidoc4j.DigestAlgorithm; +import org.digidoc4j.DigestDataFile; +import org.digidoc4j.Signature; +import org.digidoc4j.SignatureProfile; +import org.digidoc4j.SignatureToken; +import org.digidoc4j.ValidationResult; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.main.ExecutionCommand; import org.digidoc4j.main.ExecutionOption; @@ -19,6 +30,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + /** * Executor for managing detached XadES signatures. */ @@ -141,8 +158,10 @@ private void addDigestFile(String name, String base64EncodedDigest, String mimeT } private void useAiaOcsp(Configuration configuration) { - if (this.context.getCommandLine().hasOption("aiaocsp")) { - configuration.setPreferAiaOcsp(true); + if (this.context.getCommandLine().hasOption("noaiaocsp")) { + configuration.setPreferAiaOcsp(false); + } else if (this.context.getCommandLine().hasOption("aiaocsp")) { + LOGGER.warn("Option 'aiaocsp' is deprecated; preference to use AIA OCSP is enabled by default"); } } From f526d11a9910acad94fb74da9044825a413272d6 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Fri, 23 Feb 2024 13:41:40 +0200 Subject: [PATCH 23/35] DD4J-967 Restore the previous form of XML validation reports --- .../report/SignatureValidationReport.java | 6 +- .../SignatureValidationReportCreator.java | 1 - .../impl/asic/report/XmlCertificate.java | 66 +++++++++ .../impl/asic/report/XmlCertificateChain.java | 56 ++++++++ .../report/SignatureValidationReportTest.java | 128 +++++++++++++++--- .../bdoc/report/ValidationReportTest.java | 11 +- 6 files changed, 234 insertions(+), 34 deletions(-) create mode 100644 digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificate.java create mode 100644 digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificateChain.java diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java index 2dabb7cbd..dbcd3de35 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReport.java @@ -17,7 +17,6 @@ import eu.europa.esig.dss.simplereport.jaxb.Adapter3; import eu.europa.esig.dss.simplereport.jaxb.Adapter4; import eu.europa.esig.dss.simplereport.jaxb.Adapter6; -import eu.europa.esig.dss.simplereport.jaxb.XmlCertificateChain; import eu.europa.esig.dss.simplereport.jaxb.XmlDetails; import eu.europa.esig.dss.simplereport.jaxb.XmlMessage; import eu.europa.esig.dss.simplereport.jaxb.XmlSignature; @@ -125,7 +124,10 @@ public static SignatureValidationReport create(XmlSignature xmlSignature) { report.getSignatureScope().addAll(xmlSignature.getSignatureScope()); report.setId(xmlSignature.getId()); report.setSignatureFormat(xmlSignature.getSignatureFormat()); - report.setCertificateChain(xmlSignature.getCertificateChain()); + report.setCertificateChain(Optional + .ofNullable(xmlSignature.getCertificateChain()) + .map(XmlCertificateChain::create) + .orElse(null)); return report; } diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java index e383f08e7..b9fb21475 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/SignatureValidationReportCreator.java @@ -12,7 +12,6 @@ import eu.europa.esig.dss.enumerations.Indication; import eu.europa.esig.dss.enumerations.SignatureLevel; -import eu.europa.esig.dss.simplereport.jaxb.XmlCertificate; import eu.europa.esig.dss.simplereport.jaxb.XmlSignature; import eu.europa.esig.dss.simplereport.jaxb.XmlSimpleReport; import eu.europa.esig.dss.simplereport.jaxb.XmlToken; diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificate.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificate.java new file mode 100644 index 000000000..6f0ba4cc8 --- /dev/null +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificate.java @@ -0,0 +1,66 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.impl.asic.report; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; + +import java.io.Serializable; + +/** + * DD4J-967: + * This class is a copy of {@link eu.europa.esig.dss.simplereport.jaxb.XmlCertificate} as it was in DSS 5.11.1 + * (except for the migration from {@code javax} to {@code jakarta} namespace and additional + * {@link #create(eu.europa.esig.dss.simplereport.jaxb.XmlCertificate)} method). + * It is a temporary solution for keeping the XML of the validation report temporarily unchanged. + * This class may disappear in the future. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "id", + "qualifiedName" +}) +public class XmlCertificate implements Serializable { + + private final static long serialVersionUID = 1L; + + @XmlElement(required = true) + protected String id; + + @XmlElement(required = true) + protected String qualifiedName; + + static XmlCertificate create(eu.europa.esig.dss.simplereport.jaxb.XmlCertificate dssCertificate) { + XmlCertificate dd4jCertificate = new XmlCertificate(); + dd4jCertificate.setId(dssCertificate.getId()); + dd4jCertificate.setQualifiedName(dssCertificate.getQualifiedName()); + return dd4jCertificate; + } + + public String getId() { + return id; + } + + public void setId(String value) { + this.id = value; + } + + public String getQualifiedName() { + return qualifiedName; + } + + public void setQualifiedName(String value) { + this.qualifiedName = value; + } + +} diff --git a/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificateChain.java b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificateChain.java new file mode 100644 index 000000000..b060f8218 --- /dev/null +++ b/digidoc4j/src/main/java/org/digidoc4j/impl/asic/report/XmlCertificateChain.java @@ -0,0 +1,56 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.impl.asic.report; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * DD4J-967: + * This class is a copy of {@link eu.europa.esig.dss.simplereport.jaxb.XmlCertificateChain} as it was in DSS 5.11.1 + * (except for the migration from {@code javax} to {@code jakarta} namespace and additional + * {@link #create(eu.europa.esig.dss.simplereport.jaxb.XmlCertificateChain)} method). + * It is a temporary solution for keeping the XML of the validation report temporarily unchanged. + * This class may disappear in the future. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "certificate" +}) +public class XmlCertificateChain implements Serializable { + + private final static long serialVersionUID = 1L; + + @XmlElement(name = "Certificate") + protected List certificate; + + static XmlCertificateChain create(eu.europa.esig.dss.simplereport.jaxb.XmlCertificateChain dssCertificateChain) { + final XmlCertificateChain dd4jCertificateChain = new XmlCertificateChain(); + dssCertificateChain.getCertificate().stream() + .map(XmlCertificate::create) + .forEach(dd4jCertificateChain.getCertificate()::add); + return dd4jCertificateChain; + } + + public List getCertificate() { + if (certificate == null) { + certificate = new ArrayList<>(); + } + return this.certificate; + } + +} diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/SignatureValidationReportTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/SignatureValidationReportTest.java index 62a2180ce..4af490f37 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/SignatureValidationReportTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/SignatureValidationReportTest.java @@ -14,24 +14,36 @@ import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.enumerations.SignatureQualification; import eu.europa.esig.dss.enumerations.SubIndication; +import eu.europa.esig.dss.simplereport.jaxb.XmlCertificate; +import eu.europa.esig.dss.simplereport.jaxb.XmlCertificateChain; import eu.europa.esig.dss.simplereport.jaxb.XmlDetails; import eu.europa.esig.dss.simplereport.jaxb.XmlMessage; import eu.europa.esig.dss.simplereport.jaxb.XmlSignature; import eu.europa.esig.dss.simplereport.jaxb.XmlSignatureLevel; import eu.europa.esig.dss.simplereport.jaxb.XmlSignatureScope; +import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamp; +import eu.europa.esig.dss.simplereport.jaxb.XmlTimestamps; import org.digidoc4j.impl.asic.report.SignatureValidationReport; -import org.junit.Assert; import org.junit.Test; import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInRelativeOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; public class SignatureValidationReportTest { @Test - public void copyXmlSignatureParameters() { + public void create_WhenXmlSignatureParametersArePresent_SignatureValidationReportWithMatchingParametersIsCreated() { XmlSignature signature = new XmlSignature(); Date today = new Date(); signature.setSigningTime(today); @@ -44,31 +56,90 @@ public void copyXmlSignatureParameters() { signature.setSignatureLevel(sigLevel); signature.setSubIndication(SubIndication.NO_POE); signature.setAdESValidationDetails(new XmlDetails()); - signature.getAdESValidationDetails().getError().addAll(asList(createMessage("AdESError1"), createMessage("AdESError2"))); - signature.getAdESValidationDetails().getWarning().addAll(asList(createMessage("AdESWarning1"), createMessage("AdESWarning2"))); - signature.getAdESValidationDetails().getInfo().addAll(asList(createMessage("AdESInfo1"), createMessage("AdESInfo2"))); + signature.getAdESValidationDetails().getError().addAll(createMessages("AdESError1", "AdESError2")); + signature.getAdESValidationDetails().getWarning().addAll(createMessages("AdESWarning1", "AdESWarning2")); + signature.getAdESValidationDetails().getInfo().addAll(createMessages("AdESInfo1", "AdESInfo2")); signature.setQualificationDetails(new XmlDetails()); - signature.getQualificationDetails().getError().addAll(asList(createMessage("QError1"), createMessage("QError2"))); - signature.getQualificationDetails().getWarning().addAll(asList(createMessage("QWarning1"), createMessage("QWarning2"))); - signature.getQualificationDetails().getInfo().addAll(asList(createMessage("QInfo1"), createMessage("QInfo2"))); + signature.getQualificationDetails().getError().addAll(createMessages("QError1", "QError2")); + signature.getQualificationDetails().getWarning().addAll(createMessages("QWarning1", "QWarning2")); + signature.getQualificationDetails().getInfo().addAll(createMessages("QInfo1", "QInfo2")); signature.getSignatureScope().add(new XmlSignatureScope()); signature.setId("123abc"); signature.setParentId("Parent ID"); + signature.setTimestamps(new XmlTimestamps()); + signature.getTimestamps().getTimestamp().add(new XmlTimestamp()); + signature.getTimestamps().getTimestamp().get(0).setAdESValidationDetails(new XmlDetails()); + signature.getTimestamps().getTimestamp().get(0).getAdESValidationDetails().getError().add(createMessage("TsAdESError")); + signature.getTimestamps().getTimestamp().get(0).getAdESValidationDetails().getWarning().add(createMessage("TsAdESWarning")); + signature.getTimestamps().getTimestamp().get(0).getAdESValidationDetails().getInfo().add(createMessage("TsAdESInfo")); + signature.getTimestamps().getTimestamp().get(0).setQualificationDetails(new XmlDetails()); + signature.getTimestamps().getTimestamp().get(0).getQualificationDetails().getError().add(createMessage("TsQError")); + signature.getTimestamps().getTimestamp().get(0).getQualificationDetails().getWarning().add(createMessage("TsQWarning")); + signature.getTimestamps().getTimestamp().get(0).getQualificationDetails().getInfo().add(createMessage("TsQInfo")); signature.setSignatureFormat(SignatureLevel.UNKNOWN); + signature.setCertificateChain(new XmlCertificateChain()); + signature.getCertificateChain().getCertificate().addAll(asList( + createCertificate("1234", "QName1"), + createCertificate("5678", "QName2") + )); + SignatureValidationReport report = SignatureValidationReport.create(signature); - Assert.assertEquals(today, report.getSigningTime()); - Assert.assertEquals(today, report.getBestSignatureTime()); - Assert.assertEquals("SignedBy", report.getSignedBy()); - Assert.assertEquals(Indication.TOTAL_PASSED, report.getIndication()); - Assert.assertEquals("QESIG", report.getSignatureLevel().getValue().name()); - Assert.assertEquals("QESig", report.getSignatureLevel().getValue().getReadable()); - Assert.assertEquals(SubIndication.NO_POE, report.getSubIndication()); - Assert.assertThat(report.getErrors(), containsInAnyOrder("AdESError1", "AdESError2", "QError1", "QError2")); - Assert.assertThat(report.getWarnings(), containsInAnyOrder("AdESWarning1", "AdESWarning2", "QWarning1", "QWarning2")); - Assert.assertThat(report.getInfos(), containsInAnyOrder("AdESInfo1", "AdESInfo2", "QInfo1", "QInfo2")); - Assert.assertEquals(1, report.getSignatureScope().size()); - Assert.assertEquals("123abc", report.getId()); - Assert.assertEquals(SignatureLevel.UNKNOWN, report.getSignatureFormat()); + + assertThat(report.getSigningTime(), equalTo(today)); + assertThat(report.getBestSignatureTime(), equalTo(today)); + assertThat(report.getSignedBy(), equalTo("SignedBy")); + assertThat(report.getIndication(), equalTo(Indication.TOTAL_PASSED)); + assertThat(report.getSignatureLevel(), notNullValue(XmlSignatureLevel.class)); + assertThat(report.getSignatureLevel().getValue(), equalTo(SignatureQualification.QESIG)); + assertThat(report.getSignatureLevel().getDescription(), equalTo(SignatureQualification.QESIG.getLabel())); + assertThat(report.getSubIndication(), equalTo(SubIndication.NO_POE)); + assertThat(report.getErrors(), hasSize(6)); + assertThat(report.getErrors(), containsInRelativeOrder( + "AdESError1", "AdESError2", "QError1", "QError2", + "TsAdESError", "TsQError" + )); + assertThat(report.getWarnings(), hasSize(6)); + assertThat(report.getWarnings(), containsInRelativeOrder( + "AdESWarning1", "AdESWarning2", "QWarning1", "QWarning2", + "TsAdESWarning", "TsQWarning" + )); + assertThat(report.getInfos(), hasSize(6)); + assertThat(report.getInfos(), containsInRelativeOrder( + "AdESInfo1", "AdESInfo2", "QInfo1", "QInfo2", + "TsAdESInfo", "TsQInfo" + )); + assertThat(report.getSignatureScope(), hasSize(1)); + assertThat(report.getId(), equalTo("123abc")); + assertThat(report.getSignatureFormat(), equalTo(SignatureLevel.UNKNOWN)); + assertThat(report.getCertificateChain(), notNullValue(org.digidoc4j.impl.asic.report.XmlCertificateChain.class)); + assertThat(report.getCertificateChain().getCertificate(), hasSize(2)); + assertThat(report.getCertificateChain().getCertificate().get(0), notNullValue(org.digidoc4j.impl.asic.report.XmlCertificate.class)); + assertThat(report.getCertificateChain().getCertificate().get(0).getId(), equalTo("1234")); + assertThat(report.getCertificateChain().getCertificate().get(0).getQualifiedName(), equalTo("QName1")); + assertThat(report.getCertificateChain().getCertificate().get(1), notNullValue(org.digidoc4j.impl.asic.report.XmlCertificate.class)); + assertThat(report.getCertificateChain().getCertificate().get(1).getId(), equalTo("5678")); + assertThat(report.getCertificateChain().getCertificate().get(1).getQualifiedName(), equalTo("QName2")); + } + + @Test + public void create_WhenXmlSignatureParametersNotPresent_SignatureValidationReportWithMissingParametersIsCreated() { + XmlSignature signature = new XmlSignature(); + + SignatureValidationReport report = SignatureValidationReport.create(signature); + + assertThat(report.getSigningTime(), nullValue()); + assertThat(report.getBestSignatureTime(), nullValue()); + assertThat(report.getSignedBy(), nullValue()); + assertThat(report.getIndication(), nullValue()); + assertThat(report.getSignatureLevel(), nullValue()); + assertThat(report.getSubIndication(), nullValue()); + assertThat(report.getErrors(), empty()); + assertThat(report.getWarnings(), empty()); + assertThat(report.getInfos(), empty()); + assertThat(report.getSignatureScope(), empty()); + assertThat(report.getId(), nullValue()); + assertThat(report.getSignatureFormat(), nullValue()); + assertThat(report.getCertificateChain(), nullValue()); } private static XmlMessage createMessage(String message) { @@ -77,4 +148,17 @@ private static XmlMessage createMessage(String message) { return xmlMessage; } + private static List createMessages(String... messages) { + return Stream.of(messages) + .map(SignatureValidationReportTest::createMessage) + .collect(Collectors.toList()); + } + + private static XmlCertificate createCertificate(String id, String qualifiedName) { + XmlCertificate xmlCertificate = new XmlCertificate(); + xmlCertificate.setId(id); + xmlCertificate.setQualifiedName(qualifiedName); + return xmlCertificate; + } + } diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java index c2fec5c31..3e4331896 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/report/ValidationReportTest.java @@ -19,7 +19,6 @@ import org.digidoc4j.test.TestAssert; import org.digidoc4j.test.util.TestDataBuilderUtil; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; import java.nio.file.Paths; @@ -27,7 +26,6 @@ public class ValidationReportTest extends AbstractTest { @Test - @Ignore("DD4J-967") public void validContainerWithOneSignature() throws Exception { Container container = this.createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/test.txt")); Signature signature = this.createSignatureBy(container, SignatureProfile.LT, pkcs12SignatureToken); @@ -54,7 +52,6 @@ public void validContainerWithOneSignature() throws Exception { } @Test - @Ignore("DD4J-967") public void validContainerWithOneTmSignature() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_TM_SIG); String report = container.validate().getReport(); @@ -71,7 +68,6 @@ public void validContainerWithOneTmSignature() throws Exception { } @Test - @Ignore("DD4J-967") public void containerWithOneBesSignature() throws Exception { Container container = this.createNonEmptyContainerBy(Paths.get("src/test/resources/testFiles/helper-files/test.txt")); this.createSignatureBy(container, SignatureProfile.B_BES, pkcs12SignatureToken); @@ -81,14 +77,13 @@ public void containerWithOneBesSignature() throws Exception { TestAssert.assertXPathHasValue("1", "count(/SimpleReport/Signature)", report); TestAssert.assertXPathHasValue("XAdES-BASELINE-B", "/SimpleReport/Signature/@SignatureFormat", report); TestAssert.assertXPathHasValue("INDETERMINATE", "/SimpleReport/Signature/Indication", report); - TestAssert.assertXPathHasValue("TRY_LATER", "/SimpleReport/Signature/SubIndication", report); + TestAssert.assertXPathHasValue("CERTIFICATE_CHAIN_GENERAL_FAILURE", "/SimpleReport/Signature/SubIndication", report); TestAssert.assertXPathHasValue("test.txt", "/SimpleReport/Signature/SignatureScope/@name", report); TestAssert.assertXPathHasValue("true", "count(/SimpleReport/Signature/CertificateChain/Certificate) > 1", report); TestAssert.assertXPathHasValue("O’CONNEŽ-ŠUSLIK TESTNUMBER,MARY ÄNN,60001013739", "/SimpleReport/Signature/CertificateChain/Certificate[1]/qualifiedName", report); } @Test - @Ignore("DD4J-967") public void containerWithOneEpesSignature() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_B_EPES_SIG); String report = container.validate().getReport(); @@ -97,14 +92,13 @@ public void containerWithOneEpesSignature() throws Exception { TestAssert.assertXPathHasValue("1", "count(/SimpleReport/Signature)", report); TestAssert.assertXPathHasValue("XAdES-BASELINE-B-EPES", "/SimpleReport/Signature/@SignatureFormat", report); TestAssert.assertXPathHasValue("INDETERMINATE", "/SimpleReport/Signature/Indication", report); - TestAssert.assertXPathHasValue("TRY_LATER", "/SimpleReport/Signature/SubIndication", report); + TestAssert.assertXPathHasValue("CERTIFICATE_CHAIN_GENERAL_FAILURE", "/SimpleReport/Signature/SubIndication", report); TestAssert.assertXPathHasValue("junit4090904941259216539.tmp", "/SimpleReport/Signature/SignatureScope/@name", report); TestAssert.assertXPathHasValue("true", "count(/SimpleReport/Signature/CertificateChain/Certificate) > 1", report); TestAssert.assertXPathHasValue("ŽÕRINÜWŠKY,MÄRÜ-LÖÖZ,11404176865", "/SimpleReport/Signature/CertificateChain/Certificate[1]/qualifiedName", report); } @Test - @Ignore("DD4J-967") public void validContainerWithTwoSignatures() throws Exception { Container container = TestDataBuilderUtil.open(BDOC_WITH_TM_AND_TS_SIG); SignatureValidationResult result = container.validate(); @@ -126,7 +120,6 @@ public void validContainerWithTwoSignatures() throws Exception { } @Test - @Ignore("DD4J-967") public void invalidContainerWithOneSignature() throws Exception { Container container = TestDataBuilderUtil.open("src/test/resources/testFiles/invalid-containers/bdoc-tm-ocsp-revoked.bdoc"); SignatureValidationResult result = container.validate(); From 6a0b2c18adbd5b8afa865315d94a5518b3d1c90d Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 27 Feb 2024 09:59:51 +0200 Subject: [PATCH 24/35] DD4J-966 Update TEST mode default timestamp service URL --- .../src/main/java/org/digidoc4j/Constant.java | 2 +- .../impl/bdoc/IncompleteSigningTest.java | 18 +++++++++++++----- .../digidoc_test_conf_tsp_source.yaml | 6 +++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/digidoc4j/src/main/java/org/digidoc4j/Constant.java b/digidoc4j/src/main/java/org/digidoc4j/Constant.java index 900dcaa68..077024732 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/Constant.java +++ b/digidoc4j/src/main/java/org/digidoc4j/Constant.java @@ -62,7 +62,7 @@ public static class Default { public static class Test { - public static final String TSP_SOURCE = "http://demo.sk.ee/tsa"; + public static final String TSP_SOURCE = "http://tsa.demo.sk.ee/tsa"; public static final String LOTL_LOCATION = "https://open-eid.github.io/test-TL/tl-mp-test-EE.xml"; public static final String LOTL_TRUSTSTORE_PATH = "classpath:truststores/test-lotl-truststore.p12"; public static final String VALIDATION_POLICY = "conf/test_constraint.xml"; diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java index 7b1adb771..3c0d59fe2 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/IncompleteSigningTest.java @@ -87,7 +87,7 @@ public class IncompleteSigningTest extends AbstractTest { private static final String CERTIFICATE_VALIDATION_EXCEPTION_MESSAGE_REGEX = "OCSP response certificate match is not found in TSL"; private static final String CONTAINER_VALIDATION_ERROR_MESSAGE = "The certificate validation is not conclusive!"; private static final String OCSP_REQUEST_FAILED_EXCEPTION_MESSAGE_PART = "OCSP request failed"; - private static final String TECHNICAL_EXCEPTION_TSP_MESSAGE_PART = "Got error in signing process: Failed to POST URL: http://demo.sk.ee/tsa"; + private static final String TECHNICAL_EXCEPTION_TSP_MESSAGE_PART_TEMPLATE = "Got error in signing process: Failed to POST URL: %s"; private static final String TSL_REFRESH_EXCEPTION_MESSAGE_PART = "Failed to download LoTL"; @BeforeClass @@ -253,7 +253,9 @@ public void signatureProfileLtShouldFailWhenTslLoadingFails() { () -> createSignatureBy(container, SignatureProfile.LT, pkcs12SignatureToken) ); - assertThat(caughtException.getMessage(), containsString(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART)); + assertThat(caughtException.getMessage(), containsString( + String.format(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART_TEMPLATE, configuration.getTspSource()) + )); } @Test @@ -266,7 +268,9 @@ public void signatureProfileLtaShouldFailWhenTslLoadingFails() { () -> createSignatureBy(container, SignatureProfile.LTA, pkcs12SignatureToken) ); - assertThat(caughtException.getMessage(), containsString(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART)); + assertThat(caughtException.getMessage(), containsString( + String.format(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART_TEMPLATE, configuration.getTspSource()) + )); } @Test @@ -290,7 +294,9 @@ public void signatureProfileLtShouldFailWhenDataLoadersFail() { () -> createSignatureBy(container, SignatureProfile.LT, pkcs12SignatureToken) ); - assertThat(caughtException.getMessage(), containsString(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART)); + assertThat(caughtException.getMessage(), containsString( + String.format(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART_TEMPLATE, configuration.getTspSource()) + )); } @Test @@ -303,7 +309,9 @@ public void signatureProfileLtaShouldFailWhenDataLoadersFail() { () -> createSignatureBy(container, SignatureProfile.LTA, pkcs12SignatureToken) ); - assertThat(caughtException.getMessage(), containsString(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART)); + assertThat(caughtException.getMessage(), containsString( + String.format(TECHNICAL_EXCEPTION_TSP_MESSAGE_PART_TEMPLATE, configuration.getTspSource()) + )); } @Test diff --git a/digidoc4j/src/test/resources/testFiles/yaml-configurations/digidoc_test_conf_tsp_source.yaml b/digidoc4j/src/test/resources/testFiles/yaml-configurations/digidoc_test_conf_tsp_source.yaml index 0877be1a8..f745b7643 100644 --- a/digidoc4j/src/test/resources/testFiles/yaml-configurations/digidoc_test_conf_tsp_source.yaml +++ b/digidoc4j/src/test/resources/testFiles/yaml-configurations/digidoc_test_conf_tsp_source.yaml @@ -1,14 +1,14 @@ -TSP_SOURCE: http://demo.sk.ee/tsa +TSP_SOURCE: http://tsa.demo.sk.ee/tsa TSPS: - TSP: TSP_C: EE - TSP_SOURCE: http://demo.sk.ee/tsa + TSP_SOURCE: http://tsa.demo.sk.ee/tsa TSP_KEYSTORE_PATH: tspkeystorepath TSP_KEYSTORE_TYPE: tspkeystoretype TSP_KEYSTORE_PASSWORD: tspkeystorepassword - TSP: TSP_C: LV - TSP_SOURCE: http://demo.sk.ee/tsa + TSP_SOURCE: http://tsa.demo.sk.ee/tsa TSP_KEYSTORE_PATH: tspkeystorepath TSP_KEYSTORE_TYPE: tspkeystoretype TSP_KEYSTORE_PASSWORD: tspkeystorepassword From a71a697abde45d919201532f3be90e4e1a112e06 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Wed, 28 Feb 2024 09:57:29 +0200 Subject: [PATCH 25/35] DD4J-921 Remove the usage of Security Manager from command line utility tests to be able to run them on JDK 18 and higher --- .../java/org/digidoc4j/main/DigiDoc4J.java | 10 +- .../impl/bdoc/asic/TimeStampTokenTest.java | 56 +-- .../impl/pades/PadesValidationTest.java | 15 +- .../org/digidoc4j/main/DigiDoc4JTest.java | 376 +++++++++--------- .../org/digidoc4j/main/TestDigiDoc4JUtil.java | 19 + .../test/util/TestDigiDoc4JUtil.java | 48 --- 6 files changed, 263 insertions(+), 261 deletions(-) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/main/TestDigiDoc4JUtil.java delete mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/util/TestDigiDoc4JUtil.java diff --git a/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java b/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java index 8f4232103..2b31a4c5a 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java +++ b/digidoc4j/src/main/java/org/digidoc4j/main/DigiDoc4J.java @@ -44,6 +44,10 @@ private DigiDoc4J() { * @param args command line arguments */ public static void main(String[] args) { + System.exit(executeAndReturnExitStatus(args)); + } + + static int executeAndReturnExitStatus(String[] args) { try { if (System.getProperty("digidoc4j.mode") == null) { System.setProperty("digidoc4j.mode", "PROD"); @@ -56,7 +60,7 @@ public static void main(String[] args) { DigiDoc4J.logger.error("Utility error (please apply DEBUG level for stacktrace): {}", e.getMessage()); } System.err.print(e.getMessage()); - System.exit(e.getErrorCode()); + return e.getErrorCode(); } catch (Exception e) { if (DigiDoc4J.logger.isDebugEnabled()) { DigiDoc4J.logger.error("Utility error", e); @@ -64,10 +68,10 @@ public static void main(String[] args) { DigiDoc4J.logger.error("Utility error (please apply DEBUG level for stacktrace): {}", e.getMessage()); } System.err.print(e.getMessage()); - System.exit(1); + return 1; } logger.info("Finished running utility method"); - System.exit(0); + return 0; } /** diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java index 703da1fc8..795260432 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/bdoc/asic/TimeStampTokenTest.java @@ -10,12 +10,13 @@ package org.digidoc4j.impl.bdoc.asic; -import java.io.FileInputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - +import eu.europa.esig.dss.enumerations.DigestAlgorithm; +import eu.europa.esig.dss.enumerations.Indication; import eu.europa.esig.dss.enumerations.MimeTypeEnum; +import eu.europa.esig.dss.enumerations.SignatureAlgorithm; +import eu.europa.esig.dss.enumerations.TimestampType; import eu.europa.esig.dss.spi.x509.tsp.TimestampToken; +import eu.europa.esig.dss.utils.Utils; import org.digidoc4j.AbstractTest; import org.digidoc4j.Configuration; import org.digidoc4j.Container; @@ -26,7 +27,6 @@ import org.digidoc4j.impl.asic.TimeStampContainerValidationResult; import org.digidoc4j.impl.asic.manifest.ManifestValidator; import org.digidoc4j.test.TestAssert; -import org.digidoc4j.test.util.TestDigiDoc4JUtil; import org.digidoc4j.test.util.TestSigningUtil; import org.hamcrest.core.StringContains; import org.junit.Assert; @@ -34,12 +34,12 @@ import org.junit.Test; import org.junit.contrib.java.lang.system.SystemOutRule; -import eu.europa.esig.dss.enumerations.DigestAlgorithm; -import eu.europa.esig.dss.enumerations.SignatureAlgorithm; -import eu.europa.esig.dss.utils.Utils; -import eu.europa.esig.dss.enumerations.Indication; -import eu.europa.esig.dss.enumerations.TimestampType; +import java.io.FileInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import static org.digidoc4j.main.TestDigiDoc4JUtil.invokeDigiDoc4jAndReturnExitStatus; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -125,7 +125,8 @@ public void createsContainerWithTstASICS() throws Exception { String fileName = this.getFileBy("asics"); String[] parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-datst", "SHA256", "-tst"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); ZipFile zipFile = new ZipFile(fileName); ZipEntry mimeTypeEntry = zipFile.getEntry(ManifestValidator.MIMETYPE_PATH); ZipEntry manifestEntry = zipFile.getEntry(ManifestValidator.MANIFEST_PATH); @@ -148,11 +149,14 @@ public void tstASICSAddTwoSignatures() throws Exception { String fileName = this.getFileBy("asics"); String[] parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-datst", "SHA256", "-tst"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/dds_колючей стерне.txt", "text/plain", "-datst", "SHA256", "-tst"}; - TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(this.stdOut.getLog(), StringContains.containsString( + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(this.stdOut.getLog(), StringContains.containsString( "This container has already timestamp. Should be no signatures in case of timestamped ASiCS container.")); } @@ -161,11 +165,14 @@ public void tstASICSAddTwoFiles() throws Exception { String fileName = this.getFileBy("asics"); String[] parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-datst", "SHA256", "-tst"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/dds_колючей стерне.txt", "text/plain"}; - TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(this.stdOut.getLog(), StringContains.containsString( + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(this.stdOut.getLog(), StringContains.containsString( "This container has already timestamp. Should be no signatures in case of timestamped ASiCS container.")); } @@ -174,11 +181,14 @@ public void tstASICSAddPKCS12Signature() throws Exception { String fileName = this.getFileBy("asics"); String[] parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-datst", "SHA256", "-tst"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/dds_колючей стерне.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(this.stdOut.getLog(), StringContains.containsString( + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(this.stdOut.getLog(), StringContains.containsString( "This container has already timestamp. Should be no signatures in case of timestamped ASiCS container.")); } @@ -187,9 +197,9 @@ public void asicsAddPKCS12Signature() throws Exception { String fileName = this.getFileBy("asics"); String[] parameters = new String[]{"-in", fileName, "-type", "ASICS", "-add", "src/test/resources/testFiles/helper-files/dds_колючей стерне.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); - Assert.assertThat(this.stdOut.getLog(), StringContains.containsString("Not supported: Not for ASiC-S container")); - + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(this.stdOut.getLog(), StringContains.containsString("Not supported: Not for ASiC-S container")); } /* diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java index f6a8c478c..285f19834 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/pades/PadesValidationTest.java @@ -16,22 +16,20 @@ import org.digidoc4j.ContainerBuilder; import org.digidoc4j.SignatureValidationResult; import org.digidoc4j.exceptions.DigiDoc4JException; -import org.digidoc4j.main.DigiDoc4J; import org.digidoc4j.test.TestAssert; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; -import org.junit.contrib.java.lang.system.ExpectedSystemExit; import org.junit.contrib.java.lang.system.SystemOutRule; +import static org.digidoc4j.main.TestDigiDoc4JUtil.invokeDigiDoc4jAndReturnExitStatus; +import static org.junit.Assert.assertEquals; + /** * Created by Andrei on 20.11.2017. */ public class PadesValidationTest extends AbstractTest { - @Rule - public final ExpectedSystemExit systemExit = ExpectedSystemExit.none(); - @Rule public final SystemOutRule stdOut = new SystemOutRule().enableLog(); @@ -94,8 +92,11 @@ public void padesLTWithCRL_shouldFail() { @Test public void verboseMode() throws Exception { - this.systemExit.expectSystemExitWithStatus(1); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/hello_signed_INCSAVE_signed_EDITED.pdf", "-verify"}); + int result = invokeDigiDoc4jAndReturnExitStatus( + "-in", "src/test/resources/testFiles/invalid-containers/hello_signed_INCSAVE_signed_EDITED.pdf", + "-verify" + ); + assertEquals(1, result); } /* diff --git a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java index 2cd81ff3f..09062b234 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/main/DigiDoc4JTest.java @@ -23,13 +23,11 @@ import org.digidoc4j.impl.ddoc.ConfigManagerInitializer; import org.digidoc4j.test.TestAssert; import org.digidoc4j.test.util.TestCommonUtil; -import org.digidoc4j.test.util.TestDigiDoc4JUtil; import org.digidoc4j.test.util.TestSigningUtil; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; -import org.junit.contrib.java.lang.system.ExpectedSystemExit; import org.junit.contrib.java.lang.system.SystemOutRule; import java.io.File; @@ -37,6 +35,7 @@ import java.nio.file.Paths; import static org.digidoc4j.main.DigiDoc4J.isWarning; +import static org.digidoc4j.main.TestDigiDoc4JUtil.invokeDigiDoc4jAndReturnExitStatus; import static org.digidoc4j.test.matcher.ContainsPattern.containsPattern; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; @@ -45,32 +44,30 @@ public class DigiDoc4JTest extends AbstractTest { - @Rule - public final ExpectedSystemExit systemExit = ExpectedSystemExit.none(); - @Rule public final SystemOutRule stdOut = new SystemOutRule().enableLog(); @Test public void testComposingAndSigningAndAddingDataToSignFile() { - this.systemExit.expectSystemExitWithStatus(0); String containerFile = this.getFileBy("bdoc"); String dataToSignFile = this.getFileBy("ser"); String[] parameters = new String[]{"-in", containerFile, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-dts", dataToSignFile, "text/plain", "-cert", "src/test/resources/testFiles/certs/sign_RSA_from_TEST_of_ESTEIDSK2015.pem"}; - TestDigiDoc4JUtil.call(parameters); - assertTrue(String.format("No data to sign file <%s>", dataToSignFile), new File(dataToSignFile).exists - ()); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + assertTrue(String.format("No data to sign file <%s>", dataToSignFile), new File(dataToSignFile).exists()); assertTrue(String.format("No container file <%s>", containerFile), new File(containerFile).exists()); String signatureFile = this.getFileBy("sig"); parameters = new String[]{"-dts", dataToSignFile, "-sig", signatureFile, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertTrue(String.format("No signature file <%s>", signatureFile), new File(signatureFile).exists()); parameters = new String[]{"-in", containerFile, "-sig", signatureFile, "-dts", dataToSignFile}; - DigiDoc4J.main(parameters); + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); TestAssert.assertContainerIsValid(this.openContainerBy(Paths.get(containerFile))); } @@ -81,7 +78,8 @@ public void createsContainerWithSignatureProfileIsTSAForBDoc() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LTA"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(file); assertEquals(SignatureProfile.LTA, container.getSignatures().get(0).getProfile()); } @@ -93,7 +91,8 @@ public void createsContainerWithSignatureProfileIsTSForBDoc() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LT"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @@ -105,7 +104,8 @@ public void createsContainerWithSignatureProfileIsTSForAsice() { "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LT"}; System.setProperty("digidoc4j.mode", "TEST"); - TestDigiDoc4JUtil.call(params); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(params); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(fileName); assertEquals(SignatureProfile.LT, container.getSignatures().get(0).getProfile()); this.clearGlobalMode(); @@ -119,18 +119,19 @@ public void createsContainerWithSignatureProfileIsBESForBDoc() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "B_BES"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(SignatureProfile.B_BES, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @Test public void createsECCSignatureWithInvalidEncryptionType() { - this.systemExit.expectSystemExitWithStatus(1); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", "src/test/resources/testFiles/p12/ec-digiid.p12", "inno", "-e", "INVALID"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); } @Test @@ -139,7 +140,8 @@ public void createsECCSignature() { String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", "src/test/resources/testFiles/p12/sign_ECC_from_TEST_of_ESTEIDSK2015.p12", "1234", "-e", "ECDSA"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertTrue(ContainerOpener.open(file).validate().isValid()); } @@ -150,28 +152,26 @@ public void createsContainerWithUnknownSignatureProfile() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "Unknown"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(SignatureProfile.LT, ContainerOpener.open(file).getSignatures().get(0).getProfile()); } @Test public void createNewDDocContainer_throwsException() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Not supported: Creating new container is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); String[] parameters = new String[]{"-in", file, "-type", "DDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LT_TM"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Not supported: Creating new container is not supported anymore for DDoc!")); } @Test public void addDataFileToDDocContainer_throwsException() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Not supported: Adding new data files is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); Container container = ContainerOpener.open("src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"); container.saveAsFile(file); @@ -179,7 +179,10 @@ public void addDataFileToDDocContainer_throwsException() { "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-profile", "LT_TM"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Not supported: Adding new data files is not supported anymore for DDoc!")); } @Test @@ -188,7 +191,8 @@ public void createsContainerWithTypeSettingBDoc() { String[] parameters = new String[]{"-in", file, "-type", "BDOC", "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(file); assertAsicEContainer(container); } @@ -197,7 +201,8 @@ public void createsContainerWithTypeSettingBDoc() { public void defaultDigidoc4jModeIsProd() { this.clearGlobalMode(); String[] parameters = new String[]{""}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); } @@ -205,7 +210,8 @@ public void defaultDigidoc4jModeIsProd() { public void commandLineDigidoc4jModeOverwritesDefault() { this.setGlobalMode(Configuration.Mode.PROD); String[] parameters = new String[]{""}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(Configuration.Mode.PROD.name(), System.getProperty("digidoc4j.mode")); } @@ -215,7 +221,8 @@ public void createsContainerWithTypeSettingBasedOnFileExtensionBDoc() { String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(file); assertAsicEContainer(container); } @@ -226,19 +233,20 @@ public void createsContainerWithTypeSettingBDocIfNoSuitableFileExtensionAndNoTyp String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(file); assertAsicEContainer(container); } @Test public void createsContainerAndSignsIt() { - this.systemExit.expectSystemExitWithStatus(0); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); } @Test @@ -248,7 +256,8 @@ public void createContainer_andSignIt_withPkcs11() { String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs11", "/usr/local/lib/opensc-pkcs11.so", "22975", "2"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(file); assertEquals(1, container.getDataFiles().size()); assertEquals("test.txt", container.getDataFiles().get(0).getName()); @@ -258,50 +267,50 @@ public void createContainer_andSignIt_withPkcs11() { @Test public void itShouldNotBePossible_ToSignWithBoth_Pkcs11AndPkcs12() { - this.systemExit.expectSystemExitWithStatus(5); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "text/plain", "-pkcs11", "/usr/local/lib/opensc-pkcs11.so", "01497", "2", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(5, caughtExitStatus); } @Test public void createsContainerAndAddsFileWithoutMimeType() { - this.systemExit.expectSystemExitWithStatus(2); String file = this.getFileBy("bdoc"); String[] parameters = new String[]{"-in", file, "-add", "src/test/resources/testFiles/helper-files/test.txt", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(2, caughtExitStatus); } @Test public void createMultipleSignedContainers_whereInputDirIsFile_shouldThrowException() throws Exception { - this.systemExit.expectSystemExitWithStatus(6); String[] parameters = new String[]{"-inputDir", this.testFolder.newFile("inputFolder").getPath(), "-outputDir", this.testFolder.newFolder("outputFolder").getPath(), "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(6, caughtExitStatus); } @Test public void createMultipleSignedContainers_whereOutputDirIsFile_shouldThrowException() throws Exception { String inputFolder = this.testFolder.newFolder("inputFolder").getPath(); String outputFolder = this.testFolder.newFile("outputFolder").getPath(); - this.systemExit.expectSystemExitWithStatus(6); String[] parameters = new String[]{"-inputDir", inputFolder, "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(6, caughtExitStatus); } @Test public void createMultipleSignedContainers_withEmptyInputDir_shouldDoNothing() throws Exception { - this.systemExit.expectSystemExitWithStatus(0); String[] parameters = new String[]{"-inputDir", this.testFolder.newFolder("inputFolder").getPath(), "-outputDir", this.testFolder.newFolder("outputFolder").getPath(), "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); } @Test @@ -313,7 +322,8 @@ public void createMultipleSignedContainers_withinInputDirectory() throws Excepti FileUtils.writeStringToFile(new File(inputFolder, "thirdDoc.acc"), "Major General Franklin Kirby"); String[] parameters = new String[]{"-inputDir", inputFolder, "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertEquals(3, new File(outputFolder).listFiles().length); TestAssert.assertFolderContainsFile(outputFolder, "firstDoc.bdoc"); TestAssert.assertFolderContainsFile(outputFolder, "secondDoc.bdoc"); @@ -329,7 +339,8 @@ public void createMultipleSignedContainers_withoutOutputDirectory_shouldCreateOu String[] parameters = new String[]{"-inputDir", inputFolder, "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-type", "BDOC"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); File folder = new File(outputFolder); assertTrue(folder.exists()); assertTrue(folder.isDirectory()); @@ -340,14 +351,14 @@ public void createMultipleSignedContainers_withoutOutputDirectory_shouldCreateOu @Test public void createMultipleSignedContainers_withExistingSavedContainers_shouldThrowException() throws Exception { - this.systemExit.expectSystemExitWithStatus(7); String inputFolder = this.testFolder.newFolder("inputFolder").getPath(); String outputFolder = this.testFolder.newFolder("outputFolder").getPath(); FileUtils.writeStringToFile(new File(inputFolder, "firstDoc.txt"), "Hello daddy"); FileUtils.writeStringToFile(new File(outputFolder, "firstDoc.bdoc"), "John Matrix"); String[] parameters = new String[]{"-inputDir", inputFolder, "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(7, caughtExitStatus); } @Test @@ -358,7 +369,8 @@ public void createSignedContainer_forEachFile_withInputDirectoryAndMimeType() th FileUtils.writeStringToFile(new File(inputFolder, "secondDoc.pdf"), "John Matrix"); String[] parameters = new String[]{"-inputDir", inputFolder, "-mimeType", "text/xml", "-outputDir", outputFolder, "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); Container container = ContainerOpener.open(new File(outputFolder, "firstDoc.bdoc").getPath()); assertEquals("text/xml", container.getDataFiles().get(0).getMediaType()); container = ContainerOpener.open(new File(outputFolder, "secondDoc.bdoc").getPath()); @@ -367,124 +379,123 @@ public void createSignedContainer_forEachFile_withInputDirectoryAndMimeType() th @Test public void commandLineInputCausesDigiDoc4JException() { - this.systemExit.expectSystemExitWithStatus(1); - DigiDoc4J.main(new String[]{"-in", "NotFoundFile.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", "NotFoundFile.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); } @Test public void removeFileFromDDocContainer_throwsException() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Not supported: Removing data files is not supported anymore for DDoc!"))); String file = this.getFileBy("ddoc"); Container container = ContainerOpener.open("src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"); container.saveAsFile(file); - DigiDoc4J.main(new String[]{"-in", file, "-remove", "test.txt"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", file, "-remove", "test.txt"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Not supported: Removing data files is not supported anymore for DDoc!")); } @Test public void verifyValidDDoc() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Signature S0 is valid"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("Signature S0 is valid")); } @Test public void verifyDDocWithManifestErrors() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Container contains a file named which is not found in the signature file"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/manifest_validation_error.asice", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/manifest_validation_error.asice", "-verify"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Container contains a file named which is not found in the signature file")); } @Test public void verboseMode() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Opening DDoc container from file: src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify", "-verbose"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc", "-verify", "-verbose"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Opening DDoc container from file: src/test/resources/testFiles/valid-containers/ddoc_for_testing.ddoc")); } @Test public void verifyInValidDDoc() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Signature S0 is not valid"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/changed_digidoc_test.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/changed_digidoc_test.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("Signature S0 is not valid")); } @Test public void verifyDDocWithFatalError() { this.configuration = Configuration.of(Configuration.Mode.TEST); ConfigManagerInitializer.forceInitConfigManager(this.configuration); - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("ERROR: 75"))); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/error75.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/error75.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("ERROR: 75")); } @Test public void verifyDDocWithoutSignature() { - this.systemExit.expectSystemExitWithStatus(1); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/no_signed_doc_no_signature.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/no_signed_doc_no_signature.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); } @Test public void verifyDDocWithEmptyContainer() { - this.systemExit.expectSystemExitWithStatus(1); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); } @Test public void showsUsage() { - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("usage: digidoc4j"))); - DigiDoc4J.main(new String[]{}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("usage: digidoc4j")); } @Test @Ignore("Bug report at https://www.pivotaltracker.com/story/show/107563624") public void verifyBDocWithWarning() throws IOException { - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("The signer's certificate is not supported by SSCD!"))); String[] parameters = new String[]{"-in", "src/test/resources/testFiles/invalid-containers/warning.asice", "-verify", "-warnings"}; FileUtils.copyFile( new File("src/test/resources/testFiles/yaml-configurations/digidoc4j_ForBDocWarningTest.yaml"), new File("src/main/resources/digidoc4j.yaml")); // TODO Whaaaaat? - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("The signer's certificate is not supported by SSCD!")); } @Test public void verifyDDocWithError() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("ERROR: 13 - Format attribute is mandatory!"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/empty_container_no_signature.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("ERROR: 13 - Format attribute is mandatory!")); } @Test public void verifyDDocWithWarning() { this.configuration = Configuration.of(Configuration.Mode.PROD); ConfigManagerInitializer.forceInitConfigManager(this.configuration); - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "Warning: ERROR: 176 - X509IssuerName has none or invalid namespace: null"))); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/testFiles/invalid-containers/warning.ddoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/warning.ddoc", "-verify"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "Warning: ERROR: 176 - X509IssuerName has none or invalid namespace: null")); } @Test @@ -518,10 +529,10 @@ public void testIsWarningWhenWarningIsFound() { @Test public void showVersion() { - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("DigiDoc4j version"))); String[] parameters = {"--version"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("DigiDoc4j version")); } @Test @@ -538,168 +549,169 @@ public void extractDataFileFromDdoc() throws Exception { @Test public void extractDataFile_withIncorrectParameters_shouldThrowException() { - this.systemExit.expectSystemExitWithStatus(2); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/valid-containers/one_signature.bdoc", "-extract", "test.txt"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/valid-containers/one_signature.bdoc", "-extract", "test.txt"); + assertEquals(2, caughtExitStatus); } @Test public void extractDataFile_withNonExistingFile_shouldThrowException() throws Exception { - this.systemExit.expectSystemExitWithStatus(4); String[] parameters = new String[]{"-in", "src/test/resources/testFiles/valid-containers/one_signature.bdoc", "-extract", "notExistingFile.dmc", this.testFolder.newFolder("outputFolder").getPath() + "/output.txt"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(4, caughtExitStatus); } @Test public void verifyContainerWithTstASICS() { String file = "src/test/resources/testFiles/valid-containers/testtimestamp.asics"; String[] parameters = new String[]{"-in", file, "-v"}; - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Container is valid"))); - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("Container is valid")); } @Test public void verifyValidBdocMid() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString("Signature S0 is valid"))); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("Signature S0 is valid")); } @Test public void verifyValidBdocMidWithDss() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Validation was successful. Container is valid"))); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_mid.bdoc", "-v"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid")); } @Test public void verifyValidBdocEid() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Signature S0 is valid"))); String[] parameters = new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_eid.bdoc", "-v"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Signature S0 is valid")); } @Test public void verifyValidBdocEidWithDss() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Validation was successful. Container is valid"))); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_eid.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/valid-containers/valid_prod_bdoc_eid.bdoc", "-v"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid")); } @Test public void verifyEdoc() throws Exception { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> { - assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); - assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); - assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); - assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); - assertThat(stdOut.getLog(), containsString("Signature S1 is not valid")); - }); String outputFolder = this.testFolder.newFolder("outputFolder").getPath(); String[] parameters = new String[]{"-in", "src/test/resources/prodFiles/invalid-containers/edoc2_lv-eId_sha256.edoc", "-v", "-r", outputFolder}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); + assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); + assertThat(stdOut.getLog(), containsString("Signature S1 is not valid")); } @Test public void verifyEdocWithDss() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> { - assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); - assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); - assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); - assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); - assertThat(stdOut.getLog(), containsString("Validation finished. Container is NOT valid!")); - }); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/prodFiles/invalid-containers/edoc2_lv-eId_sha256.edoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/invalid-containers/edoc2_lv-eId_sha256.edoc", "-v"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString("OCSP response production time is before timestamp time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - Timestamp time is after OCSP response production time")); + assertThat(stdOut.getLog(), containsString("Error: (Signature ID: S1) - The certificate is not related to a TSA/QTST!")); + assertThat(stdOut.getLog(), containsString("Signature has 2 validation errors")); + assertThat(stdOut.getLog(), containsString("Validation finished. Container is NOT valid!")); } @Test public void verifyValidTestBdoc() { - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Signature id-c0be584463a9dca56c3e9500a3d17e75 is valid"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Signature id-c0be584463a9dca56c3e9500a3d17e75 is valid")); } @Test public void verifyValidTestBdocWithDss() { - this.systemExit.expectSystemExitWithStatus(0); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Validation was successful. Container is valid"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/valid-containers/bdoc-tm-with-large-data-file.bdoc", "-v"); + assertEquals(0, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Validation was successful. Container is valid")); } @Test public void verifyInvalidTestBdoc() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Signature S1 is not valid"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Signature S1 is not valid")); } @Test public void verifyInvalidTestBdocWithDss() { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), - containsString("Validation finished. Container is NOT valid!"))); - DigiDoc4J.main(new String[]{"-in", - "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/testFiles/invalid-containers/two_signatures_one_invalid.bdoc", "-v"); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), + containsString("Validation finished. Container is NOT valid!")); } @Test @Ignore // unstable result public void verifyValidBDocUnsafeInteger() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/InvestorToomas.bdoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/valid-containers/InvestorToomas.bdoc", "-verify"); + assertEquals(0, caughtExitStatus); } @Test public void verifyValidBDocUnsafeIntegerSystemParam() { this.setGlobalMode(Configuration.Mode.PROD); - this.systemExit.expectSystemExitWithStatus(0); System.setProperty(Constant.System.ORG_BOUNCYCASTLE_ASN1_ALLOW_UNSAFE_INTEGER, "true"); - DigiDoc4J.main(new String[]{"-in", "src/test/resources/prodFiles/valid-containers/InvestorToomas.bdoc", "-verify"}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", + "src/test/resources/prodFiles/valid-containers/InvestorToomas.bdoc", "-verify"); + assertEquals(0, caughtExitStatus); } @Test public void verifyBDocFullReport() throws Exception { - this.systemExit.expectSystemExitWithStatus(1); - this.systemExit.checkAssertionAfterwards(() -> assertThat(stdOut.getLog(), containsString( - "The certificate chain for revocation data is not trusted, it does not contain a trust anchor"))); String outputFolder = this.testFolder.newFolder("outputFolder").getPath(); String[] parameters = new String[]{"-in", "src/test/resources/testFiles/invalid-containers/tundmatuocsp.asice", "-v", "-r", outputFolder, "-showerrors"}; - DigiDoc4J.main(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(1, caughtExitStatus); + assertThat(stdOut.getLog(), containsString( + "The certificate chain for revocation data is not trusted, it does not contain a trust anchor")); } private void assertExtractingDataFile(String containerPath, String fileToExtract) throws IOException { final String outputPath = String.format("%s%s%s", this.testFolder.newFolder("outputFolder").getPath(), File.pathSeparator, "output.txt"); - this.systemExit.expectSystemExitWithStatus(0); - DigiDoc4J.main(new String[]{"-in", containerPath, "-extract", fileToExtract, outputPath}); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus("-in", containerPath, "-extract", fileToExtract, outputPath); + assertEquals(0, caughtExitStatus); TestCommonUtil.sleepInSeconds(1); assertTrue(new File(outputPath).exists()); } @@ -712,11 +724,13 @@ public void createAndValidateDetachedXades() { "-digFile", "test.txt", "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "text/plain", "-pkcs12", TestSigningUtil.TEST_PKI_CONTAINER, TestSigningUtil.TEST_PKI_CONTAINER_PASSWORD, "-sigOutputPath", xadesSignaturePath}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); parameters = new String[]{"-xades", "-digFile", "test.txt", "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "text/plain","-sigInputPath", xadesSignaturePath}; - TestDigiDoc4JUtil.call(parameters); + caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertThat(stdOut.getLog(), containsPattern("Signature id-[a-z0-9]+ is valid")); new File(xadesSignaturePath).delete(); @@ -727,8 +741,9 @@ public void validateDetachedXades_withWrongDigestFile_shouldFail() { String[] parameters = new String[]{"-xades", "-digFile", "test.txt", "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "text/plain", "-sigInputPath", "src/test/resources/testFiles/xades/test-bdoc-ts.xml"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(0, caughtExitStatus); assertThat(stdOut.getLog(), containsString("The reference data object is not intact!")); } @@ -737,8 +752,9 @@ public void validateDetachedXades_mimeTypeNotSet_shouldFail() { String[] parameters = new String[]{"-xades", "-digFile", "test.txt", "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg", "-sigInputPath", "src/test/resources/testFiles/xades/test-bdoc-ts.xml"}; - TestDigiDoc4JUtil.call(parameters); + int caughtExitStatus = invokeDigiDoc4jAndReturnExitStatus(parameters); + assertEquals(2, caughtExitStatus); assertThat(stdOut.getLog(), containsString("Problem with given parameters")); } } diff --git a/digidoc4j/src/test/java/org/digidoc4j/main/TestDigiDoc4JUtil.java b/digidoc4j/src/test/java/org/digidoc4j/main/TestDigiDoc4JUtil.java new file mode 100644 index 000000000..eb0a367f2 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/main/TestDigiDoc4JUtil.java @@ -0,0 +1,19 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.main; + +public final class TestDigiDoc4JUtil { + + public static int invokeDigiDoc4jAndReturnExitStatus(String... params) { + return DigiDoc4J.executeAndReturnExitStatus(params); + } + +} diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDigiDoc4JUtil.java b/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDigiDoc4JUtil.java deleted file mode 100644 index f45128a58..000000000 --- a/digidoc4j/src/test/java/org/digidoc4j/test/util/TestDigiDoc4JUtil.java +++ /dev/null @@ -1,48 +0,0 @@ -/* DigiDoc4J library -* -* This software is released under either the GNU Library General Public -* License (see LICENSE.LGPL). -* -* Note that the only valid version of the LGPL license as far as this -* project is concerned is the original GNU Library General Public License -* Version 2.1, February 1999 -*/ - -package org.digidoc4j.test.util; - -import java.security.Permission; - -import org.digidoc4j.main.DigiDoc4J; -import org.digidoc4j.main.DigiDoc4JUtilityException; - -/** - * Created by Janar Rahumeel (CGI Estonia) - */ - -public final class TestDigiDoc4JUtil { - - private static final SecurityManager preventExitSecurityManager = new SecurityManager() { - - @Override - public void checkPermission(Permission permission) { - } - - @Override - public void checkExit(int status) { - super.checkExit(status); - throw new DigiDoc4JUtilityException(status, "Preventing system exit"); - } - - }; - - public static void call(String[] params) { - SecurityManager securityManager = System.getSecurityManager(); - System.setSecurityManager(TestDigiDoc4JUtil.preventExitSecurityManager); - try { - DigiDoc4J.main(params); - } catch (DigiDoc4JUtilityException ignore) { - } - System.setSecurityManager(securityManager); - } - -} From 20cc92ae2bcc4e9f0a07e40b936f20ab0b5ae252 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Wed, 28 Feb 2024 13:36:06 +0200 Subject: [PATCH 26/35] DD4J-921 On Java 18 and higher, disable FileWritingOperationsTest which uses Security Manager --- .../digidoc4j/FileWritingOperationsTest.java | 29 +++++++++ .../digidoc4j/test/util/JreVersionHelper.java | 62 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 digidoc4j/src/test/java/org/digidoc4j/test/util/JreVersionHelper.java diff --git a/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java b/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java index 3d122de60..dbf0a91d9 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/FileWritingOperationsTest.java @@ -14,8 +14,12 @@ import org.digidoc4j.test.RestrictedExternalResourceRule; import org.digidoc4j.test.RestrictedExternalResourceRule.FileWritingRestrictedException; import org.digidoc4j.test.TestAssert; +import org.digidoc4j.test.util.JreVersionHelper; import org.digidoc4j.test.util.TestDataBuilderUtil; +import org.hamcrest.Matchers; import org.junit.Assert; +import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; @@ -28,12 +32,37 @@ public class FileWritingOperationsTest extends AbstractTest { + /** + * {@link RestrictedExternalResourceRule} uses {@code SecurityManager} to achieve its goal. + * Since Java 17, Security Manager and its related API-s are deprecated for removal. + * Since Java 18, dynamically installing a Security Manager is disabled by default unless the end user has explicitly + * opted to allow it. + * https://openjdk.org/jeps/411 + * TODO (DD4J-992): Find an alternative to using Security Manager for limiting filesystem access. + */ @Rule public RestrictedExternalResourceRule rule = new RestrictedExternalResourceRule( new File(System.getProperty("java.io.tmpdir") + File.separator + "dss-cache-tsl" + File.separator).getPath(), new File(System.getProperty("java.io.tmpdir") + File.separator + "temp-tsl-keystore" + File.separator).getPath() ); + /** + * Checks the JVM version and disables this test class dynamically if it is run on Java 18+. + * TODO (DD4J-992): Remove this after an alternative to using Security Manager has been found. + */ + @BeforeClass + public static void checkIfShouldExecute() { + Integer currentJreMajorVersion = JreVersionHelper.getCurrentMajorVersionIfAvailable(); + if (currentJreMajorVersion == null) { + return; // Do not skip the tests if JVM version could not be determined + } + Assume.assumeThat( + "Only run on JDK 17 or lower", + currentJreMajorVersion, + Matchers.lessThan(18) + ); + } + @Test(expected = FileWritingRestrictedException.class) public void writingToFileIsNotAllowed() throws IOException { File.createTempFile("test", "test"); diff --git a/digidoc4j/src/test/java/org/digidoc4j/test/util/JreVersionHelper.java b/digidoc4j/src/test/java/org/digidoc4j/test/util/JreVersionHelper.java new file mode 100644 index 000000000..c0ae33009 --- /dev/null +++ b/digidoc4j/src/test/java/org/digidoc4j/test/util/JreVersionHelper.java @@ -0,0 +1,62 @@ +/* DigiDoc4J library + * + * This software is released under either the GNU Library General Public + * License (see LICENSE.LGPL). + * + * Note that the only valid version of the LGPL license as far as this + * project is concerned is the original GNU Library General Public License + * Version 2.1, February 1999 + */ + +package org.digidoc4j.test.util; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Method; + +/** + * A helper class for determining the current JRE version for testing purposes. + * TODO (DD4J-993): Consider removing this class when DD4J unit tests are migrated to JUnit5. + * JUnit5 has annotations for conditional test execution based on JRE versions. + * TODO: Consider removing this class when the minimum supported version of DD4J is raised to Java 9+. + * In Java 9+, {@code java.lang.Runtime.version().major()} can be called directly. + */ +public final class JreVersionHelper { + + private static final Logger LOGGER = LoggerFactory.getLogger(JreVersionHelper.class); + + public static Integer getCurrentMajorVersionIfAvailable() { + String versionString = System.getProperty("java.version"); + if (StringUtils.startsWith(versionString, "1.8")) { + return 8; + } + + try { + // java.lang.Runtime.version() is a static method available on Java 9+ + // that returns an instance of java.lang.Runtime.Version which has the + // following method: public int major() + Method versionMethod = Runtime.class.getMethod("version"); + Object version = makeAccessible(versionMethod).invoke(null); + Method majorMethod = version.getClass().getMethod("major"); + return (int) makeAccessible(majorMethod).invoke(version); + } catch (Exception ex) { + LOGGER.warn("Failed to determine the current JRE version via java.lang.Runtime.Version.", ex); + } + + if (StringUtils.isBlank(versionString)) { + LOGGER.warn("JVM system property 'java.version' is undefined. Unable to determine the current JRE version."); + } + + return null; + } + + private static Method makeAccessible(Method method) { + if (!method.isAccessible()) { + method.setAccessible(true); + } + return method; + } + +} From 8ba89ad49c210f9af743e08721477f343b294331 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 29 Feb 2024 09:53:10 +0200 Subject: [PATCH 27/35] DD4J-989 Update dependencies --- digidoc4j/pom.xml | 18 +++++++++++------- pom.xml | 12 ++++++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index 5d07f928e..eee5057e7 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -23,24 +23,24 @@ org.digidoc4j.dss - 1.5.0 + 1.6.0 4.4 2.15.1 3.14.0 2.4.3 6.0.d4j.1 2.2 - 5.3 - 2.15.2 + 5.3.1 + 2.16.1 3.0.2 4.13.2 2.4 1.3.14 4.11.0 - 2.1 + 2.2 1.19.0 - 2.35.0 - 3.0.3 + 2.35.2 + 3.0.4 1.6 1.4 @@ -53,7 +53,7 @@ 0.15.3 3.0.1 3.3.1 - 3.5.0 + 3.5.2 1.6.13 ${project.build.directory}/build/util @@ -327,6 +327,10 @@ ${wiremock.version} test + + com.jayway.jsonpath + json-path + commons-fileupload commons-fileupload diff --git a/pom.xml b/pom.xml index 61746e99f..1e9b6bb7c 100644 --- a/pom.xml +++ b/pom.xml @@ -143,15 +143,15 @@ 1.8 1.76 - 1.16.0 + 1.16.1 2.0.12 - 8.3.1 - 0.8.10 - 3.11.0 - 3.5.0 + 8.4.3 + 0.8.11 + 3.12.1 + 3.6.3 3.3.0 - 3.1.2 + 3.2.5 none From 79adae68c0008c4f62ccad88c2dfad364b68aa77 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Thu, 29 Feb 2024 16:29:43 +0200 Subject: [PATCH 28/35] DD4J-989 Update Maven wrapper --- .mvn/wrapper/maven-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 06d5d2f8b..83fff6d6e 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1 +1 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip \ No newline at end of file +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip \ No newline at end of file From 714581efd394914ffe58a8de93577869dc4b4fcd Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 4 Mar 2024 16:19:11 +0200 Subject: [PATCH 29/35] DD4J-962 Update external service URL-s in README --- README.md | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f09b24dde..5d6c9cd57 100644 --- a/README.md +++ b/README.md @@ -68,11 +68,19 @@ The support for creating BDOC-specific **time-mark** signatures was removed sinc # Requirements * Java **8** or higher (since version 4.0.0-RC.1) -* Internet access to external verification services - * OCSP (Online Certificate Status Protocol) - http://ocsp.sk.ee - * EU TSL (European Commission's Trusted Status List) - https://ec.europa.eu/information_society/policy/esignature/trusted-list/tl-mp.xml - * All the EU member states' TL servers referred in the EU TSL. Note that this list may change. (e.g. https://sr.riik.ee/tsl/estonian-tsl.xml, https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml, https://www.viestintavirasto.fi/attachments/TSL-Ficora.xml etc.) - * TSA (Time Stamping Authority) - http://tsa.sk.ee +* Internet access to external services + * OCSP (Online Certificate Status Protocol) - AIA OCSP URL from signer's certificate or default fallback value + http://ocsp.sk.ee (for more information, see + [here](https://github.com/open-eid/digidoc4j/wiki/Questions-&-Answers#usage-of-aia-ocsp-for-timestamp-based-asic-e-containers-since-release-310)) + * EU TSL (European Commission's Trusted Status List) - default value https://ec.europa.eu/tools/lotl/eu-lotl.xml (for + more information, see [here](https://github.com/open-eid/digidoc4j/wiki/Examples-of-using-it#using-configuration)) + * All the EU member states' TL servers referred in the EU TSL. Note that this list may change. + (e.g. https://sr.riik.ee/tsl/estonian-tsl.xml, https://sedediatid.mineco.gob.es/Prestadores/TSL/TSL.xml, https://dp.trustedlist.fi/fi-tl.xml etc.) + * TSA (Time Stamping Authority) - default value http://tsa.sk.ee (for more information, see + [here](https://github.com/open-eid/digidoc4j/wiki/Examples-of-using-it#using-configuration)) + * AIA (Authority Information Access) CA issuers - missing certificates of certificate chains downloaded from the URLs + referred to in existing certificates + * Signature Policy documents, if applicable (e.g. https://www.sk.ee/repository/bdoc-spec21.pdf) ## Maven You can use the library as a Maven dependency from the Maven Central (http://mvnrepository.com/artifact/org.digidoc4j/digidoc4j) From f5daa5ee622941fa28b06a1a09a2307985da53b6 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Mon, 4 Mar 2024 16:20:05 +0200 Subject: [PATCH 30/35] DD4J-962 Add version 5.3.0 release notes --- RELEASE-NOTES.txt | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt index f376279c5..741cacca4 100644 --- a/RELEASE-NOTES.txt +++ b/RELEASE-NOTES.txt @@ -1,6 +1,31 @@ DigiDoc4J Java library release notes ------------------------------------ +Release 5.3.0 +------------------ +Summary of the major changes since 5.2.0 +------------------------------------------ +* DSS version update to 6.0 (sd-dss.6.0.d4j.1), previously used DSS 5.11.1. Check changes in DSS here: https://github.com/esig/dss/releases + DSS update has caused the following notable changes to dependencies: + - Migration from Javax to Jakarta namespace + - JAXB dependencies updated from 2.3.X to 3.0.X + - Apache Santuario xmlsec updated from 2.3.X to 3.0.X + - Bouncy Castle updated from jdk15on:1.70 to jdk18on:1.76 + - SLF4J updated from 1.7.X to 2.0.X +* Prefer to use AIA OCSP by default on signature creation + - In DigiDoc4J command line utility, deprecated -aiaocsp parameter and added new -noaiaocsp parameter +* TEST mode default timestamp URL updated to http://tsa.demo.sk.ee/tsa +* Changes in validation policies +* Updated dependencies + +Known issues +------------ +* At the time of release, the newest supported Bouncy Castle version is 1.76 + Bouncy Castle version 1.77 causes OCSP response parsing to fail +* We have noticed a slight increase in TSL loading times due to pivot LOTL support +* We have noticed a decrease in performance with the introduction of properly accessing AIA certificate resources +* Opening a container that contains signatures, triggers TSL loading (TSL lazy loading does not work as expected) + Release 5.2.0 ------------------ Summary of the major changes since 5.1.0 From 5653e55363fe0b67aff6b7ce2bc0e947e5775749 Mon Sep 17 00:00:00 2001 From: Heiti Tobi Date: Tue, 12 Mar 2024 09:59:50 +0200 Subject: [PATCH 31/35] DD4J-987 Align constraints accordance with DSS 6.0 --- .../src/main/resources/conf/constraint.xml | 226 ++++++++++++++++++ .../main/resources/conf/test_constraint.xml | 226 ++++++++++++++++++ 2 files changed, 452 insertions(+) diff --git a/digidoc4j/src/main/resources/conf/constraint.xml b/digidoc4j/src/main/resources/conf/constraint.xml index 7e84e1381..aef61dbff 100644 --- a/digidoc4j/src/main/resources/conf/constraint.xml +++ b/digidoc4j/src/main/resources/conf/constraint.xml @@ -14,10 +14,21 @@ + + + + + + + + + + + @@ -27,9 +38,29 @@ + nonRepudiation + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -65,7 +96,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -121,11 +178,14 @@ + + + + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + + + @@ -171,7 +255,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -180,11 +290,15 @@ + + + + + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -248,7 +393,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -304,13 +475,17 @@ + + + + @@ -321,8 +496,26 @@ + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + 1.3.6.1.5.5.7.48.1.5 + + + @@ -354,7 +547,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -408,6 +627,13 @@ + + + + + + + diff --git a/digidoc4j/src/main/resources/conf/test_constraint.xml b/digidoc4j/src/main/resources/conf/test_constraint.xml index 7e84e1381..aef61dbff 100644 --- a/digidoc4j/src/main/resources/conf/test_constraint.xml +++ b/digidoc4j/src/main/resources/conf/test_constraint.xml @@ -14,10 +14,21 @@ + + + + + + + + + + + @@ -27,9 +38,29 @@ + nonRepudiation + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -65,7 +96,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -121,11 +178,14 @@ + + + + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + + + @@ -171,7 +255,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -180,11 +290,15 @@ + + + + + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -248,7 +393,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -304,13 +475,17 @@ + + + + @@ -321,8 +496,26 @@ + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + 1.3.6.1.5.5.7.48.1.5 + + + @@ -354,7 +547,33 @@ + + + + + + keyCertSign + + + + + 2.5.29.15 + 2.5.29.32 + 2.5.29.17 + 2.5.29.19 + 2.5.29.30 + 2.5.29.36 + 2.5.29.37 + 2.5.29.31 + 2.5.29.54 + 1.3.6.1.5.5.7.1.3 + + + + 1.3.6.1.5.5.7.48.1.5 + + @@ -408,6 +627,13 @@ + + + + + + + From 5bd594e4cbd4b7152d7af9f59f2a86f24a0c7c71 Mon Sep 17 00:00:00 2001 From: Heiti Tobi Date: Fri, 15 Mar 2024 14:28:02 +0200 Subject: [PATCH 32/35] DD4J-987 Add SigningCertificateRefersCertificateChain constraint accordance with DSS 6.0 --- digidoc4j/src/main/resources/conf/constraint.xml | 3 +++ digidoc4j/src/main/resources/conf/test_constraint.xml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/digidoc4j/src/main/resources/conf/constraint.xml b/digidoc4j/src/main/resources/conf/constraint.xml index aef61dbff..5b7af8796 100644 --- a/digidoc4j/src/main/resources/conf/constraint.xml +++ b/digidoc4j/src/main/resources/conf/constraint.xml @@ -178,6 +178,7 @@ + @@ -291,6 +292,7 @@ + @@ -475,6 +477,7 @@ + diff --git a/digidoc4j/src/main/resources/conf/test_constraint.xml b/digidoc4j/src/main/resources/conf/test_constraint.xml index aef61dbff..5b7af8796 100644 --- a/digidoc4j/src/main/resources/conf/test_constraint.xml +++ b/digidoc4j/src/main/resources/conf/test_constraint.xml @@ -178,6 +178,7 @@ + @@ -291,6 +292,7 @@ + @@ -475,6 +477,7 @@ + From f3955a0b979c25820211c7bc5ec539850d6bdc81 Mon Sep 17 00:00:00 2001 From: Heiti Tobi Date: Fri, 15 Mar 2024 15:02:18 +0200 Subject: [PATCH 33/35] DD4J-987 On new added FAIL level constraints set level to IGNORE --- .../src/main/resources/conf/constraint.xml | 58 +++++++++---------- .../main/resources/conf/test_constraint.xml | 58 +++++++++---------- 2 files changed, 58 insertions(+), 58 deletions(-) diff --git a/digidoc4j/src/main/resources/conf/constraint.xml b/digidoc4j/src/main/resources/conf/constraint.xml index 5b7af8796..f8f7a1362 100644 --- a/digidoc4j/src/main/resources/conf/constraint.xml +++ b/digidoc4j/src/main/resources/conf/constraint.xml @@ -19,10 +19,10 @@ - + - - + + @@ -57,10 +57,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -96,12 +96,12 @@ - + - - - + + + keyCertSign @@ -119,10 +119,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -323,10 +323,10 @@ - + - - + + @@ -338,7 +338,7 @@ - + @@ -359,10 +359,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -398,9 +398,9 @@ - - - + + + keyCertSign @@ -418,10 +418,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -499,7 +499,7 @@ - + @@ -518,7 +518,7 @@ 1.3.6.1.5.5.7.48.1.5 - + @@ -553,9 +553,9 @@ - - - + + + keyCertSign @@ -573,10 +573,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + diff --git a/digidoc4j/src/main/resources/conf/test_constraint.xml b/digidoc4j/src/main/resources/conf/test_constraint.xml index 5b7af8796..f8f7a1362 100644 --- a/digidoc4j/src/main/resources/conf/test_constraint.xml +++ b/digidoc4j/src/main/resources/conf/test_constraint.xml @@ -19,10 +19,10 @@ - + - - + + @@ -57,10 +57,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -96,12 +96,12 @@ - + - - - + + + keyCertSign @@ -119,10 +119,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -323,10 +323,10 @@ - + - - + + @@ -338,7 +338,7 @@ - + @@ -359,10 +359,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -398,9 +398,9 @@ - - - + + + keyCertSign @@ -418,10 +418,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + @@ -499,7 +499,7 @@ - + @@ -518,7 +518,7 @@ 1.3.6.1.5.5.7.48.1.5 - + @@ -553,9 +553,9 @@ - - - + + + keyCertSign @@ -573,10 +573,10 @@ 1.3.6.1.5.5.7.1.3 - + 1.3.6.1.5.5.7.48.1.5 - + From 6c07c4504d56b855d146415f954431989aa1b567 Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 19 Mar 2024 08:32:46 +0200 Subject: [PATCH 34/35] DD4J-962 Replace expired certificate in OCSP source test --- .../test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java b/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java index 7837d5125..d95f87c03 100644 --- a/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java +++ b/digidoc4j/src/test/java/org/digidoc4j/impl/SKOnlineOCSPSourceTest.java @@ -70,9 +70,9 @@ public class SKOnlineOCSPSourceTest extends AbstractTest { @Test public void getValidCertificateOCSPToken() throws CertificateEncodingException { CommonOCSPCertificateSource certificateSource = new CommonOCSPCertificateSource(); - certificateSource.addCertificate(new CertificateToken(openX509Certificate(Paths.get("src/test/resources/testFiles/certs/EE_Certification_Centre_Root_CA.pem.crt")))); + certificateSource.addCertificate(new CertificateToken(openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TESTofEECertificationCentreRootCA.crt")))); - X509Certificate subjectCertificate = openX509Certificate(Paths.get("src/test/resources/testFiles/certs/ESTEID-SK_2011.pem.crt")); + X509Certificate subjectCertificate = openX509Certificate(Paths.get("src/test/resources/testFiles/certs/TEST_of_ESTEID-SK_2015.pem.crt")); CertificateToken issuerCertificateToken = getIssuerCertificateToken(subjectCertificate, certificateSource); SKOnlineOCSPSource ocspSource = constructOCSPSource(); From d706bdf17e7a86910a78eae4c6f3731d8640fbba Mon Sep 17 00:00:00 2001 From: Risto Seene Date: Tue, 19 Mar 2024 08:34:30 +0200 Subject: [PATCH 35/35] DD4J-962 Update version to 5.3.0 --- ddoc4j/pom.xml | 4 ++-- digidoc4j/pom.xml | 6 +++--- digidoc4j/src/main/java/org/digidoc4j/Version.java | 2 +- pom.xml | 2 +- publish.sh | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ddoc4j/pom.xml b/ddoc4j/pom.xml index 5b9ee861e..3e0ce85a5 100644 --- a/ddoc4j/pom.xml +++ b/ddoc4j/pom.xml @@ -5,7 +5,7 @@ ddoc4j jar - 5.3.0-SNAPSHOT + 5.3.0 DDoc4J DDoc4J is Java Library for validating DDOC documents. It's not recommended to use it directly but rather through DigiDoc4J's API. @@ -14,7 +14,7 @@ digidoc4j-parent org.digidoc4j - 5.3.0-SNAPSHOT + 5.3.0 diff --git a/digidoc4j/pom.xml b/digidoc4j/pom.xml index eee5057e7..784f33321 100644 --- a/digidoc4j/pom.xml +++ b/digidoc4j/pom.xml @@ -6,7 +6,7 @@ digidoc4j jar - 5.3.0-SNAPSHOT + 5.3.0 DigiDoc4j DigiDoc4j is a Java library for digitally signing documents and creating digital signature containers @@ -17,7 +17,7 @@ digidoc4j-parent org.digidoc4j - 5.3.0-SNAPSHOT + 5.3.0 @@ -74,7 +74,7 @@ ddoc4j org.digidoc4j - 5.3.0-SNAPSHOT + 5.3.0 diff --git a/digidoc4j/src/main/java/org/digidoc4j/Version.java b/digidoc4j/src/main/java/org/digidoc4j/Version.java index 01b722c0a..c6d86f9d3 100644 --- a/digidoc4j/src/main/java/org/digidoc4j/Version.java +++ b/digidoc4j/src/main/java/org/digidoc4j/Version.java @@ -11,5 +11,5 @@ package org.digidoc4j; public class Version { - public static final String VERSION = "5.3.0-SNAPSHOT"; + public static final String VERSION = "5.3.0"; } diff --git a/pom.xml b/pom.xml index 1e9b6bb7c..3882e0842 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.digidoc4j digidoc4j-parent - 5.3.0-SNAPSHOT + 5.3.0 pom DigiDoc4J parent diff --git a/publish.sh b/publish.sh index cce897b7d..905fc6544 100755 --- a/publish.sh +++ b/publish.sh @@ -1,6 +1,6 @@ #!/bin/bash -version="5.3.0-SNAPSHOT" +version="5.3.0" staging_url="https://oss.sonatype.org/service/local/staging/deploy/maven2/" repositoryId="ossrh"