diff --git a/.github/workflows/ci-dependency-check.yml b/.github/workflows/ci-dependency-check.yml index 3031e3c9..47996d71 100644 --- a/.github/workflows/ci-dependency-check.yml +++ b/.github/workflows/ci-dependency-check.yml @@ -4,9 +4,9 @@ on: - cron: '48 02 * * 0' # Each Sunday at 02:48 UTC pull_request: types: - - opened - - synchronize - - reopened + - opened + - synchronize + - reopened workflow_dispatch: jobs: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 79fa733d..3aa4ba9f 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -21,22 +21,22 @@ jobs: language: [ 'java' ] steps: - - name: Checkout repository - uses: actions/checkout@v3 - - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - - - name: Setup Java 11 - uses: actions/setup-java@v2 - with: - java-version: 11 - distribution: adopt - - - name: Build - run: >- + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + + - name: Setup Java 11 + uses: actions/setup-java@v2 + with: + java-version: 11 + distribution: adopt + + - name: Build + run: >- mvn clean package --batch-mode --file ./pom.xml @@ -44,9 +44,9 @@ jobs: --define app.packages.username="${APP_PACKAGES_USERNAME}" --define app.packages.password="${APP_PACKAGES_PASSWORD}" -DskipTests=true; - env: - APP_PACKAGES_USERNAME: ${{ github.actor }} - APP_PACKAGES_PASSWORD: ${{ secrets.GITHUB_TOKEN }} + env: + APP_PACKAGES_USERNAME: ${{ github.actor }} + APP_PACKAGES_PASSWORD: ${{ secrets.GITHUB_TOKEN }} - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.grenrc.js b/.grenrc.js index e50821ee..c788f149 100644 --- a/.grenrc.js +++ b/.grenrc.js @@ -1,30 +1,30 @@ module.exports = { - "dataSource": "prs", - "prefix": "", - "onlyMilestones": false, - "groupBy": { - "Enhancements": [ - "enhancement", - "internal" - ], - "Bug Fixes": [ - "bug" - ], - "Documentation": [ - "documentation" - ], - "Others": [ - "other" - ] - }, - "changelogFilename": "CHANGELOG.md", - "template": { - commit: ({ message, url, author, name }) => `- [${message}](${url}) - ${author ? `@${author}` : name}`, - issue: "- {{name}} [{{text}}]({{url}})", - noLabel: "other", - group: "\n#### {{heading}}\n", - changelogTitle: "# Changelog\n\n", - release: "## {{release}} ({{date}})\n{{body}}", - releaseSeparator: "\n---\n\n" - } + "dataSource": "prs", + "prefix": "", + "onlyMilestones": false, + "groupBy": { + "Enhancements": [ + "enhancement", + "internal" + ], + "Bug Fixes": [ + "bug" + ], + "Documentation": [ + "documentation" + ], + "Others": [ + "other" + ] + }, + "changelogFilename": "CHANGELOG.md", + "template": { + commit: ({message, url, author, name}) => `- [${message}](${url}) - ${author ? `@${author}` : name}`, + issue: "- {{name}} [{{text}}]({{url}})", + noLabel: "other", + group: "\n#### {{heading}}\n", + changelogTitle: "# Changelog\n\n", + release: "## {{release}} ({{date}})\n{{body}}", + releaseSeparator: "\n---\n\n" + } } diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index e1811e07..e8ae2ed2 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,4 +1,3 @@ - # Contributor Covenant Code of Conduct ## Our Pledge @@ -59,8 +58,8 @@ representative at an online or offline event. ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at [opensource@telekom.de](mailto:opensource@telekom.de). All complaints will be reviewed and investigated promptly and fairly. @@ -107,7 +106,7 @@ Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an +standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d97f3776..6992aff4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,9 +4,11 @@ All members of the project community must abide by the [Contributor Covenant, version 2.0](CODE_OF_CONDUCT.md). Only by respecting each other can we develop a productive, collaborative community. -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting [opensource@telekom.de](mailto:opensource@telekom.de) and/or a project maintainer. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by +contacting [opensource@telekom.de](mailto:opensource@telekom.de) and/or a project maintainer. -We appreciate your courtesy of avoiding political questions here. Issues which are not related to the project itself will be closed by our community managers. +We appreciate your courtesy of avoiding political questions here. Issues which are not related to the project itself +will be closed by our community managers. ## Engaging in our project @@ -14,19 +16,25 @@ We use GitHub to manage reviews of pull requests. * If you are a new contributor, see: [Steps to Contribute](#steps-to-contribute) -* If you have a trivial fix or improvement, go ahead and create a pull request, addressing (with `@...`) a suitable maintainer of this repository (see [CODEOWNERS](CODEOWNERS) of the repository you want to contribute to) in the description of the pull request. +* If you have a trivial fix or improvement, go ahead and create a pull request, addressing (with `@...`) a suitable + maintainer of this repository (see [CODEOWNERS](CODEOWNERS) of the repository you want to contribute to) in the + description of the pull request. -* If you plan to do something more involved, please reach out to us and send an [email](mailto:opensource@telekom.de). This will avoid unnecessary work and surely give you and us a good deal of inspiration. +* If you plan to do something more involved, please reach out to us and send an [email](mailto:opensource@telekom.de). + This will avoid unnecessary work and surely give you and us a good deal of inspiration. -* Relevant coding style guidelines are available in the respective sub-repositories as they are programming language-dependent. +* Relevant coding style guidelines are available in the respective sub-repositories as they are programming + language-dependent. ## Steps to Contribute -Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on. This is to prevent duplicated efforts from other contributors on the same issue. +Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on. +This is to prevent duplicated efforts from other contributors on the same issue. If you have questions about one of the issues, please comment on them, and one of the maintainers will clarify. -We kindly ask you to follow the [Pull Request Checklist](#Pull-Request-Checklist) to ensure reviews can happen accordingly. +We kindly ask you to follow the [Pull Request Checklist](#Pull-Request-Checklist) to ensure reviews can happen +accordingly. ## Contributing Code @@ -36,7 +44,8 @@ The following rule governs code contributions: * Contributions must be licensed under the [Apache 2.0 License](./LICENSE) * Newly created files must be opened by an instantiated version of the file 'templates/file-header.txt' -* At least if you add a new file to the repository, add your name into the contributor section of the file NOTICE (please respect the preset entry structure) +* At least if you add a new file to the repository, add your name into the contributor section of the file NOTICE ( + please respect the preset entry structure) ## Contributing Documentation @@ -48,15 +57,22 @@ The following rule governs documentation contributions: ## Pull Request Checklist -* Branch from the main branch and, if needed, rebase to the current main branch before submitting your pull request. If it doesn't merge cleanly with main you may be asked to rebase your changes. +* Branch from the main branch and, if needed, rebase to the current main branch before submitting your pull request. If + it doesn't merge cleanly with main you may be asked to rebase your changes. -* Commits should be as small as possible while ensuring that each commit is correct independently (i.e., each commit should compile and pass tests). +* Commits should be as small as possible while ensuring that each commit is correct independently (i.e., each commit + should compile and pass tests). -* Test your changes as thoroughly as possible before you commit them. Preferably, automate your test by unit/integration tests. If tested manually, provide information about the test scope in the PR description (e.g. “Test passed: Upgrade version from 0.42 to 0.42.23.”). +* Test your changes as thoroughly as possible before you commit them. Preferably, automate your test by unit/integration + tests. If tested manually, provide information about the test scope in the PR description (e.g. “Test passed: Upgrade + version from 0.42 to 0.42.23.”). -* Create _Work In Progress [WIP]_ pull requests only if you need clarification or an explicit review before you can continue your work item. +* Create _Work In Progress [WIP]_ pull requests only if you need clarification or an explicit review before you can + continue your work item. -* If your patch is not getting reviewed or you need a specific person to review it, you can @-reply a reviewer asking for a review in the pull request or a comment, or you can ask for a review by contacting us via [email](mailto:opensource@telekom.de). +* If your patch is not getting reviewed or you need a specific person to review it, you can @-reply a reviewer asking + for a review in the pull request or a comment, or you can ask for a review by contacting us + via [email](mailto:opensource@telekom.de). * Post review: * If a review requires you to change your commit(s), please test the changes again. @@ -68,8 +84,13 @@ The following rule governs documentation contributions: * We use GitHub issues to track bugs and enhancement requests. -* Please provide as much context as possible when you open an issue. The information you provide must be comprehensive enough to reproduce that issue for the assignee. Therefore, contributors may use but aren't restricted to the issue template provided by the project maintainers. +* Please provide as much context as possible when you open an issue. The information you provide must be comprehensive + enough to reproduce that issue for the assignee. Therefore, contributors may use but aren't restricted to the issue + template provided by the project maintainers. -* When creating an issue, try using one of our issue templates which already contain some guidelines on which content is expected to process the issue most efficiently. If no template applies, you can of course also create an issue from scratch. +* When creating an issue, try using one of our issue templates which already contain some guidelines on which content is + expected to process the issue most efficiently. If no template applies, you can of course also create an issue from + scratch. -* Please apply one or more applicable [labels](/../../labels) to your issue so that all community members are able to cluster the issues better. +* Please apply one or more applicable [labels](/../../labels) to your issue so that all community members are able to + cluster the issues better. diff --git a/README.md b/README.md index 9203ce54..7f7064ff 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,6 @@ Licensing

- ## About This repository contains the source code of the EU Digital COVID Certificate Gateway (DGCG). @@ -43,17 +42,23 @@ backend-to-backend integration is facilitated, and countries can onboard increme retain flexibility and can control data processing of their users. ## Development -Please be aware that the provided configuration files contain passwords that do not conform to any reasonable password policies, hence under no circumstances should be applied to productive or even broader test environments. -Passwords used in productive scenarios should be provided only at runtime and stored in safe place, with restricted and logged access. + +Please be aware that the provided configuration files contain passwords that do not conform to any reasonable password +policies, hence under no circumstances should be applied to productive or even broader test environments. +Passwords used in productive scenarios should be provided only at runtime and stored in safe place, with restricted and +logged access. + ### Prerequisites - OpenJDK 11 (with installed ```keytool``` CLI) - Maven -- Authenticate to [Github Packages](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-apache-maven-registry) +- Authenticate + to [Github Packages](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-apache-maven-registry) #### Authenticating to GitHub Packages -As some of the required libraries (and/or versions are pinned/available only from GitHub Packages) You need to authenticate +As some of the required libraries (and/or versions are pinned/available only from GitHub Packages) You need to +authenticate to [GitHub Packages](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-apache-maven-registry) The following steps need to be followed @@ -127,8 +132,10 @@ afterwards the PublicKey has to be exported in a Java KeyStore. keytool -importcert -alias dgcg_trust_anchor -file cert_ta.pem -keystore ta.jks -storepass dgcg-p4ssw0rd ``` -Put the created ta.jks file in the "certs" directory of dgc-gateway. If you are using the Docker image then this folder must -be in the root directory of your local workspace (on the same level as this readme file). Create directory it does not already exist. +Put the created ta.jks file in the "certs" directory of dgc-gateway. If you are using the Docker image then this folder +must +be in the root directory of your local workspace (on the same level as this readme file). Create directory it does not +already exist. #### Create Database @@ -148,8 +155,9 @@ docker-compose up --build `ERROR: for dgc-gateway_dgc-gateway_1 Cannot create container for service dgc-gateway` -This error occurs in Docker-for-Windows if Docker does not have access to the gateway folder. In Docker-for-Windows, -go to `Settings > Resources > File Sharing` and add the root directory of the repository, then restart Docker-for-Windows. +This error occurs in Docker-for-Windows if Docker does not have access to the gateway folder. In Docker-for-Windows, +go to `Settings > Resources > File Sharing` and add the root directory of the repository, then restart +Docker-for-Windows. #### Insert Trusted Parties @@ -172,11 +180,13 @@ dgc ta sign -c cert_ta.pem -k key_ta.pem -i cert_csca.pem dgc ta sign -c cert_ta.pem -k key_ta.pem -i cert_upload.pem ``` -Afterwards you can create a new entry in the `trusted_parties` table and fill all of the fields with the data produced by the above commands. +Afterwards you can create a new entry in the `trusted_parties` table and fill all of the fields with the data produced +by the above commands. ##### Inserting Trusted Parties into the Database -Log on to the mysql container (using the docker commands or opening a shell with the docker UI) and open mysql cli like this: +Log on to the mysql container (using the docker commands or opening a shell with the docker UI) and open mysql cli like +this: ``` mysql --user=root --password=admin dgc @@ -250,7 +260,7 @@ curl -X GET http://localhost:8080/trustList -H "accept: application/json" -H "X- ``` * Replace the example SHA with that of your own test certificate in the `X-SSL-Client-SHA256` header -* Replace the example country with your own country in the `X-SSL-Client-DN` header (i.e. US, CN, ZA) +* Replace the example country with your own country in the `X-SSL-Client-DN` header (i.e. US, CN, ZA) That command will return something looking like this (but with large base64 strings) @@ -305,7 +315,8 @@ Property, e.g. C=EU) #### Coverting the certificate/private key into PKCS12 -Windows users may wish to convert their certificate/private keys into a PKCS12 package so that it can be imported into the +Windows users may wish to convert their certificate/private keys into a PKCS12 package so that it can be imported into +the machine's certificate store. Thankfully that is pretty simple using openssl. For example to convert the test authentication certificate created earlier: @@ -338,18 +349,23 @@ The following channels are available for discussions, feedback, and support requ | Type | Channel | | ------------------------ | ------------------------------------------------------ | -| **Gateway issues** | | -| **Other requests** | | +| **Gateway +issues** | | +| **Other +requests** | | -## How to contribute +## How to contribute -Contribution and feedback is encouraged and always welcome. For more information about how to contribute, the project structure, -as well as additional contribution information, see our [Contribution Guidelines](./CONTRIBUTING.md). By participating in this +Contribution and feedback is encouraged and always welcome. For more information about how to contribute, the project +structure, +as well as additional contribution information, see our [Contribution Guidelines](./CONTRIBUTING.md). By participating +in this project, you agree to abide by its [Code of Conduct](./CODE_OF_CONDUCT.md) at all times. -## Contributors +## Contributors -Our commitment to open source means that we are enabling -in fact encouraging- all interested parties to contribute and become part of its developer community. +Our commitment to open source means that we are enabling -in fact encouraging- all interested parties to contribute and +become part of its developer community. ## Licensing @@ -360,6 +376,8 @@ the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0. -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" -BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the [LICENSE](./LICENSE) for the specific +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " +AS IS" +BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the [LICENSE](./LICENSE) for the +specific language governing permissions and limitations under the License. diff --git a/codestyle/checkstyle.xml b/codestyle/checkstyle.xml index ce3b135e..f12c8ee4 100644 --- a/codestyle/checkstyle.xml +++ b/codestyle/checkstyle.xml @@ -1,7 +1,7 @@ + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - - - - - - - - - - - - - + + + + + - - + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - - + + + - - - - - - - - + + + + + + - - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + - - - - - - - + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/software-design-dgc-gateway.md b/docs/software-design-dgc-gateway.md index fe7bf9b1..e014d6de 100644 --- a/docs/software-design-dgc-gateway.md +++ b/docs/software-design-dgc-gateway.md @@ -1,31 +1,44 @@ # Software Design EU Digital Green Certificates Gateway + by Michael Schulte (m.schulte@t-systems.com) -## Introduction +## Introduction + This documents describes detailed aspects of the implementation of the -EU-digital-green-certificates Gateway. It is closely related to the document [trust-framework_interoperability_certificates](https://ec.europa.eu/health/sites/health/files/ehealth/docs/trust-framework_interoperability_certificates_en.pdf), -to which describes the overarching framework and structure. The [European Digital Green Certificate Gateway](https://ec.europa.eu/health/sites/health/files/ehealth/docs/digital-green-certificates_v2_en.pdf) defines the gateway structure defines the high level architecture. +EU-digital-green-certificates Gateway. It is closely related to the +document [trust-framework_interoperability_certificates](https://ec.europa.eu/health/sites/health/files/ehealth/docs/trust-framework_interoperability_certificates_en.pdf) +, +to which describes the overarching framework and structure. +The [European Digital Green Certificate Gateway](https://ec.europa.eu/health/sites/health/files/ehealth/docs/digital-green-certificates_v2_en.pdf) +defines the gateway structure defines the high level architecture. -Target audience for this document are software engineers who want to get a better understanding of the insight of the implementation to be able to contribute. +Target audience for this document are software engineers who want to get a better understanding of the insight of the +implementation to be able to contribute. This document is not finished, feedback is welcome and will change its content. +# Overview + +## Purpose of the Software System + +The Digital Green Certificate Gateway (DGCG) has the purpose to support the EU trust framework. +It provides the operability to securely share validation and verification across the connected national backends. +With the usage of DGCG Each national backend is free to distribute the keys via any preferred technology to support the +national verification devices in the best way. +If the Digital Green Certificate is in a correctly formatted 2D code, each verifier device can verify each code from +other countries, if the verifier is connected to the backend (online verification) or if it has downloaded and stored +the necessary public keys beforehand (offline verification). -# Overview -## Purpose of the Software System -The Digital Green Certificate Gateway (DGCG) has the purpose to support the EU trust framework. -It provides the operability to securely share validation and verification across the connected national backends. -With the usage of DGCG Each national backend is free to distribute the keys via any preferred technology to support the national verification devices in the best way. -If the Digital Green Certificate is in a correctly formatted 2D code, each verifier device can verify each code from other countries, if the verifier is connected to the backend (online verification) or if it has downloaded and stored the necessary public keys beforehand (offline verification). +## Core Entities -## Core Entities -|Entity| Definition| +|Entity| Definition| | ------------- |:-------------:| | trusted_party | stores the certificate for the trusted parties| | signer_information | stores the certificate for the signer | | audit_event | stores all events happening in the system | # Context View + The diagram below shows the api endpoints from the DGC Gateway and the dataflow from and to national backends. ![Data Flow View](DGCG-Overview.png "API Overview") National Health Authorities acting the certificate management process. @@ -33,70 +46,97 @@ National Health Authorities acting the certificate management process. # Software Design ## Communication + This is a condesed overview of the comminication of the DGCG + ### Triangle of Trust -The triangle of trust is the blueprint for Green Certificate interoperability: --**Holder**: A Green Certificate (DGC) owner (i.e., a citizen with a vaccination, negative PCR test result, or positive anti-body test result)—note that the Green Certificate can be held digitally within a wallet app or on paper (or both) --**Issuer**: A national authority + +The triangle of trust is the blueprint for Green Certificate interoperability: +-**Holder**: A Green Certificate (DGC) owner (i.e., a citizen with a vaccination, negative PCR test result, or positive +anti-body test result)—note that the Green Certificate can be held digitally within a wallet app or on paper (or both) +-**Issuer**: A national authority -**Verifier**: An offline/online verifier (e.g., customs officers, police, or hotel staff) ![triangle_of_trust.png](triangle_of_trust.png) -How does the verifier know which issuer is trustworthy? In a personal relationship, one would decide by experience. In this architecture, the DGCG tells the verifier which issuers are trustworthy by providing cryptographically anchored information. +How does the verifier know which issuer is trustworthy? In a personal relationship, one would decide by experience. In +this architecture, the DGCG tells the verifier which issuers are trustworthy by providing cryptographically anchored +information. + ### Distribution of Verification Information -Exactly how each national app communicates with the corresponding national backend -whether via CDN, active push, or otherwise - is left to each country. Important here is the cryptographically secured E2E protection between the member states. + +Exactly how each national app communicates with the corresponding national backend -whether via CDN, active push, or +otherwise - is left to each country. Important here is the cryptographically secured E2E protection between the member +states. ![distribution_of_signing.png](distribution_of_signing.png) + ### Communication ways -- Device-to-device communication is built on a standardized 2D code and verifier format defined by the EU Trust Framework. -- A direct backend-to-backend communication is not necessary, because the main purpose of the DGCG solution is to provide verification information. + +- Device-to-device communication is built on a standardized 2D code and verifier format defined by the EU Trust + Framework. +- A direct backend-to-backend communication is not necessary, because the main purpose of the DGCG solution is to + provide verification information. + ### Trust -To ensure that just data from trusted parties are accepted. The system contains a trust list which is signed entry by entry air gapped by an official signer. This signer, signs with his private key each request of onboarding and provides this signed information to the DGCG operator which can set this entry on the trust list. This guarantees that no external attacker or another party than the trusted signer can create valid records for the trust list. The public key of the trusted signer is shared out of band to the other parties, to establish an effective trust anchoring. + +To ensure that just data from trusted parties are accepted. The system contains a trust list which is signed entry by +entry air gapped by an official signer. This signer, signs with his private key each request of onboarding and provides +this signed information to the DGCG operator which can set this entry on the trust list. This guarantees that no +external attacker or another party than the trusted signer can create valid records for the trust list. The public key +of the trusted signer is shared out of band to the other parties, to establish an effective trust anchoring. ![trust.png](trust.png) ## Interfaces + DGCG provides a simple REST API with common upload and download functionality for trusted information. ![api.png](api.png) -The are described further with a OpenAPI doc and in the document [European Digital Green Certificate Gateway](https://ec.europa.eu/health/sites/health/files/ehealth/docs/digital-green-certificates_v2_en.pdf) +The are described further with a OpenAPI doc and in the +document [European Digital Green Certificate Gateway](https://ec.europa.eu/health/sites/health/files/ehealth/docs/digital-green-certificates_v2_en.pdf) ## Database Design ###Trusted Party Table -| Field | Description | Data Type | -| -------------- | ------------------------------------------------ | ------------------------------------------------ | -| Id | Primary key | Long | -| Timestamp | Timestamp of the Record | Timestamp | -| Country | Country Code | varchar(2) | -| Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | +| Field | Description | Data Type | +| -------------- | ------------------------------------------------ | ------------------------------------------------ | +| Id | Primary key | Long | +| Timestamp | Timestamp of the Record | Timestamp | +| Country | Country Code | varchar(2) | +| Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | | Certificate Type | Type of the certificate (Authentication, Signing, Issuer, Client, CSCA) | varchar(*) | -| RawData | Raw Data of the certificate | binary| -| Signature | Signature of the Trust Anchor | varchar(*) | -The cerificate type is one of the following +| RawData | Raw Data of the certificate | binary| +| Signature | Signature of the Trust Anchor | varchar(*) | +The cerificate type is one of the following + - **Authentication** Certificate which the member state is using to authenticate at DGCG (NBTLS) - **Upload** Certificate which the member state is using to sign the uploaded information’s (NBUS) - **CSCA** Country Signing Certificate Authority certificate (NBCSCA) ###Signer Information Table -| Field | Description | Data Type | -| -------------- | ------------------------------------------------ | ------------------------------------------------ | -| Id | Primary key | Long | -| Timestamp | Timestamp of the Record | Timestamp | -| Country | Country Code | varchar(2) | -| Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | +| Field | Description | Data Type | +| -------------- | ------------------------------------------------ | ------------------------------------------------ | +| Id | Primary key | Long | +| Timestamp | Timestamp of the Record | Timestamp | +| Country | Country Code | varchar(2) | +| Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | | Certificate Type | Type of the certificate (Authentication, Signing, Issuer, Client, CSCA) | varchar(*) | -| RawData | Raw Data of the certificate | binary| -| Signature | Signature of the Trust Anchor | varchar(*) | -The cerificate type is one of the following +| RawData | Raw Data of the certificate | binary| +| Signature | Signature of the Trust Anchor | varchar(*) | +The cerificate type is one of the following + - **DSC** Certificate which the member state is using to sign documents (NBDSC) -###Audit Event Table -| Field | Description | Data Type | -| -------------- | ------------------------------------------------ | ------------------------------------------------ | -| Id | Primary key | Long | -| Timestamp | Timestamp of the Record | Timestamp | -| Country | Country Code | varchar(2) | -| Uploader Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | -| Authentication Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | -| Event | Event which occurs | binary| -| Description | Description of the Event | varchar(*) | -The Rights on the table are restricted to insert only for the application user to restrict manipulation of the audit events. -The following table will contain all Audit Events. It is currently under implementation, so the list will be filled after. + ###Audit Event Table + | Field | Description | Data Type | + | -------------- | ------------------------------------------------ | ------------------------------------------------ + | + | Id | Primary key | Long | + | Timestamp | Timestamp of the Record | Timestamp | + | Country | Country Code | varchar(2) | + | Uploader Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | + | Authentication Sha256Fingerprint | SHA256-fingerprint of the certificate | varchar(*) | + | Event | Event which occurs | binary| + | Description | Description of the Event | varchar(*) | + The Rights on the table are restricted to insert only for the application user to restrict manipulation of the audit + events. + The following table will contain all Audit Events. It is currently under implementation, so the list will be filled + after. | Event | Description | | -------------- | ------------------------------------------------ | @@ -127,9 +167,12 @@ This is a List of all Possible Problem Reports that can be returned. | 0x299 | Unexpected Error | Not available | Ask Support for help | ## Monitoring + ## Audit Logging -The purpose of the audit logging is to track the usage of the system. + +The purpose of the audit logging is to track the usage of the system. The audit events will be additionally logged into the application log. + ### Log File Structure The target environment for this service is an Apache Tomcat Server. So all log output will be written to stdout @@ -137,13 +180,16 @@ which is redirected to `catalina.out` log file. So the content of this file need ### Log Message Structure -All log messages are following one format. The log format is inspired by the Splunk best practices document ([link](https://dev.splunk.com/enterprise/docs/developapps/addsupport/logging/loggingbestpractices/)) +All log messages are following one format. The log format is inspired by the Splunk best practices +document ([link](https://dev.splunk.com/enterprise/docs/developapps/addsupport/logging/loggingbestpractices/)) Each log message contains key value pairs which will represent the required data. -All of these log messages are consisting of mandatory and additional fields. The mandatory fields are always at the beginning of a log message. - The key value pairs are connected by a "=" and seperated by "," followed by a space. If the value consists of more than one word, the value will be wrapped within double quotes. - Multiple log messages are seperated by a new line. - The following mandatory fields will be sent with each log message: +All of these log messages are consisting of mandatory and additional fields. The mandatory fields are always at the +beginning of a log message. +The key value pairs are connected by a "=" and seperated by "," followed by a space. If the value consists of more than +one word, the value will be wrapped within double quotes. +Multiple log messages are seperated by a new line. +The following mandatory fields will be sent with each log message: | Field | Content | Example Value | | ---------- | ------------------------------------------------ | -------------------------------------- | @@ -159,15 +205,17 @@ All of these log messages are consisting of mandatory and additional fields. The | exception | Stack Trace, if available | org.springframew... | Example: + ``` timestamp="2020-08-04 17:19:46.038", level=INFO, pid=44929, traceId=e7d394f3b0431c68, spanId=e7d394f3b0431c68, thread=scheduling-1, class=e.i.f.service.SignerInformationService, message="Uploaded certificate already exist", exception="" ``` *exception field will only be written to log file. In console stack traces will be printed directly. -These key-value-pairs can be followed by additional attributes. The additional attributes are individual for each log message. +These key-value-pairs can be followed by additional attributes. The additional attributes are individual for each log +message. -### Log messages +### Log messages | Event | Log Level | Log Message | Additional attributes | | ----- | --------- | ----------- | --------------------- | @@ -222,35 +270,45 @@ The load balancer terminates TLS, executes the mutual TLS authentication and for The IP of the load balancer is assigned to registered domain name. To allow authentication of the http request the load balancer adds header - attributes containing meta information about the client certificate used to - authenticate the request. - +attributes containing meta information about the client certificate used to +authenticate the request. ## Reverse Proxy -The reverse proxy distributes load over the tomcat instances. + +The reverse proxy distributes load over the tomcat instances. The main purpose for EDGCGS is to provide fail over behavior in case a tomcat instance is not available anymore. ## Database + The database is implemented as mySQL 5.7 ## Log Analytics/Monitoring Integration ## Secret Management -Environment specific secrets are managed as part of the tomcat configuration. JDBC connections are provided as tomcat resources. + +Environment specific secrets are managed as part of the tomcat configuration. JDBC connections are provided as tomcat +resources. # Security -In this section, we define the security concept and security requirements for the DGCG Gateway. The meaning of the words "MUST", "MAY", and "SHOULD" is defined in [RFC 2119](https://tools.ietf.org/html/rfc2119). To each requirement, an identifier, in the format "SecReq-{Number}", is assigned. +In this section, we define the security concept and security requirements for the DGCG Gateway. The meaning of the +words "MUST", "MAY", and "SHOULD" is defined in [RFC 2119](https://tools.ietf.org/html/rfc2119). To each requirement, an +identifier, in the format "SecReq-{Number}", is assigned. -## 1. Definitions +## 1. Definitions -**Client**: It refers to a National Backend (see [DGCG Gateway Architecture Specification](https://ec.europa.eu/health/sites/health/files/ehealth/docs/trust-framework_interoperability_certificates_en.pdf)) that uploads or downloads to/from the DGCG Gateway. In the section "Client Authentication", Client and National Backend are used interchangeably. +**Client**: It refers to a National Backend ( +see [DGCG Gateway Architecture Specification](https://ec.europa.eu/health/sites/health/files/ehealth/docs/trust-framework_interoperability_certificates_en.pdf)) +that uploads or downloads to/from the DGCG Gateway. In the section "Client Authentication", Client and National Backend +are used interchangeably. **DGCG Gateway Components** -* **Load Balancer**: The component that receives the clients' requests (e.g., signerCertificate , trustList or audit) and forwards them to the DGCG Gateway Service after successful execution of the TLS protocol. +* **Load Balancer**: The component that receives the clients' requests (e.g., signerCertificate , trustList or audit) + and forwards them to the DGCG Gateway Service after successful execution of the TLS protocol. -* **Service**: The component that processes the clients' requests (e.g., signerCertificate , trustList or audit) after successful client authentication. +* **Service**: The component that processes the clients' requests (e.g., signerCertificate , trustList or audit) after + successful client authentication. * **Database**: The component where the information (e.g., thumbprint) of the clients' certificates is stored. @@ -261,180 +319,239 @@ In this section, we define the security concept and security requirements for th - **CSCA** Country Signing Certificate Authority certificate (NBCSCA) - **DSC** Certificate which the member state is using to sign documents (NBDSC) -**Batch Signature**: A [PKCS#7](https://tools.ietf.org/html/rfc5652) object containing, among others, the signature of a diagnosis key batch and the Signing Certificate. +**Batch Signature**: A [PKCS#7](https://tools.ietf.org/html/rfc5652) object containing, among others, the signature of a +diagnosis key batch and the Signing Certificate. -**Client Authentication**: The process in which a Client is authenticated (using its Authentication Certificate) and authorized to request signerCertificate , trustList or audit. +**Client Authentication**: The process in which a Client is authenticated (using its Authentication Certificate) and +authorized to request signerCertificate , trustList or audit. -**Certificate Thumbprint/Fingerprint**: Hash value of a certificate. We have defined the SHA-256 hash function for calculation of the fingerprint. In this document, certificate hash, certificate fingerprint, and certificate thumbprint are used interchangeably. +**Certificate Thumbprint/Fingerprint**: Hash value of a certificate. We have defined the SHA-256 hash function for +calculation of the fingerprint. In this document, certificate hash, certificate fingerprint, and certificate thumbprint +are used interchangeably. ##Client Authentication -As shown in the figure below, the Ditital Green Certificate Gateway Load Balancer authenticates the Clients (National Databases) via mTLS. Then, the clients' requests are forwarded to the DGCG , which validates the Client Authentication Certificate against a whitelist stored in the database. Once the certificate has been successfully verified, the DGCG passes the requests to the corresponding endpoints (e.g., signerCertificate , trustList or audit). +As shown in the figure below, the Ditital Green Certificate Gateway Load Balancer authenticates the Clients (National +Databases) via mTLS. Then, the clients' requests are forwarded to the DGCG , which validates the Client Authentication +Certificate against a whitelist stored in the database. Once the certificate has been successfully verified, the DGCG +passes the requests to the corresponding endpoints (e.g., signerCertificate , trustList or audit). -**SecReq-001** All the clients' requests (e.g., upload diagnostic key batch) MUST be authenticated. +**SecReq-001** All the clients' requests (e.g., upload diagnostic key batch) MUST be authenticated. ###Load Balancer -**SecReq-002** The Load Balancer MUST perform mutual TLS (mTLS) with the clients (national backends). +**SecReq-002** The Load Balancer MUST perform mutual TLS (mTLS) with the clients (national backends). **SecReq-003** The Load Balancer MUST implement TLS termination. ####Certificate Validation -**SecReq-004** If the client's certificate is not sent during the TLS handshake protocol, the Load Balancer MUST reject the client's request. +**SecReq-004** If the client's certificate is not sent during the TLS handshake protocol, the Load Balancer MUST reject +the client's request. -**SecReq-005** If the client's certificate has expired, the Load Balancer MUST reject the client's request. The expiration is determined by the “notAfter” field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the certificate. +**SecReq-005** If the client's certificate has expired, the Load Balancer MUST reject the client's request. The +expiration is determined by the “notAfter” field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the +certificate. -**SecReq-006** The Load Balancer MUST maintain a bundle containing the root CA certificates or intermediate CA certificates needed to verify (trust) the clients' authentication certificates. If a national backend uses a self-signed client authentication certificate, this certificate MUST be added to the CA bundle. +**SecReq-006** The Load Balancer MUST maintain a bundle containing the root CA certificates or intermediate CA +certificates needed to verify (trust) the clients' authentication certificates. If a national backend uses a self-signed +client authentication certificate, this certificate MUST be added to the CA bundle. -**SecReq-007** The Load Balancer MUST validate the client's certificate chain using its CA bundle (SecReq-006). If validation fails, the Load Balancer MUST reject the client's request. +**SecReq-007** The Load Balancer MUST validate the client's certificate chain using its CA bundle (SecReq-006). If +validation fails, the Load Balancer MUST reject the client's request. -**SecReq-008** The Load Balancer MAY maintain a Certificate Revocation List (CRL) (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-54)). +**SecReq-008** The Load Balancer MAY maintain a Certificate Revocation List (CRL) ( +see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-54)). -**SecReq-009** If SecReq-008 is fulfilled, the Load Balancer MUST reject a request, if the client's certificate is present in the CRL. +**SecReq-009** If SecReq-008 is fulfilled, the Load Balancer MUST reject a request, if the client's certificate is +present in the CRL. ####Request Forwarding -**SecReq-010** If the client's certificate was successfully validated, the Load Balancer MUST forward the corresponding request to the DGCG Service via HTTP. +**SecReq-010** If the client's certificate was successfully validated, the Load Balancer MUST forward the corresponding +request to the DGCG Service via HTTP. -**SecReq-011** When a client's request is forwarded to the DGCG Service (See SecReq-010), the Load Balancer MUST add the following HTTP headers to the request: +**SecReq-011** When a client's request is forwarded to the DGCG Service (See SecReq-010), the Load Balancer MUST add +the following HTTP headers to the request: | HTTP Header | Description | |---------------------|-------------| -| X-SSL-Client-SHA256 | SHA-256 hash value of the DER encoded client's certificate. The so-called certificate fingerprint or thumbprint. (base64 encoded bytes, not base64 encoded hexadecimal string representation) | -| X-SSL-Client-DN | The subject Distinguished Name (DN) of the client's certificate (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-23) and [RFC 1719](https://tools.ietf.org/html/rfc1779#page-6)). The DN MUST contain the Country (C) attribute. (it is possible to transmit DN string URL encoded) | +| X-SSL-Client-SHA256 | SHA-256 hash value of the DER encoded client's certificate. The so-called certificate fingerprint or thumbprint. (base64 encoded bytes, not base64 encoded hexadecimal string representation) | +| X-SSL-Client-DN | The subject Distinguished Name (DN) of the client's certificate (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-23) and [RFC 1719](https://tools.ietf.org/html/rfc1779#page-6)). The DN MUST contain the Country (C) attribute. (it is possible to transmit DN string URL encoded) | -###Ditital Green Certificate Gateway Service +###Ditital Green Certificate Gateway Service -**SecReq-012** The Ditital Green Certificate Gateway (DGCG) Service MUST authenticate the clients' requests using the information sent in the HTTP requests (see SecReq-011) and the certificate information stored in the DGCG Database. +**SecReq-012** The Ditital Green Certificate Gateway (DGCG) Service MUST authenticate the clients' requests using the +information sent in the HTTP requests (see SecReq-011) and the certificate information stored in the DGCG Database. **SecReq-013** To authenticate a client, the DGCG Service MUST perform the following steps: -1. Extract the value of the *X-SSL-Client-SHA256* and *X-SSL-Client-DN* headers from the HTTP request forwarded by the Load Balancer (see SecReq-011). +1. Extract the value of the *X-SSL-Client-SHA256* and *X-SSL-Client-DN* headers from the HTTP request forwarded by the + Load Balancer (see SecReq-011). 2. Extract the Country (C) attribute from the X-SSL-Client-DN value. -3. Query the DGCG Database using the X-SSL-Client-SHA256 value and the Country (C) attribute. Also, the certificate type (see SecReq-019) MUST be used in the query. In this case, the type is: AUTHENTICATION. +3. Query the DGCG Database using the X-SSL-Client-SHA256 value and the Country (C) attribute. Also, the certificate + type (see SecReq-019) MUST be used in the query. In this case, the type is: AUTHENTICATION. - 1. If the query does not return any record, the DGCG Service MUST reject the client's request. + 1. If the query does not return any record, the DGCG Service MUST reject the client's request. - 2. If the query returns a record, the DGCG Service MUST check whether the certificate has not been revoked. If the certificate was already revoked, the DGCG Service MUST reject the request. Otherwise continue with step 4. + 2. If the query returns a record, the DGCG Service MUST check whether the certificate has not been revoked. If the + certificate was already revoked, the DGCG Service MUST reject the request. Otherwise continue with step 4. -4. If the client’s request was authenticated successfully, the DGCG Service MUST forward the request to the corresponding endpoint (e.g., download or upload endpoint). +4. If the client’s request was authenticated successfully, the DGCG Service MUST forward the request to the + corresponding endpoint (e.g., download or upload endpoint). ####Logging -**SecReq-014** The DGCG Service MUST log each authentication attempt using the information of the X-SSL-Client-DN header. +**SecReq-014** The DGCG Service MUST log each authentication attempt using the information of the X-SSL-Client-DN +header. + +**SecReq-015** The DGCG Service MUST use the log format defined by the Cyber Defense Center (CDC) **TODO:TBD**. -**SecReq-015** The DGCG Service MUST use the log format defined by the Cyber Defense Center (CDC) **TODO:TBD**. - ###Storing Secrets The service has two secrets which need special handling during storage + - private key of DGCGTLS for outgoing TLS connections (for call back), to allow mTLS authentication -- public key of DGCGTA Trust Anchor +- public key of DGCGTA Trust Anchor -These keys need to be stored seperate from the database. They are stored in two different Java KeyStore (https://en.wikipedia.org/wiki/Java_KeyStore) and deployed manually to the Tomcat instances. The keystores are protected with a password, the password is set as JVM property. +These keys need to be stored seperate from the database. They are stored in two different Java +KeyStore (https://en.wikipedia.org/wiki/Java_KeyStore) and deployed manually to the Tomcat instances. The keystores are +protected with a password, the password is set as JVM property. ### Certificate Verification during OnBoarding -Note that the onboarding process is *not* part of the DGCG Gateway (software). It is included here to inform the future operators of the EDGCGS and the operators of the member-states of key technical steps. The entire onboarding process will be defined separately as part of the overall e-Health network process. +Note that the onboarding process is *not* part of the DGCG Gateway (software). It is included here to inform the future +operators of the EDGCGS and the operators of the member-states of key technical steps. The entire onboarding process +will be defined separately as part of the overall e-Health network process. -**SecReq-023** The Ditital Green Certificate Gateway (DGCG) upload endpoint MUST validate the Signing Certificate, which is sent in the PKCS#7 object (see SecReq-017), based on the requirements specified below. The file format is PKCS#12 (pfx) with a password. The password is communicated by to the DGCG by the Designated Country Technical Contact (DCTC) during a verification call where the DGCG contacts the DCTC to verify the authenticity of the upload and get the password. +**SecReq-023** The Ditital Green Certificate Gateway (DGCG) upload endpoint MUST validate the Signing Certificate, +which is sent in the PKCS#7 object (see SecReq-017), based on the requirements specified below. The file format is +PKCS#12 (pfx) with a password. The password is communicated by to the DGCG by the Designated Country Technical Contact ( +DCTC) during a verification call where the DGCG contacts the DCTC to verify the authenticity of the upload and get the +password. -**SecReq-###** The Relative Distinguished Name(RDN) 'C' in the Distinguished Name (DN) must match the country of the the Country. +**SecReq-###** The Relative Distinguished Name(RDN) 'C' in the Distinguished Name (DN) must match the country of the the +Country. **SecReq-###** The RDN 'emailAddress' in the Distinguished Name (DN) must match the 24x7 email address of the Country. -**SecReq-###** The RNDs CN, O and (optional OU) should be populated with a set of human readable and operationally correct set of values. Such as '/CN=DGCGS Netherlands/OU=National Health Institute/O=Ministry of Public Health/C=NL'. +**SecReq-###** The RNDs CN, O and (optional OU) should be populated with a set of human readable and operationally +correct set of values. Such as '/CN=DGCGS Netherlands/OU=National Health Institute/O=Ministry of Public Health/C=NL'. **SecReq-###** The PKCS#12 (pfx) Should contain the complete chain, where applicable. -**SecReq-###** If the Signing Certificate should be valid for at least 3 (more) month. The expiration is determined by the "notAfter" field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the certificate. +**SecReq-###** If the Signing Certificate should be valid for at least 3 (more) month. The expiration is determined by +the "notAfter" field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the certificate. -**SecReq-###** The DGCG upload endpoint MUST verify the signature of the Signing Certificate. If validation failed, the DGCG upload endpoint MUST abort Onboarding.. +**SecReq-###** The DGCG upload endpoint MUST verify the signature of the Signing Certificate. If validation failed, the +DGCG upload endpoint MUST abort Onboarding.. -**SecReq-###** In order to ensure maximum interoperability in a short timeline fields such as the Key Usage, Extended Key Usage will be operationally *ignored*. +**SecReq-###** In order to ensure maximum interoperability in a short timeline fields such as the Key Usage, Extended +Key Usage will be operationally *ignored*. **SecReq-###** The X.509 certificate will be of version X.509 v3 (RFC5280). -**SecReq-###** The key-lengths will meet or exceed the BSI Recommendations(2020) and the ECRYPT-CSA Recommendations(2018) for near term production: 3072 bits (RSA) or 256 bits (EC) and SHA256. +**SecReq-###** The key-lengths will meet or exceed the BSI Recommendations(2020) and the ECRYPT-CSA Recommendations( + +2018) for near term production: 3072 bits (RSA) or 256 bits (EC) and SHA256. ### Certificate Verification during subsequent use and Upload -Digital Green Certificate Gateway (DGCG) upload endpoint MUST validate the Signing Certificate. -**SecReq-###** If the Signing Certificate has expired, the DGCG upload endpoint MUST reject the upload request. The expiration is determined by the "notAfter" field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the certificate. +**SecReq-###** If the Signing Certificate has expired, the DGCG upload endpoint MUST reject the upload request. The +expiration is determined by the "notAfter" field (see [RFC 5280](https://tools.ietf.org/html/rfc5280#page-22)) of the +certificate. -**SecReq-###** The DGCG upload endpoint MUST verify the signature of the Signing Certificate. If validation failed, the DGCG upload endpoint MUST reject the upload request. +**SecReq-###** The DGCG upload endpoint MUST verify the signature of the Signing Certificate. If validation failed, the +DGCG upload endpoint MUST reject the upload request. -**SecReq-026** To verify whether a Signing Certificate is whitelisted, the DGCG upload endpoint MUST execute the next steps: +**SecReq-026** To verify whether a Signing Certificate is whitelisted, the DGCG upload endpoint MUST execute the next +steps: -1. Extract the *Origin* value from the +1. Extract the *Origin* value from the 2. Extract the *Country (C)* attribute from the X-SSL-Client-DN request header (see SecReq-011). -3. Compare the *Origin* with the *Country*. +3. Compare the *Origin* with the *Country*. - 1. If the Origin is not equal to Country, the upload endpoint MUST reject the signature, and thus, reject the upload request. Otherwise, continue with step 4. + 1. If the Origin is not equal to Country, the upload endpoint MUST reject the signature, and thus, reject the upload + request. Otherwise, continue with step 4. 4. Extract the signing certificate (DER encoded) from the PKCS#7 object. 5. Calculate the SHA-256 value of the extracted signing certificate. -6. Query the DGCG Database using the calculated SHA-256 value and the Country (C) attribute. Also, the certificate type (see SecReq-028) MUST be used in the query. In this case, the type is: SIGNING. - - 1. If the query does not return any record, the upload endpoint MUST reject the signature, and thus, reject the upload request. +6. Query the DGCG Database using the calculated SHA-256 value and the Country (C) attribute. Also, the certificate + type (see SecReq-028) MUST be used in the query. In this case, the type is: SIGNING. - 2. If the query returns a record, the upload endpoint MUST verify that the certificate has not been revoked. If the certificate was already revoked, the upload endpoint MUST reject the signature, and thus, reject the upload request. + 1. If the query does not return any record, the upload endpoint MUST reject the signature, and thus, reject the + upload request. + 2. If the query returns a record, the upload endpoint MUST verify that the certificate has not been revoked. If the + certificate was already revoked, the upload endpoint MUST reject the signature, and thus, reject the upload + request. -## Certificate Requirements +## Certificate Requirements -**SecReq-033** All certificates MUST be complied with the X.509 version 3 certificate standard (see [RFC 5280](https://tools.ietf.org/html/rfc5280)). +**SecReq-033** All certificates MUST be complied with the X.509 version 3 certificate standard ( +see [RFC 5280](https://tools.ietf.org/html/rfc5280)). **SecReq-034** All certificates MUST contain a Distinguished Name (DN) in the subject field. -**SecReq-035** The Distinguished Name (DN) MUST have the Country (C) attribute, containing the [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) (e.g., NL) of the National Backend. +**SecReq-035** The Distinguished Name (DN) MUST have the Country (C) attribute, containing +the [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) (e.g., NL) of the +National Backend. --The Signing Certificates, which are used to verify the batch signature, CAN be self-signed. (this subject is likely to change) +-The Signing Certificates, which are used to verify the batch signature, CAN be self-signed. (this subject is likely to +change) -**SecReq-037** The Signing Certificates SHOULD set the Key Usage extension to "digitalSignature" (see [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2.1.3)). +**SecReq-037** The Signing Certificates SHOULD set the Key Usage extension to "digitalSignature" ( +see [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2.1.3)). --The Authentication Certificates, which are used to authenticate the National Backends, SHOULD set the Key Extended Usage extension to "clientAuth" (see [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2.1.12)). +-The Authentication Certificates, which are used to authenticate the National Backends, SHOULD set the Key Extended +Usage extension to "clientAuth" (see [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2.1.12)). -###Cryptographic Requirements +###Cryptographic Requirements -**SecReq-042** The cryptographic operations performed with the National Backends certificates MUST fulfill the following requirements: +**SecReq-042** The cryptographic operations performed with the National Backends certificates MUST fulfill the +following requirements: -| Signature Algorithm | Minimum Key Length | Hash Algorithm | +| Signature Algorithm | Minimum Key Length | Hash Algorithm | |---------------------|--------------------|----------------| -| RSA | 2024 | SHA-256
SHA-384
SHA-512 | -| ECDSA | 250 | SHA-256
SHA-384
SHA-512 | - -The above requirements were defined based on the [BSI recommendations](https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/TechnischeRichtlinien/TR02102/BSI-TR-02102.pdf?__blob=publicationFile&v=10) for cryptographic algorithms and key lengths. +| RSA | 2024 | SHA-256
SHA-384
SHA-512 | +| ECDSA | 250 | SHA-256
SHA-384
SHA-512 | +The above requirements were defined based on +the [BSI recommendations](https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/TechnischeRichtlinien/TR02102/BSI-TR-02102.pdf?__blob=publicationFile&v=10) +for cryptographic algorithms and key lengths. # Deployment View -The system contains different stages which reflect the different perspectives + +The system contains different stages which reflect the different perspectives to the deployed software. Stages: + - DEV - TEST - ACC - PROD ## Generic Deployment View + This view is a generic view which outlines the structure, but does not contain any specifics related to a stage. ![Generic Deployment View](DGCG-deployment-template.png "Generic Deployment View") +## General Software Versions and config +Tomcat hosting service – tomcat instances that are controlled together. Deployment is performed using Nexus artefact +repository. We confirmed in the meantime that the rolling upgrade is possible, but we still need to analyse the +requirements against the service capabilities -## General Software Versions and config - -Tomcat hosting service – tomcat instances that are controlled together. Deployment is performed using Nexus artefact repository. We confirmed in the meantime that the rolling upgrade is possible, but we still need to analyse the requirements against the service capabilities - Tomcat version: Tomcat 9.0.37 - JDK version : JDK 11 (OpenJDK) - Heap Size (MB): 8GB @@ -442,59 +559,74 @@ Tomcat hosting service – tomcat instances that are controlled together. Deploy - Direct Memory Size (MB): default (currently we are not able to specify this) MySQL – Supported version: 5.7 + - Required information to create the instance - Character Set : utf8|latin1|utf16|utf32|other>: utf8 - Estimated DB Size: 10 GB - Required capacity of the VM (GB of memory and number of vCPU) - 4 cores 16 GB RAM - Number of concurrent users: 1 User for the application with max 28 sessions to store data +## Stage DEV - Development -## Stage DEV - Development -As per beginning of the project a dev environment exists in the OTC allowing quick +As per beginning of the project a dev environment exists in the OTC allowing quick and easy access for developer. Scaling Level -- single worker node +- single worker node Security Level + - full security Test Data + - has a number of countries preloaded ### Sizing TEST + Proposal -- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] -- Database equivalent to 2x [4 Cores and 16 GB RAM] +- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] +- Database equivalent to 2x [4 Cores and 16 GB RAM] ## Stage TEST + Scaling Level + - fully scaled Security Level + - full security Test Data + - has a number of countries preloaded ### Sizing TEST + Proposal -- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] -- Database equivalent to 2x [4 Cores and 16 GB RAM] +- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] +- Database equivalent to 2x [4 Cores and 16 GB RAM] ## Stage ACC + ## Stage PROD + ### Sizing PROD Proposal -- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] -- Database equivalent to 2x [4 Cores and 16 GB RAM] + +- Worker Nodes 3x [4 x Cores, 16 GB RAM, 10 GB free Storage] +- Database equivalent to 2x [4 Cores and 16 GB RAM] # Data Deletion -The data base stores + +The data base stores # Other Constraints and Conditions -Timezone all times and dates are interpreted as timestamps in UTC (https://en.wikipedia.org/wiki/Coordinated_Universal_Time) + +Timezone all times and dates are interpreted as timestamps in +UTC (https://en.wikipedia.org/wiki/Coordinated_Universal_Time) diff --git a/manifests/deployment.yml b/manifests/deployment.yml index d271fa40..0f9960cb 100644 --- a/manifests/deployment.yml +++ b/manifests/deployment.yml @@ -1,4 +1,4 @@ -apiVersion : apps/v1 +apiVersion: apps/v1 kind: Deployment metadata: name: "ddccservices-56e3" @@ -16,4 +16,4 @@ spec: - name: "ddccservices-56e3" image: "ddccsrv.azurecr.io/ddccservices" ports: - - containerPort: 8080 \ No newline at end of file + - containerPort: 8080 \ No newline at end of file diff --git a/manifests/service.yml b/manifests/service.yml index c49e9723..812b44bb 100644 --- a/manifests/service.yml +++ b/manifests/service.yml @@ -1,15 +1,15 @@ apiVersion: v1 kind: Service metadata: - name: "ddccservices-56e3" - labels: - app: "ddccservices-56e3" + name: "ddccservices-56e3" + labels: + app: "ddccservices-56e3" spec: - type: LoadBalancer - ports: + type: LoadBalancer + ports: - port: 8080 targetPort: 8080 protocol: TCP name: http - selector: - app: "ddccservices-56e3" \ No newline at end of file + selector: + app: "ddccservices-56e3" \ No newline at end of file diff --git a/owasp/suppressions.xml b/owasp/suppressions.xml index 413e712f..5786d342 100644 --- a/owasp/suppressions.xml +++ b/owasp/suppressions.xml @@ -1,25 +1,25 @@ - - Bug only affects not used features of embedded tomcat. - CVE-2022-23181 - - - False Positive - CVE-2016-1000027 - - - False Positive - Updated to newest version - CVE-2018-14335 - - - False Positive - CVE-2020-5408 - - - Only affecting example code shipped with tomcat. - CVE-2022-34305 + + Bug only affects not used features of embedded tomcat. + CVE-2022-23181 + + + False Positive + CVE-2016-1000027 + + + False Positive - Updated to newest version + CVE-2018-14335 + + + False Positive + CVE-2020-5408 + + + Only affecting example code shipped with tomcat. + CVE-2022-34305 - + diff --git a/pom.xml b/pom.xml index b190e16f..3c4a02b1 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.springframework.boot spring-boot-starter-parent - 2.6.8 + 2.7.3 @@ -43,23 +43,23 @@ UTF-8 UTF-8 - 7.1.1 - 5.7.2 + 7.1.2 + 5.7.3 1.18.24 - 4.13.0 - 1.6.9 + 4.15.0 + 1.6.11 1.5.2.Final 1.70 3.1.0 1.14.1 - 4.38.0 + 4.41.0 2021.0.3 2.1.214 - 5.6.5.Final + 5.6.11.Final 1.3.1 - 3.4.1 - 3.1.2 + 3.4.2 + 3.2.0 3.9.1.2184 0.8.8 1.7.0 @@ -168,6 +168,17 @@ org.springframework.boot spring-boot-starter + + + org.yaml + snakeyaml + + + + + org.yaml + snakeyaml + 1.31 org.springframework.boot @@ -287,7 +298,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.10.1 org.codehaus.mojo @@ -297,12 +308,12 @@ org.apache.maven.plugins maven-war-plugin - 3.3.1 + 3.3.2 org.apache.maven.plugins maven-resources-plugin - 3.2.0 + 3.3.0 org.apache.maven.plugins diff --git a/settings.xml b/settings.xml index 9552ce4b..90474828 100644 --- a/settings.xml +++ b/settings.xml @@ -1,12 +1,12 @@ - false - - - dgc-github - ${app.packages.username} - ${app.packages.password} - - + false + + + dgc-github + ${app.packages.username} + ${app.packages.password} + + diff --git a/src/main/java/eu/europa/ec/dgc/gateway/client/AssetManagerClient.java b/src/main/java/eu/europa/ec/dgc/gateway/client/AssetManagerClient.java index 70be55bf..bd39a9b2 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/client/AssetManagerClient.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/client/AssetManagerClient.java @@ -53,18 +53,18 @@ ResponseEntity uploadFile(@RequestHeader(HttpHeaders.AUTHORIZATION) String @RequestBody byte[] file); @PostMapping( - value = "/ocs/v2.php/apps/files/api/v2/synchronize", - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE + value = "/ocs/v2.php/apps/files/api/v2/synchronize", + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE ) ResponseEntity synchronize( - @RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader, - @RequestHeader("OCS-APIRequest") String ocsApiRequest, - @RequestBody SynchronizeFormData formData); + @RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader, + @RequestHeader("OCS-APIRequest") String ocsApiRequest, + @RequestBody SynchronizeFormData formData); @GetMapping( - value = "/remote.php/dav/files/{uid}/{path}/{filename}", - produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) + value = "/remote.php/dav/files/{uid}/{path}/{filename}", + produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) ResponseEntity downloadFile(@RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader, @PathVariable("uid") String uid, @PathVariable("path") String path, diff --git a/src/main/java/eu/europa/ec/dgc/gateway/entity/TrustedIssuerEntity.java b/src/main/java/eu/europa/ec/dgc/gateway/entity/TrustedIssuerEntity.java index bc2b909a..02577dbd 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/entity/TrustedIssuerEntity.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/entity/TrustedIssuerEntity.java @@ -33,7 +33,6 @@ import lombok.Setter; - @Getter @Setter @Entity diff --git a/src/main/java/eu/europa/ec/dgc/gateway/repository/SignerInformationRepository.java b/src/main/java/eu/europa/ec/dgc/gateway/repository/SignerInformationRepository.java index 12d6922d..62d57eb6 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/repository/SignerInformationRepository.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/repository/SignerInformationRepository.java @@ -66,10 +66,10 @@ List getByCertificateTypeAndCountryAndDeletedAtIsNull( SignerInformationEntity.CertificateType type, String countryCode); @Query(SELECT_SINCE) - List getIsSince(@Param("since")ZonedDateTime since); + List getIsSince(@Param("since") ZonedDateTime since); @Query(SELECT_SINCE) - List getIsSince(@Param("since")ZonedDateTime since, Pageable pageable); + List getIsSince(@Param("since") ZonedDateTime since, Pageable pageable); List getByDeletedAtIsNull(); @@ -77,13 +77,13 @@ List getByCertificateTypeAndCountryAndDeletedAtIsNull( @Query(SELECT_BY_TYPE_SINCE) List getByCertificateTypeIsSince( - @Param("certType")SignerInformationEntity.CertificateType type, - @Param("since")ZonedDateTime since); + @Param("certType") SignerInformationEntity.CertificateType type, + @Param("since") ZonedDateTime since); @Query(SELECT_BY_TYPE_SINCE) List getByCertificateTypeIsSince( - @Param("certType")SignerInformationEntity.CertificateType type, - @Param("since")ZonedDateTime since, Pageable pageable); + @Param("certType") SignerInformationEntity.CertificateType type, + @Param("since") ZonedDateTime since, Pageable pageable); @Query(SELECT_BY_TYPE_AND_COUNTRY_SINCE) List getByCertificateTypeAndCountryIsSince( diff --git a/src/main/java/eu/europa/ec/dgc/gateway/repository/TrustedPartyRepository.java b/src/main/java/eu/europa/ec/dgc/gateway/repository/TrustedPartyRepository.java index 18e4f1c0..67bbcb8e 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/repository/TrustedPartyRepository.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/repository/TrustedPartyRepository.java @@ -36,7 +36,7 @@ public interface TrustedPartyRepository extends JpaRepository= :since"; - + List getByCountryAndCertificateType(String country, TrustedPartyEntity.CertificateType type); List getByCertificateType(TrustedPartyEntity.CertificateType type); @@ -55,13 +55,13 @@ Optional getFirstByThumbprintAndCertificateType( @Query(SELECT_BY_TYPE_SINCE) List getByCertificateTypeIsSince( - @Param("certType")TrustedPartyEntity.CertificateType type, - @Param("since")ZonedDateTime since); + @Param("certType") TrustedPartyEntity.CertificateType type, + @Param("since") ZonedDateTime since); @Query(SELECT_BY_TYPE_AND_COUNTRY_SINCE) List getByCountryAndCertificateTypeIsSince( - @Param("country")String countryCode, - @Param("certType")TrustedPartyEntity.CertificateType type, - @Param("since")ZonedDateTime since); + @Param("country") String countryCode, + @Param("certType") TrustedPartyEntity.CertificateType type, + @Param("since") ZonedDateTime since); } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationController.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationController.java index c89945a9..6589edf2 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationController.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationController.java @@ -62,8 +62,8 @@ public class CertificateMigrationController { public static final String SENT_VALUES_FORMAT = "{%s} country:{%s}"; public static final String X_004 = "0x004"; public static final String DEFAULT_ERROR_MESSAGE = "Possible reasons: Wrong Format," - + " no CMS, not the correct signing alg missing attributes, invalid signature, " - + "certificate not signed by known CA"; + + " no CMS, not the correct signing alg missing attributes, invalid signature, " + + "certificate not signed by known CA"; private final SignerInformationService signerInformationService; @@ -81,24 +81,23 @@ public class CertificateMigrationController { @GetMapping @Operation( security = { - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) }, summary = "Get all cms packages for a country identified by certificate.", tags = {"CMS Migration"}, responses = { - @ApiResponse( - responseCode = "200", - description = "Download successful.", - content = @Content( - mediaType = MediaType.APPLICATION_JSON_VALUE, - schema = @Schema(implementation = CmsPackageDto.class) - ) - ) + @ApiResponse( + responseCode = "200", + description = "Download successful.", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = CmsPackageDto.class) + )) } ) public ResponseEntity> getCmsPackages( - @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String countryCode + @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String countryCode ) { log.info("Getting cms packages for {}", countryCode); @@ -119,51 +118,50 @@ public ResponseEntity> getCmsPackages( /** * Update a CMS Package. - * */ @CertificateAuthenticationRequired @PostMapping @Operation( - security = { - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) - }, - tags = {"CMS Migration"}, - summary = "Update an existing CMS Package", - description = "Endpoint to update an existing CMS pacakage.", - requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( - required = true, - content = @Content(schema = @Schema(implementation = CmsPackageDto.class)) - ), - responses = { - @ApiResponse( - responseCode = "204", - description = "Update applied."), - @ApiResponse( - responseCode = "409", - description = "CMS Package does not exist."), - @ApiResponse( - responseCode = "400", - description = "Invalid CMS input.") - } + security = { + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) + }, + tags = {"CMS Migration"}, + summary = "Update an existing CMS Package", + description = "Endpoint to update an existing CMS pacakage.", + requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( + required = true, + content = @Content(schema = @Schema(implementation = CmsPackageDto.class)) + ), + responses = { + @ApiResponse( + responseCode = "204", + description = "Update applied."), + @ApiResponse( + responseCode = "409", + description = "CMS Package does not exist."), + @ApiResponse( + responseCode = "400", + description = "Invalid CMS input.") + } ) public ResponseEntity updateCmsPackage( - @RequestBody CmsPackageDto cmsPackageDto, - @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String countryCode, - @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) String authThumbprint + @RequestBody CmsPackageDto cmsPackageDto, + @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String countryCode, + @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) String authThumbprint ) { if (CmsPackageDto.CmsPackageTypeDto.DSC == cmsPackageDto.getType()) { SignedCertificateDto signedCertificateDto = getSignerCertificate(cmsPackageDto.getCms()); if (!signedCertificateDto.isVerified()) { throw new DgcgResponseException(HttpStatus.BAD_REQUEST, "0x260", "CMS signature is invalid", "", - "Submitted package needs to be signed by a valid upload certificate"); + "Submitted package needs to be signed by a valid upload certificate"); } try { signerInformationService.updateSignerCertificate(cmsPackageDto.getEntityId(), - signedCertificateDto.getPayloadCertificate(), signedCertificateDto.getSignerCertificate(), - signedCertificateDto.getSignature(), countryCode); + signedCertificateDto.getPayloadCertificate(), signedCertificateDto.getSignerCertificate(), + signedCertificateDto.getSignature(), countryCode); } catch (SignerInformationService.SignerCertCheckException e) { handleSignerCertException(cmsPackageDto, countryCode, e); } @@ -172,17 +170,17 @@ public ResponseEntity updateCmsPackage( if (!signedStringDto.isVerified()) { throw new DgcgResponseException(HttpStatus.BAD_REQUEST, "0x260", "CMS signature is invalid", "", - "Submitted package needs to be signed by a valid upload certificate"); + "Submitted package needs to be signed by a valid upload certificate"); } try { if (CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST == cmsPackageDto.getType()) { revocationListService.updateRevocationBatchCertificate(cmsPackageDto.getEntityId(), - signedStringDto.getPayloadString(), signedStringDto.getSignerCertificate(), - signedStringDto.getRawMessage(), countryCode); + signedStringDto.getPayloadString(), signedStringDto.getSignerCertificate(), + signedStringDto.getRawMessage(), countryCode); } else if (CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE == cmsPackageDto.getType()) { validationRuleService.updateValidationRuleCertificate(cmsPackageDto.getEntityId(), - signedStringDto.getPayloadString(), signedStringDto.getSignerCertificate(), - signedStringDto.getRawMessage(), countryCode); + signedStringDto.getPayloadString(), signedStringDto.getSignerCertificate(), + signedStringDto.getRawMessage(), countryCode); } } catch (RevocationListService.RevocationBatchServiceException e) { handleRevocationBatchException(cmsPackageDto, countryCode, e); @@ -207,14 +205,14 @@ private void handleSignerCertException(CmsPackageDto cmsPackageDto, String count switch (e.getReason()) { case EXIST_CHECK_FAILED: throw new DgcgResponseException(HttpStatus.CONFLICT, "0x010", - "Certificate to be updated does not exist.", - sentValues, e.getMessage()); + "Certificate to be updated does not exist.", + sentValues, e.getMessage()); case UPLOAD_FAILED: throw new DgcgResponseException(HttpStatus.INTERNAL_SERVER_ERROR, - "0x011", "Upload of new Signer Certificate failed", sentValues, e.getMessage()); + "0x011", "Upload of new Signer Certificate failed", sentValues, e.getMessage()); default: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, X_004, DEFAULT_ERROR_MESSAGE, sentValues, - e.getMessage()); + e.getMessage()); } } @@ -225,17 +223,17 @@ private void handleRevocationBatchException(CmsPackageDto cmsPackageDto, String switch (e.getReason()) { case NOT_FOUND: throw new DgcgResponseException(HttpStatus.CONFLICT, "0x020", - "RevocationBatch to be updated does not exist.", - sentValues, e.getMessage()); + "RevocationBatch to be updated does not exist.", + sentValues, e.getMessage()); case INVALID_COUNTRY: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, - "0x021", "Invalid country", sentValues, e.getMessage()); + "0x021", "Invalid country", sentValues, e.getMessage()); case INVALID_JSON_VALUES: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, - "0x022", "Json Payload invalid", sentValues, e.getMessage()); + "0x022", "Json Payload invalid", sentValues, e.getMessage()); default: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, X_004, DEFAULT_ERROR_MESSAGE, sentValues, - e.getMessage()); + e.getMessage()); } } @@ -246,17 +244,17 @@ private void handleValidationRuleExcepetion(CmsPackageDto cmsPackageDto, String switch (e.getReason()) { case NOT_FOUND: throw new DgcgResponseException(HttpStatus.CONFLICT, "0x030", - "ValidationRule to be updated does not exist.", - sentValues, e.getMessage()); + "ValidationRule to be updated does not exist.", + sentValues, e.getMessage()); case INVALID_COUNTRY: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, - "0x031", "Invalid country", sentValues, e.getMessage()); + "0x031", "Invalid country", sentValues, e.getMessage()); case INVALID_JSON: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, "0x032", "Json Payload invalid", sentValues, - e.getMessage()); + e.getMessage()); default: throw new DgcgResponseException(HttpStatus.BAD_REQUEST, X_004, DEFAULT_ERROR_MESSAGE, sentValues, - e.getMessage()); + e.getMessage()); } } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListController.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListController.java index d0b5cdd5..3718c06b 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListController.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListController.java @@ -76,7 +76,7 @@ public class CertificateRevocationListController { private final RevocationBatchMapper revocationBatchMapper; public static final String UUID_REGEX = - "^[0-9a-f]{8}\\b-[0-9a-f]{4}\\b-[0-9a-f]{4}\\b-[0-9a-f]{4}\\b-[0-9a-f]{12}$"; + "^[0-9a-f]{8}\\b-[0-9a-f]{4}\\b-[0-9a-f]{4}\\b-[0-9a-f]{4}\\b-[0-9a-f]{12}$"; private static final String MDC_DOWNLOADER_COUNTRY = "downloaderCountry"; private static final String MDC_DOWNLOADED_COUNTRY = "downloadedCountry"; @@ -88,19 +88,19 @@ public class CertificateRevocationListController { @CertificateAuthenticationRequired(requiredRoles = CertificateAuthenticationRole.RevocationListReader) @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE) @Operation( - security = { - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) - }, - tags = {"Revocation"}, - summary = "Download Batch List", - description = "Returning a list of batches with a small wrapper providing metadata." - + " The batches are sorted by date in ascending (chronological) order.", - parameters = { - @Parameter( - in = ParameterIn.HEADER, - name = HttpHeaders.IF_MODIFIED_SINCE, - description = "This header contains the last downloaded date to get just the latest results. " + security = { + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) + }, + tags = {"Revocation"}, + summary = "Download Batch List", + description = "Returning a list of batches with a small wrapper providing metadata." + + " The batches are sorted by date in ascending (chronological) order.", + parameters = { + @Parameter( + in = ParameterIn.HEADER, + name = HttpHeaders.IF_MODIFIED_SINCE, + description = "This header contains the last downloaded date to get just the latest results. " + "On the initial call the header should be the set to ‘2021-06-01T00:00:00Z’", required = true) }, @@ -155,22 +155,22 @@ public ResponseEntity downloadBatchList( required = true) }, responses = { - @ApiResponse( - responseCode = "200", - description = "Response contains the batch.", - content = @Content(schema = @Schema(implementation = RevocationBatchDto.class)), - headers = @Header(name = HttpHeaders.ETAG, description = "Batch ID")), - @ApiResponse( - responseCode = "404", - description = "Batch does not exist."), - @ApiResponse( - responseCode = "410", - description = "Batch already deleted.") + @ApiResponse( + responseCode = "200", + description = "Response contains the batch.", + content = @Content(schema = @Schema(implementation = RevocationBatchDto.class)), + headers = @Header(name = HttpHeaders.ETAG, description = "Batch ID")), + @ApiResponse( + responseCode = "404", + description = "Batch does not exist."), + @ApiResponse( + responseCode = "410", + description = "Batch already deleted.") } ) public ResponseEntity downloadBatch( - @Valid @PathVariable("batchId") @Pattern(regexp = UUID_REGEX) String batchId, - @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String downloaderCountry) { + @Valid @PathVariable("batchId") @Pattern(regexp = UUID_REGEX) String batchId, + @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String downloaderCountry) { try { RevocationBatchDownload download = revocationListService.getRevocationBatch(batchId); @@ -183,9 +183,9 @@ public ResponseEntity downloadBatch( log.info("Revocation Batch downloaded."); return ResponseEntity - .ok() - .header(HttpHeaders.ETAG, download.getBatchId()) - .body(download.getSignedCms()); + .ok() + .header(HttpHeaders.ETAG, download.getBatchId()) + .body(download.getSignedCms()); } catch (RevocationListService.RevocationBatchServiceException e) { switch (e.getReason()) { diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListController.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListController.java index d0c284d3..4da39412 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListController.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListController.java @@ -148,12 +148,12 @@ public ResponseEntity> downloadTrustList( @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String downloaderCountryCode ) { List trustList; - if (isPaginationRequired(page,size)) { + if (isPaginationRequired(page, size)) { page = (page != null && page >= 0) ? page : 0; size = (size != null && size >= 0) ? size : 100; trustList = trustListMapper.trustListToTrustListDto( - trustListService.getTrustList(ifModifiedSince, page, size)); + trustListService.getTrustList(ifModifiedSince, page, size)); } else { trustList = trustListMapper.trustListToTrustListDto( trustListService.getTrustList(ifModifiedSince, null, null)); @@ -242,12 +242,12 @@ public ResponseEntity> downloadTrustListFilteredByType( TrustListType mappedType = trustListMapper.certificateTypeDtoToTrustListType(type); List trustList; - if (isPaginationRequired(page,size)) { + if (isPaginationRequired(page, size)) { page = (page != null && page >= 0) ? page : 0; size = (size != null && size >= 0) ? size : 100; trustList = trustListMapper.trustListToTrustListDto( - trustListService.getTrustList(mappedType, ifModifiedSince, page, size)); + trustListService.getTrustList(mappedType, ifModifiedSince, page, size)); } else { trustList = trustListMapper.trustListToTrustListDto( trustListService.getTrustList(mappedType, ifModifiedSince, null, null)); @@ -347,12 +347,12 @@ public ResponseEntity> downloadTrustListFilteredByCountryAndT countryCode = countryCode.toUpperCase(Locale.ROOT); List trustList; - if (isPaginationRequired(page,size)) { + if (isPaginationRequired(page, size)) { page = (page != null && page >= 0) ? page : 0; size = (size != null && size >= 0) ? size : 100; trustList = trustListMapper.trustListToTrustListDto( - trustListService.getTrustList(mappedType, countryCode, ifModifiedSince, page, size)); + trustListService.getTrustList(mappedType, countryCode, ifModifiedSince, page, size)); } else { trustList = trustListMapper.trustListToTrustListDto( trustListService.getTrustList(mappedType, countryCode, ifModifiedSince, null, null)); @@ -373,47 +373,46 @@ public ResponseEntity> downloadTrustListFilteredByCountryAndT @CertificateAuthenticationRequired @GetMapping(path = "/issuers", produces = MediaType.APPLICATION_JSON_VALUE) @Operation( - security = { - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), - @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) - }, - summary = "Returns the list of trusted issuers filtered by criterias.", - tags = {"Trust List"}, - parameters = { - @Parameter( - in = ParameterIn.QUERY, - name = "country", - description = "Two-Digit Country Code", - examples = {@ExampleObject("EU"), @ExampleObject("DE")} - ) - }, - responses = { - @ApiResponse( - responseCode = "200", - description = "Returns the list of trusted issuers.", - content = @Content( - mediaType = MediaType.APPLICATION_JSON_VALUE, - array = @ArraySchema(schema = @Schema(implementation = TrustedIssuerDto.class)))), - @ApiResponse( - responseCode = "401", - description = "Unauthorized. No Access to the system." - + "(Client Certificate not present or whitelisted)", - content = @Content( - mediaType = MediaType.APPLICATION_JSON_VALUE, - schema = @Schema(implementation = ProblemReportDto.class) - )) - }) + security = { + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_HASH), + @SecurityRequirement(name = OpenApiConfig.SECURITY_SCHEMA_DISTINGUISH_NAME) + }, + summary = "Returns the list of trusted issuers filtered by criterias.", + tags = {"Trust List"}, + parameters = { + @Parameter( + in = ParameterIn.QUERY, + name = "country", + description = "Two-Digit Country Code", + examples = {@ExampleObject("EU"), @ExampleObject("DE")}) + }, + responses = { + @ApiResponse( + responseCode = "200", + description = "Returns the list of trusted issuers.", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + array = @ArraySchema(schema = @Schema(implementation = TrustedIssuerDto.class)))), + @ApiResponse( + responseCode = "401", + description = "Unauthorized. No Access to the system." + + "(Client Certificate not present or whitelisted)", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = ProblemReportDto.class) + )) + }) public ResponseEntity> getTrustedIssuersByCountry( - @RequestParam(value = "country", required = false) List<@Size(min = 2, max = 2) String> searchCountry + @RequestParam(value = "country", required = false) List<@Size(min = 2, max = 2) String> searchCountry ) { if (CollectionUtils.isNotEmpty(searchCountry)) { log.debug("Downloading TrustedIssuers TrustList. Parameters country: {}", searchCountry); return ResponseEntity.ok(trustedIssuerMapper.trustedIssuerEntityToTrustedIssuerDto( - trustedIssuerService.getAllIssuers(searchCountry))); + trustedIssuerService.getAllIssuers(searchCountry))); } else { log.debug("Downloading all TrustedIssuers TrustList."); return ResponseEntity.ok(trustedIssuerMapper.trustedIssuerEntityToTrustedIssuerDto( - trustedIssuerService.getAllIssuers())); + trustedIssuerService.getAllIssuers())); } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleController.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleController.java index 7db4db45..220eba22 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleController.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleController.java @@ -104,8 +104,7 @@ public class ValidationRuleController { content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(ref = "#/components/schemas/ValidationRuleDownloadResponse") - ) - ) + )) } ) public ResponseEntity>> downloadValidationRules( @@ -152,18 +151,15 @@ public ResponseEntity>> downloadValidationRu responses = { @ApiResponse( responseCode = "201", - description = "Created successful." - ), + description = "Created successful."), @ApiResponse( responseCode = "400", description = "Bad data submitted. See ProblemReport for more details.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ), + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "403", description = "You are not allowed to create this validation rules.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ) + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))) } ) public ResponseEntity uploadValidationRule( @@ -251,30 +247,25 @@ public ResponseEntity uploadValidationRule( responses = { @ApiResponse( responseCode = "204", - description = "Delete successful." - ), + description = "Delete successful."), @ApiResponse( responseCode = "400", description = "Bad data submitted. See ProblemReport for more details.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ), + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "403", description = "You are not allowed to delete these validation rules.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ), + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "404", description = "Validation rule not found.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ) + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))) } ) public ResponseEntity deleteValidationRules( @org.springframework.web.bind.annotation.RequestBody SignedStringDto signedString, @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY) String authenticatedCountryCode, - @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) String thumbprint - ) { + @RequestAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) String thumbprint) { log.info("Rule Delete Request"); @@ -349,23 +340,19 @@ public ResponseEntity deleteValidationRules( responses = { @ApiResponse( responseCode = "204", - description = "Delete successful." - ), + description = "Delete successful."), @ApiResponse( responseCode = "400", description = "Bad data submitted. See ProblemReport for more details.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ), + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "403", description = "You are not allowed to delete these validation rules.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ), + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "404", description = "Validation rule not found.", - content = @Content(schema = @Schema(implementation = ProblemReportDto.class)) - ) + content = @Content(schema = @Schema(implementation = ProblemReportDto.class))) } ) public ResponseEntity deleteValidationRulesAliasEndpoint( diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetController.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetController.java index 701f41db..e5ce8df9 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetController.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetController.java @@ -69,21 +69,19 @@ public class ValuesetController { @ApiResponse( responseCode = "200", description = "List of valueset ids", - content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class))) - ), + content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), @ApiResponse( responseCode = "401", description = "Unauthorized. No Access to the system. (Client Certificate not present or whitelisted)", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, - schema = @Schema(implementation = ProblemReportDto.class) - )) + schema = @Schema(implementation = ProblemReportDto.class))) } ) public ResponseEntity> getValuesetIds() { return ResponseEntity.ok(valuesetService.getValuesetIds()); } - + /** * Controller to get a specific valueset. */ @@ -101,22 +99,19 @@ public ResponseEntity> getValuesetIds() { @ApiResponse( responseCode = "200", description = "Valueset JSON Object", - content = @Content(schema = @Schema(implementation = String.class)) - ), + content = @Content(schema = @Schema(implementation = String.class))), @ApiResponse( responseCode = "401", description = "Unauthorized. No Access to the system. (Client Certificate not present or whitelisted)", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, - schema = @Schema(implementation = ProblemReportDto.class) - )), + schema = @Schema(implementation = ProblemReportDto.class))), @ApiResponse( responseCode = "404", description = "Valueset not found", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, - schema = @Schema(implementation = ProblemReportDto.class) - )) + schema = @Schema(implementation = ProblemReportDto.class))) } ) public ResponseEntity getValueset(@PathVariable("id") String id) { diff --git a/src/main/java/eu/europa/ec/dgc/gateway/restapi/dto/TrustedIssuerDto.java b/src/main/java/eu/europa/ec/dgc/gateway/restapi/dto/TrustedIssuerDto.java index 43118c47..5dc58e7c 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/restapi/dto/TrustedIssuerDto.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/restapi/dto/TrustedIssuerDto.java @@ -42,7 +42,7 @@ public class TrustedIssuerDto { private String thumbprint; @Schema(example = "o53CbAa77LyIMFc5Gz+B2Jc275Gdg/SdLayw7gx0GrTcinR95zfTLr8nNHgJMYlX3rD8Y11zB/Osyt0 ..." - + " W+VIrYRGSEmgjGy2EwzvA5nVhsaA+/udnmbyQw9LjAOQ==") + + " W+VIrYRGSEmgjGy2EwzvA5nVhsaA+/udnmbyQw9LjAOQ==") private String sslPublicKey; @Schema(example = "JWKS") diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/PublishingService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/PublishingService.java index fd3f93ea..825fbc7e 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/PublishingService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/PublishingService.java @@ -291,7 +291,7 @@ private void downloadFile(String filename) { ResponseEntity downloadResponse; try { downloadResponse = assetManagerClient.downloadFile(getAuthHeader(), - properties.getPublication().getAmngrUid(), properties.getPublication().getPath(), filename); + properties.getPublication().getAmngrUid(), properties.getPublication().getPath(), filename); if (downloadResponse.getStatusCode().is2xxSuccessful()) { log.info("Download of file {} was successful.", filename); @@ -316,10 +316,10 @@ private void downloadFile(String filename) { try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) { fileOutputStream.write(downloadResponse.getBody()); log.info("Saved file {} to {} ({} Bytes)", - filename, targetFile.getAbsolutePath(), downloadResponse.getBody().length); + filename, targetFile.getAbsolutePath(), downloadResponse.getBody().length); } catch (IOException e) { log.error("Failed to write downloaded file to disk: {}, {}", - targetFile.getAbsolutePath(), e.getMessage()); + targetFile.getAbsolutePath(), e.getMessage()); } } else { log.error("Download Response does not contain any body"); @@ -330,7 +330,7 @@ private void downloadFile(String filename) { private String getAuthHeader() { String header = "Basic "; header += Base64.getEncoder().encodeToString((properties.getPublication().getUser() + ":" - + properties.getPublication().getPassword()).getBytes(StandardCharsets.UTF_8)); + + properties.getPublication().getPassword()).getBytes(StandardCharsets.UTF_8)); return header; } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/RevocationListService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/RevocationListService.java index 60d43a8f..e436f647 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/RevocationListService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/RevocationListService.java @@ -232,16 +232,16 @@ public RevocationBatchDownload getRevocationBatch(String batchId) throws Revocat if (entity.isEmpty()) { throw new RevocationBatchServiceException( - RevocationBatchServiceException.Reason.NOT_FOUND, "Batch not found"); + RevocationBatchServiceException.Reason.NOT_FOUND, "Batch not found"); } if (entity.get().getDeleted()) { throw new RevocationBatchServiceException( - RevocationBatchServiceException.Reason.GONE, "Batch already deleted."); + RevocationBatchServiceException.Reason.GONE, "Batch already deleted."); } return new RevocationBatchDownload( - entity.get().getBatchId(), entity.get().getSignedBatch(), entity.get().getCountry()); + entity.get().getBatchId(), entity.get().getSignedBatch(), entity.get().getCountry()); } /** @@ -253,10 +253,10 @@ public RevocationBatchDownload getRevocationBatch(String batchId) throws Revocat public List getCmsPackage(String country) { List revocationBatchEntities = revocationBatchRepository.getAllByCountry(country); return revocationBatchEntities.stream() - .filter(it -> !it.getDeleted()) - .map(it -> new CmsPackageDto(it.getSignedBatch(), it.getId(), - CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST)) - .collect(Collectors.toList()); + .filter(it -> !it.getDeleted()) + .map(it -> new CmsPackageDto(it.getSignedBatch(), it.getId(), + CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST)) + .collect(Collectors.toList()); } /** @@ -270,11 +270,11 @@ public List getCmsPackage(String country) { * with detailed information why the validation has failed. */ public RevocationBatchEntity updateRevocationBatchCertificate( - Long id, - String payloadRevocationBatch, - X509CertificateHolder signerCertificate, - String cms, - String authenticatedCountryCode + Long id, + String payloadRevocationBatch, + X509CertificateHolder signerCertificate, + String cms, + String authenticatedCountryCode ) throws RevocationBatchServiceException { final RevocationBatchEntity revocationBatchEntity = revocationBatchRepository.findById(id).orElseThrow( @@ -291,11 +291,11 @@ public RevocationBatchEntity updateRevocationBatchCertificate( log.info("Updating cms of Revocation Batch Entity with id {}", revocationBatchEntity.getBatchId()); auditService.addAuditEvent( - authenticatedCountryCode, - signerCertificate, - authenticatedCountryCode, - "UPDATED", - String.format("Updated Revocation Batch (%s)", revocationBatchEntity.getBatchId()) + authenticatedCountryCode, + signerCertificate, + authenticatedCountryCode, + "UPDATED", + String.format("Updated Revocation Batch (%s)", revocationBatchEntity.getBatchId()) ); RevocationBatchEntity updatedEntity = revocationBatchRepository.save(revocationBatchEntity); @@ -311,11 +311,11 @@ private void contentCheckUploaderCountry(RevocationBatchDto parsedBatch, String } private void contentCheckUploaderCountry(String batchCountryCode, String countryCode) - throws RevocationBatchServiceException { + throws RevocationBatchServiceException { if (!batchCountryCode.equals(countryCode)) { throw new RevocationBatchServiceException( - RevocationBatchServiceException.Reason.INVALID_COUNTRY, - "Country does not match your authentication."); + RevocationBatchServiceException.Reason.INVALID_COUNTRY, + "Country does not match your authentication."); } } @@ -392,12 +392,12 @@ private void contentCheckValidValuesForDeletion(RevocationBatchDeleteRequestDto } private void contentCheckMigrateCms(String payload, String entityCms) - throws RevocationBatchServiceException { + throws RevocationBatchServiceException { SignedStringDto signedStringDto = getSignedString(entityCms); if (!payload.equals(signedStringDto.getPayloadString())) { throw new RevocationBatchServiceException( - RevocationBatchServiceException.Reason.INVALID_JSON_VALUES, - "New cms payload does not match present payload." + RevocationBatchServiceException.Reason.INVALID_JSON_VALUES, + "New cms payload does not match present payload." ); } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpService.java index c7ade469..ba002dc8 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpService.java @@ -47,7 +47,7 @@ public void cleanup() { log.info("Starting SignerInformation Cleanup Job."); int affectedRowsDeleted = signerInformationRepository.deleteDeletedSignerInformationOlderThan( - ZonedDateTime.now().minusDays(configProperties.getSignerInformation().getDeleteThreshold()) + ZonedDateTime.now().minusDays(configProperties.getSignerInformation().getDeleteThreshold()) ); log.info("Deleted {} SignerInformation.", affectedRowsDeleted); diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationService.java index cb25379c..ee26f44a 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/SignerInformationService.java @@ -100,12 +100,12 @@ public List getSignerInformation( * Optional the list can be filtered by a timestamp and paginated. * * @param ifModifiedSince since timestamp for filtering SignerInformation. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return list of SignerInformation */ - public List getSignerInformation(ZonedDateTime ifModifiedSince, - Integer page, Integer size) { + public List getSignerInformation(ZonedDateTime ifModifiedSince, + Integer page, Integer size) { if (ifModifiedSince != null && page != null && size != null) { return signerInformationRepository.getIsSince(ifModifiedSince, PageRequest.of(page, size)); } else if (ifModifiedSince != null) { @@ -118,13 +118,13 @@ public List getSignerInformation(ZonedDateTime ifModif } /** - * Finds a list of SignerInformation filtered by type. - * Optional the list can be filtered by a timestamp and paginated. + * Finds a list of SignerInformation filtered by type. + * Optional the list can be filtered by a timestamp and paginated. * - * @param type type to filter for + * @param type type to filter for * @param ifModifiedSince since timestamp for filtering SignerInformation. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of SignerInformation */ public List getSignerInformation(SignerInformationEntity.CertificateType type, @@ -147,11 +147,11 @@ public List getSignerInformation(SignerInformationEntit * Finds a list of SignerInformation filtered by type and country. * Optional the list can be filtered by a timestamp and paginated. * - * @param countryCode 2-digit country Code to filter for. - * @param type type to filter for + * @param countryCode 2-digit country Code to filter for. + * @param type type to filter for * @param ifModifiedSince since timestamp for filtering SignerInformation. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of SignerInformation */ public List getSignerInformation( @@ -436,7 +436,7 @@ private void contentCheckKidAlreadyExists(X509CertificateHolder uploadedCertific } private SignerInformationEntity contentCheckExists(X509CertificateHolder uploadedCertificate) - throws SignerCertCheckException { + throws SignerCertCheckException { String uploadedCertificateThumbprint = certificateUtils.getCertThumbprint(uploadedCertificate); Optional signerInformationEntity = @@ -444,7 +444,7 @@ private SignerInformationEntity contentCheckExists(X509CertificateHolder uploade return signerInformationEntity.orElseThrow( () -> new SignerCertCheckException(SignerCertCheckException.Reason.EXIST_CHECK_FAILED, - "Uploaded certificate does not exists")); + "Uploaded certificate does not exists")); } private boolean certificateSignedByCa(X509CertificateHolder certificate, TrustedPartyEntity caCertificateEntity) { diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustListService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustListService.java index b91f708d..a3f805a8 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustListService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustListService.java @@ -105,8 +105,8 @@ public List getTrustList(TrustListType type, String countryCode) { * Optional the list can be filtered by a timestamp and paginated. * * @param ifModifiedSince since timestamp for filtering TrustList. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of {@link TrustList} ordered by KID */ public List getTrustList(ZonedDateTime ifModifiedSince, @@ -135,10 +135,10 @@ public List getTrustList(ZonedDateTime ifModifiedSince, * Finds a list of TrustList filtered by type. * Optional the list can be filtered by a timestamp and paginated. * - * @param type the type to filter for. + * @param type the type to filter for. * @param ifModifiedSince since timestamp for filtering TrustList. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of {@link TrustList} ordered by KID */ public List getTrustList(TrustListType type, @@ -157,11 +157,11 @@ public List getTrustList(TrustListType type, } else { if (type == TrustListType.DSC) { trustListsByType = mergeAndConvert(Collections.emptyList(), - signerInformationService.getSignerInformation(SignerInformationEntity.CertificateType.DSC, - ifModifiedSince, null, null)); + signerInformationService.getSignerInformation(SignerInformationEntity.CertificateType.DSC, + ifModifiedSince, null, null)); } else { trustListsByType = mergeAndConvert(trustedPartyService.getCertificates(map(type), - ifModifiedSince, null, null), + ifModifiedSince, null, null), Collections.emptyList()); } } @@ -173,14 +173,14 @@ public List getTrustList(TrustListType type, } /** - * Finds a list of TrustList filtered by country and type. - * Optional the list can be filtered by a timestamp and paginated. + * Finds a list of TrustList filtered by country and type. + * Optional the list can be filtered by a timestamp and paginated. * - * @param type the type to filter for. - * @param countryCode the 2-Digit country code to filter for. + * @param type the type to filter for. + * @param countryCode the 2-Digit country code to filter for. * @param ifModifiedSince since timestamp for filtering TrustList. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of {@link TrustList} ordered by KID */ public List getTrustList(TrustListType type, String countryCode, @@ -223,9 +223,9 @@ private List mergeAndConvert( List signerInformationList) { return Stream.concat( - trustedPartyList.stream().map(this::convert), - signerInformationList.stream().map(this::convert) - ) + trustedPartyList.stream().map(this::convert), + signerInformationList.stream().map(this::convert) + ) .sorted(Comparator.comparing(TrustList::getKid)) .collect(Collectors.toList()); } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerService.java index 2879559d..a464bf7d 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerService.java @@ -70,9 +70,9 @@ public class TrustedIssuerService { */ public List getAllIssuers() { return trustedIssuerRepository.findAll() - .stream() - .filter(this::validateTrustedIssuerIntegrity) - .collect(Collectors.toList()); + .stream() + .filter(this::validateTrustedIssuerIntegrity) + .collect(Collectors.toList()); } /** @@ -82,9 +82,9 @@ public List getAllIssuers() { */ public List getAllIssuers(final List countryCodes) { return trustedIssuerRepository.getAllByCountryIn(countryCodes) - .stream() - .filter(this::validateTrustedIssuerIntegrity) - .collect(Collectors.toList()); + .stream() + .filter(this::validateTrustedIssuerIntegrity) + .collect(Collectors.toList()); } private boolean validateTrustedIssuerIntegrity(TrustedIssuerEntity trustedIssuerEntity) { @@ -99,7 +99,7 @@ private boolean validateTrustedIssuerIntegrity(TrustedIssuerEntity trustedIssuer X509CertificateHolder trustAnchor = null; try { trustAnchor = certificateUtils.convertCertificate((X509Certificate) trustAnchorKeyStore.getCertificate( - dgcConfigProperties.getTrustAnchor().getCertificateAlias())); + dgcConfigProperties.getTrustAnchor().getCertificateAlias())); } catch (KeyStoreException | CertificateEncodingException | IOException e) { log.error("Could not load DGCG-TrustAnchor from KeyStore.", e); return false; @@ -107,8 +107,8 @@ private boolean validateTrustedIssuerIntegrity(TrustedIssuerEntity trustedIssuer // verify signature SignedStringMessageParser parser = new SignedStringMessageParser( - trustedIssuerEntity.getSignature(), - Base64.getEncoder().encodeToString(getHashData(trustedIssuerEntity).getBytes(StandardCharsets.UTF_8))); + trustedIssuerEntity.getSignature(), + Base64.getEncoder().encodeToString(getHashData(trustedIssuerEntity).getBytes(StandardCharsets.UTF_8))); if (parser.getParserState() != SignedMessageParser.ParserState.SUCCESS) { DgcMdc.put(MDC_PROP_PARSER_STATE, parser.getParserState().name()); @@ -131,8 +131,8 @@ private boolean validateTrustedIssuerIntegrity(TrustedIssuerEntity trustedIssuer private String getHashData(TrustedIssuerEntity entity) { return entity.getCountry() + HASH_SEPARATOR - + entity.getName() + HASH_SEPARATOR - + entity.getUrl() + HASH_SEPARATOR - + entity.getUrlType().name() + HASH_SEPARATOR; + + entity.getName() + HASH_SEPARATOR + + entity.getUrl() + HASH_SEPARATOR + + entity.getUrlType().name() + HASH_SEPARATOR; } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedPartyService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedPartyService.java index 9d5d4c61..0eb67161 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedPartyService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/TrustedPartyService.java @@ -108,8 +108,8 @@ public List getCertificates(String country, TrustedPartyEnti * Optional the list can be filtered by a timestamp and paginated. * * @param ifModifiedSince since timestamp for filtering Certificate. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of certificates. */ public List getCertificates(ZonedDateTime ifModifiedSince, @@ -141,10 +141,10 @@ public List getCertificates(ZonedDateTime ifModifiedSince, * Finds a list of Certificates by type. * Optional the list can be filtered by a timestamp and paginated. * - * @param type type to filter for. + * @param type type to filter for. * @param ifModifiedSince since timestamp for filtering Certificate. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of certificates. */ public List getCertificates(TrustedPartyEntity.CertificateType type, @@ -162,7 +162,7 @@ public List getCertificates(TrustedPartyEntity.CertificateTy } else { trustedPartyEntityByTypeList = trustedPartyRepository.getByCertificateTypeIsSince( - type, ifModifiedSince) + type, ifModifiedSince) .stream() .filter(this::validateCertificateIntegrity) .collect(Collectors.toList()); @@ -178,11 +178,11 @@ public List getCertificates(TrustedPartyEntity.CertificateTy * Finds a list of Certificates by country and type. * Optional the list can be filtered by a timestamp and paginated. * - * @param country country of certificate. - * @param type type to filter for. + * @param country country of certificate. + * @param type type to filter for. * @param ifModifiedSince since timestamp for filtering Certificate. - * @param page zero-based page index, must NOT be negative. - * @param size number of items in a page to be returned, must be greater than 0. + * @param page zero-based page index, must NOT be negative. + * @param size number of items in a page to be returned, must be greater than 0. * @return List of certificates. */ public List getCertificates(String country, diff --git a/src/main/java/eu/europa/ec/dgc/gateway/service/ValidationRuleService.java b/src/main/java/eu/europa/ec/dgc/gateway/service/ValidationRuleService.java index 39e7977d..bf01f4e3 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/service/ValidationRuleService.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/service/ValidationRuleService.java @@ -208,8 +208,8 @@ public ValidationRuleEntity addValidationRule( public List getCmsPackage(String country) { List validationRuleEntities = validationRuleRepository.getAllByCountry(country); return validationRuleEntities.stream() - .map(it -> new CmsPackageDto(it.getCms(), it.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE)) - .collect(Collectors.toList()); + .map(it -> new CmsPackageDto(it.getCms(), it.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE)) + .collect(Collectors.toList()); } /** @@ -223,11 +223,11 @@ public List getCmsPackage(String country) { * a reason property with detailed information why the validation has failed. */ public ValidationRuleEntity updateValidationRuleCertificate( - Long id, - String payloadValidationRule, - X509CertificateHolder signerCertificate, - String cms, - String authenticatedCountryCode + Long id, + String payloadValidationRule, + X509CertificateHolder signerCertificate, + String cms, + String authenticatedCountryCode ) throws ValidationRuleCheckException { ValidationRuleEntity validationRuleEntity = validationRuleRepository.findById(id).orElseThrow( @@ -380,11 +380,11 @@ private void contentCheckUploaderCountry(ParsedValidationRule parsedValidationRu } private void contentCheckUploaderCountry(String validationRuleCountryCode, String countryCode) - throws ValidationRuleCheckException { + throws ValidationRuleCheckException { if (!validationRuleCountryCode.equals(countryCode)) { throw new ValidationRuleCheckException( - ValidationRuleCheckException.Reason.INVALID_COUNTRY, - "Country does not match your authentication."); + ValidationRuleCheckException.Reason.INVALID_COUNTRY, + "Country does not match your authentication."); } } @@ -416,11 +416,11 @@ private ParsedValidationRule contentCheckValidJson(String json) throws Validatio } void contentCheckMigrateCms(String payload, String entityCms) - throws ValidationRuleCheckException { + throws ValidationRuleCheckException { SignedStringDto signedStringDto = getSignedString(entityCms); if (!payload.equals(signedStringDto.getPayloadString())) { throw new ValidationRuleCheckException(ValidationRuleCheckException.Reason.INVALID_JSON, - "New cms payload does not match present payload." + "New cms payload does not match present payload." ); } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/utils/CmsUtils.java b/src/main/java/eu/europa/ec/dgc/gateway/utils/CmsUtils.java index b884cb0f..4803e84f 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/utils/CmsUtils.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/utils/CmsUtils.java @@ -37,12 +37,12 @@ private CmsUtils() { public static SignedStringDto getSignedString(final String cms) { SignedStringMessageParser messageParser = new SignedStringMessageParser(cms); return SignedStringDto.builder() - .payloadString(messageParser.getPayload()) - .signerCertificate(messageParser.getSigningCertificate()) - .rawMessage(cms) - .signature(messageParser.getSignature()) - .verified(messageParser.isSignatureVerified()) - .build(); + .payloadString(messageParser.getPayload()) + .signerCertificate(messageParser.getSigningCertificate()) + .rawMessage(cms) + .signature(messageParser.getSignature()) + .verified(messageParser.isSignatureVerified()) + .build(); } /** @@ -51,11 +51,11 @@ public static SignedStringDto getSignedString(final String cms) { public static SignedCertificateDto getSignerCertificate(final String cms) { SignedCertificateMessageParser certificateParser = new SignedCertificateMessageParser(cms); return SignedCertificateDto.builder() - .payloadCertificate(certificateParser.getPayload()) - .signerCertificate(certificateParser.getSigningCertificate()) - .rawMessage(cms) - .signature(certificateParser.getSignature()) - .verified(certificateParser.isSignatureVerified()) - .build(); + .payloadCertificate(certificateParser.getPayload()) + .signerCertificate(certificateParser.getSigningCertificate()) + .rawMessage(cms) + .signature(certificateParser.getSignature()) + .verified(certificateParser.isSignatureVerified()) + .build(); } } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/utils/ListUtils.java b/src/main/java/eu/europa/ec/dgc/gateway/utils/ListUtils.java index 64e9cf64..015bfc73 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/utils/ListUtils.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/utils/ListUtils.java @@ -25,7 +25,7 @@ public class ListUtils { - private ListUtils(){ + private ListUtils() { } /** @@ -41,7 +41,7 @@ public static List getPage(List list, int page, int size) { if (page < 0) { throw new IllegalArgumentException("Page index must not be less than zero!"); } - if (size <= 0) { + if (size <= 0) { throw new IllegalArgumentException("Page size must not be less than one!"); } diff --git a/src/main/resources/db/changelog/alter-signer-information-for-deletion.xml b/src/main/resources/db/changelog/alter-signer-information-for-deletion.xml index 981116ae..0a21d4ab 100644 --- a/src/main/resources/db/changelog/alter-signer-information-for-deletion.xml +++ b/src/main/resources/db/changelog/alter-signer-information-for-deletion.xml @@ -9,7 +9,7 @@ - + diff --git a/src/main/resources/db/changelog/fix-certificate-thumbprints.xml b/src/main/resources/db/changelog/fix-certificate-thumbprints.xml index ce51f139..41432aba 100644 --- a/src/main/resources/db/changelog/fix-certificate-thumbprints.xml +++ b/src/main/resources/db/changelog/fix-certificate-thumbprints.xml @@ -8,11 +8,15 @@ - UPDATE trusted_party SET thumbprint = concat('00', thumbprint) WHERE length(thumbprint) = 62; + UPDATE trusted_party + SET thumbprint = concat('00', thumbprint) + WHERE length(thumbprint) = 62; - UPDATE signer_information SET thumbprint = concat('00', thumbprint) WHERE length(thumbprint) = 62; + UPDATE signer_information + SET thumbprint = concat('00', thumbprint) + WHERE length(thumbprint) = 62; diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 8a6a2211..53a3b5c6 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -11,7 +11,9 @@ - timestamp="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}", level="%level", hostname="${HOSTNAME}", pid="${PID:-}", thread="%thread", class="%logger{40}", message="%replace(%replace(%m){'[\r\n]+', ', '}){'"', '\''}", trace="%X{traceId}", span="%X{spanId}", %X%n + timestamp="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}", level="%level", hostname="${HOSTNAME}", + pid="${PID:-}", thread="%thread", class="%logger{40}", message="%replace(%replace(%m){'[\r\n]+', ', + '}){'"', '\''}", trace="%X{traceId}", span="%X{spanId}", %X%n utf8 @@ -29,7 +31,10 @@ - timestamp="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}", level="%level", hostname="${HOSTNAME}", pid="${PID:-}", thread="%thread", class="%logger{40}", message="%replace(%replace(%m){'[\r\n]+', ','}){'"', '\''}", exception="%replace(%ex){'[\r\n]+', ', '}", trace="%X{traceId}", span="%X{spanId}", %X%n%nopex + timestamp="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}", level="%level", hostname="${HOSTNAME}", + pid="${PID:-}", thread="%thread", class="%logger{40}", message="%replace(%replace(%m){'[\r\n]+', + ','}){'"', '\''}", exception="%replace(%ex){'[\r\n]+', ', '}", trace="%X{traceId}", span="%X{spanId}", + %X%n%nopex utf8 diff --git a/src/test/java/eu/europa/ec/dgc/gateway/publishing/ArchivePublishingTest.java b/src/test/java/eu/europa/ec/dgc/gateway/publishing/ArchivePublishingTest.java index f0981d41..232630f4 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/publishing/ArchivePublishingTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/publishing/ArchivePublishingTest.java @@ -20,6 +20,11 @@ package eu.europa.ec.dgc.gateway.publishing; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import eu.europa.ec.dgc.gateway.client.AssetManagerClient; import eu.europa.ec.dgc.gateway.config.DgcConfigProperties; import eu.europa.ec.dgc.gateway.entity.TrustedPartyEntity; @@ -60,11 +65,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import org.mockito.Mockito; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -164,18 +165,24 @@ public void testArchiveContainsRequiredFiles() throws Exception { ArgumentCaptor uploadArchiveArgumentCaptor = ArgumentCaptor.forClass(byte[].class); ArgumentCaptor uploadSignatureArgumentCaptor = ArgumentCaptor.forClass(byte[].class); - ArgumentCaptor synchronizeFormDataArgumentCaptor = ArgumentCaptor.forClass(AssetManagerClient.SynchronizeFormData.class); - byte[] dummyByteArrayArchive = new byte[]{0xd, 0xe, 0xa, 0xd, 0xb, 0xe, 0xe, 0xf}; - byte[] dummyByteArraySignature = new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa}; + ArgumentCaptor synchronizeFormDataArgumentCaptor = + ArgumentCaptor.forClass(AssetManagerClient.SynchronizeFormData.class); + byte[] dummyByteArrayArchive = new byte[] {0xd, 0xe, 0xa, 0xd, 0xb, 0xe, 0xe, 0xf}; + byte[] dummyByteArraySignature = new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa}; - when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedArchiveName), uploadArchiveArgumentCaptor.capture())) + when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedArchiveName), uploadArchiveArgumentCaptor.capture())) .thenReturn(ResponseEntity.ok(null)); - when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedSignatureName), uploadSignatureArgumentCaptor.capture())) + when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedSignatureName), uploadSignatureArgumentCaptor.capture())) .thenReturn(ResponseEntity.ok(null)); - when(assetManagerClientMock.synchronize(eq(expectedAuthHeader), eq("true"), synchronizeFormDataArgumentCaptor.capture())) - .thenReturn(ResponseEntity.ok(new AssetManagerSynchronizeResponseDto("OK", 200, "Message", expectedPath, "token"))); + when(assetManagerClientMock.synchronize(eq(expectedAuthHeader), eq("true"), + synchronizeFormDataArgumentCaptor.capture())) + .thenReturn( + ResponseEntity.ok( + new AssetManagerSynchronizeResponseDto("OK", 200, "Message", expectedPath, "token"))); when(assetManagerClientMock.downloadFile(expectedAuthHeader, expectedUid, expectedPath, expectedArchiveName)) .thenReturn(ResponseEntity.ok(dummyByteArrayArchive)); @@ -185,19 +192,24 @@ public void testArchiveContainsRequiredFiles() throws Exception { publishingService.publishGatewayData(); - verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedArchiveName), any()); - verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedSignatureName), any()); + verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedArchiveName), any()); + verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedSignatureName), any()); verify(assetManagerClientMock).synchronize(eq(expectedAuthHeader), eq("true"), any()); verify(assetManagerClientMock).downloadFile(expectedAuthHeader, expectedUid, expectedPath, expectedArchiveName); - verify(assetManagerClientMock).downloadFile(expectedAuthHeader, expectedUid, expectedPath, expectedSignatureName); + verify(assetManagerClientMock).downloadFile(expectedAuthHeader, expectedUid, expectedPath, + expectedSignatureName); Assertions.assertNotNull(uploadArchiveArgumentCaptor.getValue()); Assertions.assertNotNull(uploadSignatureArgumentCaptor.getValue()); Assertions.assertNotNull(synchronizeFormDataArgumentCaptor.getValue()); Assertions.assertEquals(expectedPath, synchronizeFormDataArgumentCaptor.getValue().getPath()); - Assertions.assertArrayEquals(new String[]{expectedArchiveName, expectedSignatureName}, synchronizeFormDataArgumentCaptor.getValue().getNodeList().split(",")); - Assertions.assertArrayEquals(new String[]{"u1@c1.de", "u1@c2.de"}, synchronizeFormDataArgumentCaptor.getValue().getNotifyEmails().split(",")); + Assertions.assertArrayEquals(new String[] {expectedArchiveName, expectedSignatureName}, + synchronizeFormDataArgumentCaptor.getValue().getNodeList().split(",")); + Assertions.assertArrayEquals(new String[] {"u1@c1.de", "u1@c2.de"}, + synchronizeFormDataArgumentCaptor.getValue().getNotifyEmails().split(",")); Map archiveContent = readZipFile(uploadArchiveArgumentCaptor.getValue()); @@ -207,55 +219,71 @@ public void testArchiveContainsRequiredFiles() throws Exception { * Check for Static files. */ Assertions.assertTrue(archiveContent.containsKey("Readme.txt")); - Assertions.assertArrayEquals(FileUtils.readFileToByteArray(ResourceUtils.getFile("classpath:publication/Readme.txt")), archiveContent.get("Readme.txt")); + Assertions.assertArrayEquals( + FileUtils.readFileToByteArray(ResourceUtils.getFile("classpath:publication/Readme.txt")), + archiveContent.get("Readme.txt")); Assertions.assertTrue(archiveContent.containsKey("License.txt")); - Assertions.assertArrayEquals(FileUtils.readFileToByteArray(ResourceUtils.getFile("classpath:publication/License.txt")), archiveContent.get("License.txt")); + Assertions.assertArrayEquals( + FileUtils.readFileToByteArray(ResourceUtils.getFile("classpath:publication/License.txt")), + archiveContent.get("License.txt")); /* * Check for Version file */ Assertions.assertTrue(archiveContent.containsKey("Version.txt")); String versionFileContent = new String(archiveContent.get("Version.txt"), StandardCharsets.UTF_8); - ZonedDateTime parsedTimestamp = ZonedDateTime.parse(versionFileContent.substring(versionFileContent.indexOf(":") + 2).trim(), DateTimeFormatter.ISO_OFFSET_DATE_TIME); + ZonedDateTime parsedTimestamp = + ZonedDateTime.parse(versionFileContent.substring(versionFileContent.indexOf(":") + 2).trim(), + DateTimeFormatter.ISO_OFFSET_DATE_TIME); Assertions.assertTrue(ZonedDateTime.now().until(parsedTimestamp, ChronoUnit.SECONDS) < 10); /* * Check for CSCA */ - Assertions.assertTrue((archiveContent.containsKey("CSCA/DCC/C1/" + certificateUtils.getCertThumbprint(csca1) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("CSCA/DCC/C1/" + certificateUtils.getCertThumbprint(csca1) + ".pem"))); checkPemFile(csca1, archiveContent.get("CSCA/DCC/C1/" + certificateUtils.getCertThumbprint(csca1) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("CSCA/DCC/C2/" + certificateUtils.getCertThumbprint(csca2) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("CSCA/DCC/C2/" + certificateUtils.getCertThumbprint(csca2) + ".pem"))); checkPemFile(csca2, archiveContent.get("CSCA/DCC/C2/" + certificateUtils.getCertThumbprint(csca2) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("CSCA/DCC/C3/" + certificateUtils.getCertThumbprint(csca3) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("CSCA/DCC/C3/" + certificateUtils.getCertThumbprint(csca3) + ".pem"))); checkPemFile(csca3, archiveContent.get("CSCA/DCC/C3/" + certificateUtils.getCertThumbprint(csca3) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("CSCA/DCC/C4/" + certificateUtils.getCertThumbprint(csca4) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("CSCA/DCC/C4/" + certificateUtils.getCertThumbprint(csca4) + ".pem"))); checkPemFile(csca4, archiveContent.get("CSCA/DCC/C4/" + certificateUtils.getCertThumbprint(csca4) + ".pem")); /* * Check for DSC */ - Assertions.assertTrue((archiveContent.containsKey("DSC/DCC/C1/" + certificateUtils.getCertThumbprint(dsc1) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("DSC/DCC/C1/" + certificateUtils.getCertThumbprint(dsc1) + ".pem"))); checkPemFile(dsc1, archiveContent.get("DSC/DCC/C1/" + certificateUtils.getCertThumbprint(dsc1) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("DSC/DCC/C2/" + certificateUtils.getCertThumbprint(dsc2) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("DSC/DCC/C2/" + certificateUtils.getCertThumbprint(dsc2) + ".pem"))); checkPemFile(dsc2, archiveContent.get("DSC/DCC/C2/" + certificateUtils.getCertThumbprint(dsc2) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("DSC/DCC/C3/" + certificateUtils.getCertThumbprint(dsc3) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("DSC/DCC/C3/" + certificateUtils.getCertThumbprint(dsc3) + ".pem"))); checkPemFile(dsc3, archiveContent.get("DSC/DCC/C3/" + certificateUtils.getCertThumbprint(dsc3) + ".pem")); - Assertions.assertTrue((archiveContent.containsKey("DSC/DCC/C4/" + certificateUtils.getCertThumbprint(dsc4) + ".pem"))); + Assertions.assertTrue( + (archiveContent.containsKey("DSC/DCC/C4/" + certificateUtils.getCertThumbprint(dsc4) + ".pem"))); checkPemFile(dsc4, archiveContent.get("DSC/DCC/C4/" + certificateUtils.getCertThumbprint(dsc4) + ".pem")); /* * Check Signature */ - SignedByteArrayMessageParser parser = new SignedByteArrayMessageParser(uploadSignatureArgumentCaptor.getValue(), Base64.getEncoder().encode(uploadArchiveArgumentCaptor.getValue())); + SignedByteArrayMessageParser parser = new SignedByteArrayMessageParser(uploadSignatureArgumentCaptor.getValue(), + Base64.getEncoder().encode(uploadArchiveArgumentCaptor.getValue())); Assertions.assertEquals(SignedMessageParser.ParserState.SUCCESS, parser.getParserState()); - Assertions.assertArrayEquals(dgcTestKeyStore.getPublicationSigner().getEncoded(), parser.getSigningCertificate().getEncoded()); + Assertions.assertArrayEquals(dgcTestKeyStore.getPublicationSigner().getEncoded(), + parser.getSigningCertificate().getEncoded()); Assertions.assertTrue(parser.isSignatureVerified()); /* @@ -273,17 +301,19 @@ public void testArchiveContainsRequiredFiles() throws Exception { @Test public void testSynchronizeDisabled() { - when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedArchiveName), any())) + when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedArchiveName), any())) .thenReturn(ResponseEntity.ok(null)); - when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedSignatureName), any())) + when(assetManagerClientMock.uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedSignatureName), any())) .thenReturn(ResponseEntity.ok(null)); when(assetManagerClientMock.downloadFile(expectedAuthHeader, expectedUid, expectedPath, expectedArchiveName)) - .thenReturn(ResponseEntity.ok(new byte[]{})); + .thenReturn(ResponseEntity.ok(new byte[] {})); when(assetManagerClientMock.downloadFile(expectedAuthHeader, expectedUid, expectedPath, expectedSignatureName)) - .thenReturn(ResponseEntity.ok(new byte[]{})); + .thenReturn(ResponseEntity.ok(new byte[] {})); properties.getPublication().setSynchronizeEnabled(false); @@ -291,16 +321,19 @@ public void testSynchronizeDisabled() { properties.getPublication().setSynchronizeEnabled(true); - verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedArchiveName), any()); - verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), eq(expectedSignatureName), any()); + verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedArchiveName), any()); + verify(assetManagerClientMock).uploadFile(eq(expectedAuthHeader), eq(expectedUid), eq(expectedPath), + eq(expectedSignatureName), any()); verify(assetManagerClientMock, Mockito.never()).synchronize(eq(expectedAuthHeader), eq("true"), any()); } - private void checkPemFile(X509Certificate expected, byte[] pemFile) throws IOException, CertificateEncodingException { + private void checkPemFile(X509Certificate expected, byte[] pemFile) + throws IOException, CertificateEncodingException { try ( - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pemFile); - InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream); - PEMParser pemParser = new PEMParser(inputStreamReader) + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pemFile); + InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream); + PEMParser pemParser = new PEMParser(inputStreamReader) ) { Object object = pemParser.readObject(); Assertions.assertTrue(object instanceof X509CertificateHolder); diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationControllerTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationControllerTest.java index ddd7c52f..fcc7266f 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationControllerTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateMigrationControllerTest.java @@ -112,7 +112,7 @@ void setUp() { JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer( - new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX").toFormatter() + new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX").toFormatter() )); objectMapper.registerModule(javaTimeModule); @@ -122,14 +122,16 @@ void setUp() { @Test void testAllCertTypes() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ec"); - X509Certificate certDscEu = CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), countryCode, "Test"); + X509Certificate certDscEu = + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), countryCode, "Test"); String cmsBase64 = Base64.getEncoder().encodeToString(certDscEu.getEncoded()); SignedCertificateMessageBuilder messageBuilder = new SignedCertificateMessageBuilder() - .withPayload(certificateUtils.convertCertificate(certDscEu)) - .withSigningCertificate( - certificateUtils.convertCertificate(trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode)), - trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode)); + .withPayload(certificateUtils.convertCertificate(certDscEu)) + .withSigningCertificate( + certificateUtils.convertCertificate( + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode)), + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode)); String detachedSignature = messageBuilder.buildAsString(true); @@ -137,21 +139,23 @@ void testAllCertTypes() throws Exception { createRevocation("id1", cmsBase64, false); createValidationEntry(cmsBase64); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); MvcResult mvcResult = mockMvc.perform(get("/cms-migration") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].type", is(CmsPackageDto.CmsPackageTypeDto.DSC.name()))) - .andExpect(jsonPath("$[1].type", is(CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST.name()))) - .andExpect(jsonPath("$[1].cms", is(cmsBase64))) - .andExpect(jsonPath("$[2].type", is(CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE.name()))) - .andExpect(jsonPath("$[2].cms", is(cmsBase64))) - .andReturn(); - - List response = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<>() { - }); + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0].type", is(CmsPackageDto.CmsPackageTypeDto.DSC.name()))) + .andExpect(jsonPath("$[1].type", is(CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST.name()))) + .andExpect(jsonPath("$[1].cms", is(cmsBase64))) + .andExpect(jsonPath("$[2].type", is(CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE.name()))) + .andExpect(jsonPath("$[2].cms", is(cmsBase64))) + .andReturn(); + + List response = + objectMapper.readValue(mvcResult.getResponse().getContentAsString(), new TypeReference<>() { + }); SignedCertificateMessageParser parser = new SignedCertificateMessageParser(response.get(0).getCms()); Assertions.assertEquals(SignedMessageParser.ParserState.SUCCESS, parser.getParserState()); Assertions.assertTrue(parser.isSignatureVerified()); @@ -161,176 +165,219 @@ void testAllCertTypes() throws Exception { @Test void testRevocationDeleted() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ec"); - X509Certificate certDscEu = CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), countryCode, "Test"); + X509Certificate certDscEu = + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), countryCode, "Test"); String cmsBase64 = Base64.getEncoder().encodeToString(certDscEu.getEncoded()); createRevocation("id1", null, true); RevocationBatchEntity entity = createRevocation("id2", cmsBase64, false); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/cms-migration") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) - .andExpect(jsonPath("$", hasSize(1))) - .andExpect(jsonPath("$[0].entityId", is(entity.getId()), Long.class)) - .andExpect(jsonPath("$[0].cms", is(cmsBase64))); + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].entityId", is(entity.getId()), Long.class)) + .andExpect(jsonPath("$[0].cms", is(cmsBase64))); } @Test void testNoneForCountry() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/cms-migration") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) - .andExpect(jsonPath("$", hasSize(0))); + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject)) + .andExpect(jsonPath("$", hasSize(0))); } @Test void testUpdateDSC() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String existingPayload = new SignedCertificateMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) + .buildAsString(); SignedCertificateMessageParser parser = new SignedCertificateMessageParser(existingPayload); - SignerInformationEntity existingEntity = createSignerInfoEntity(existingPayload, parser.getSignature(), certificateUtils.getCertThumbprint(payloadCertificate)); + SignerInformationEntity existingEntity = createSignerInfoEntity(existingPayload, parser.getSignature(), + certificateUtils.getCertThumbprint(payloadCertificate)); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.CSCA, countryCode); - X509Certificate signerCertificateUpdate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKeyUpdate = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificateUpdate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKeyUpdate = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificateUpdate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKeyUpdate = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificateUpdate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKeyUpdate = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPairUpdate = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificateUpdate = CertificateTestUtils.generateCertificate(payloadKeyPairUpdate, countryCode, "Payload Cert", cscaCertificateUpdate, cscaPrivateKeyUpdate); + X509Certificate payloadCertificateUpdate = + CertificateTestUtils.generateCertificate(payloadKeyPairUpdate, countryCode, "Payload Cert", + cscaCertificateUpdate, cscaPrivateKeyUpdate); String updatePayload = new SignedCertificateMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificateUpdate), signerPrivateKeyUpdate) - .withPayload(new X509CertificateHolder(payloadCertificateUpdate.getEncoded())) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificateUpdate), + signerPrivateKeyUpdate) + .withPayload(new X509CertificateHolder(payloadCertificateUpdate.getEncoded())) + .buildAsString(); String updatedSignature = new SignedCertificateMessageParser(updatePayload).getSignature(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, existingEntity.getId(), CmsPackageDto.CmsPackageTypeDto.DSC); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, existingEntity.getId(), CmsPackageDto.CmsPackageTypeDto.DSC); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNoContent()); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNoContent()); Optional updatedCert = signerInformationRepository.findById(existingEntity.getId()); Assertions.assertTrue(updatedCert.isPresent()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificateUpdate.getEncoded()), updatedCert.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificateUpdate.getEncoded()), + updatedCert.get().getRawData()); Assertions.assertEquals(updatedSignature, updatedCert.get().getSignature()); } @Test void testUpdateDSCNotFound() throws Exception { - X509Certificate signerCertificateUpdate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKeyUpdate = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificateUpdate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKeyUpdate = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificateUpdate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKeyUpdate = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificateUpdate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKeyUpdate = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPairUpdate = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificateUpdate = CertificateTestUtils.generateCertificate(payloadKeyPairUpdate, countryCode, "Payload Cert", cscaCertificateUpdate, cscaPrivateKeyUpdate); + X509Certificate payloadCertificateUpdate = + CertificateTestUtils.generateCertificate(payloadKeyPairUpdate, countryCode, "Payload Cert", + cscaCertificateUpdate, cscaPrivateKeyUpdate); String updatePayload = new SignedCertificateMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificateUpdate), signerPrivateKeyUpdate) - .withPayload(new X509CertificateHolder(payloadCertificateUpdate.getEncoded())) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificateUpdate), + signerPrivateKeyUpdate) + .withPayload(new X509CertificateHolder(payloadCertificateUpdate.getEncoded())) + .buildAsString(); CmsPackageDto dto = new CmsPackageDto(updatePayload, 404L, CmsPackageDto.CmsPackageTypeDto.DSC); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isConflict()) - .andExpect(jsonPath("$.code", is("0x010"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code", is("0x010"))); } @Test void testUpdateDSCCMSinvalid() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String existingPayload = new SignedCertificateMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) + .buildAsString(); SignedCertificateMessageParser parser = new SignedCertificateMessageParser(existingPayload); - SignerInformationEntity existingEntity = createSignerInfoEntity(existingPayload, parser.getSignature(), certificateUtils.getCertThumbprint(payloadCertificate)); + SignerInformationEntity existingEntity = createSignerInfoEntity(existingPayload, parser.getSignature(), + certificateUtils.getCertThumbprint(payloadCertificate)); - CmsPackageDto dto = new CmsPackageDto("invalidCMS", existingEntity.getId(), CmsPackageDto.CmsPackageTypeDto.DSC); + CmsPackageDto dto = + new CmsPackageDto("invalidCMS", existingEntity.getId(), CmsPackageDto.CmsPackageTypeDto.DSC); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x260"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x260"))); } @Test void testUpdateValidationRule() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); ValidationRuleEntity entity = createValidationEntry(payload); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNoContent()); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNoContent()); Optional updatedRule = - validationRuleRepository.findById(entity.getId()); + validationRuleRepository.findById(entity.getId()); Assertions.assertTrue(updatedRule.isPresent()); Assertions.assertEquals(updatePayload, updatedRule.get().getCms()); @@ -338,39 +385,45 @@ void testUpdateValidationRule() throws Exception { @Test void testUpdateValidationRulePayloadNotMatching() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); ValidationRuleEntity entity = createValidationEntry(existingPayload); validationRule.setIdentifier("MISMATCH"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x032"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x032"))); Optional updatedRule = - validationRuleRepository.findById(entity.getId()); + validationRuleRepository.findById(entity.getId()); Assertions.assertTrue(updatedRule.isPresent()); Assertions.assertEquals(existingPayload, updatedRule.get().getCms()); @@ -378,88 +431,101 @@ void testUpdateValidationRulePayloadNotMatching() throws Exception { @Test void testUpdateValidationRulePayloadNotFound() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setIdentifier("MISMATCH"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); CmsPackageDto dto = new CmsPackageDto(updatePayload, 404L, CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isConflict()) - .andExpect(jsonPath("$.code", is("0x030"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code", is("0x030"))); } @Test void testUpdateValidationRuleInvalidCMS() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); ValidationRuleEntity entity = createValidationEntry(existingPayload); - CmsPackageDto dto = new CmsPackageDto("invalidCms", entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); + CmsPackageDto dto = + new CmsPackageDto("invalidCms", entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x260"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x260"))); } @Test void testUpdateValidationRuleWrongCountry() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); ValidationRuleEntity entity = createValidationEntry(existingPayload, "DE"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.VALIDATION_RULE); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x031"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x031"))); Optional updatedRule = - validationRuleRepository.findById(entity.getId()); + validationRuleRepository.findById(entity.getId()); Assertions.assertTrue(updatedRule.isPresent()); Assertions.assertEquals(existingPayload, updatedRule.get().getCms()); @@ -467,38 +533,44 @@ void testUpdateValidationRuleWrongCountry() throws Exception { @Test void testUpdateRevocation() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash2 = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash2 = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); RevocationBatchDto revocationBatch = createRevocationBatch("kid1"); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); RevocationBatchEntity entity = createRevocationBatchEntity(existingPayload); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNoContent()); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNoContent()); Optional updatedBatch = - revocationBatchRepository.findById(entity.getId()); + revocationBatchRepository.findById(entity.getId()); Assertions.assertTrue(updatedBatch.isPresent()); Assertions.assertEquals(updatePayload, updatedBatch.get().getSignedBatch()); @@ -506,41 +578,47 @@ void testUpdateRevocation() throws Exception { @Test void testUpdateRevocationPayloadNotMatching() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash2 = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash2 = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); RevocationBatchDto revocationBatch = createRevocationBatch("kid1"); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); RevocationBatchEntity entity = createRevocationBatchEntity(existingPayload); RevocationBatchDto revocationBatchUnmatch = createRevocationBatch("kid2"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(revocationBatchUnmatch)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(revocationBatchUnmatch)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x022"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x022"))); Optional updatedBatch = - revocationBatchRepository.findById(entity.getId()); + revocationBatchRepository.findById(entity.getId()); Assertions.assertTrue(updatedBatch.isPresent()); Assertions.assertEquals(existingPayload, updatedBatch.get().getSignedBatch()); @@ -548,56 +626,63 @@ void testUpdateRevocationPayloadNotMatching() throws Exception { @Test void testUpdateRevocationPayloadNotFound() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); RevocationBatchDto revocationBatch = createRevocationBatch("kid1"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); CmsPackageDto dto = new CmsPackageDto(updatePayload, 404L, CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isConflict()) - .andExpect(jsonPath("$.code", is("0x020"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.code", is("0x020"))); } @Test void testUpdateRevocationInvalidCMS() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); RevocationBatchDto revocationBatch = createRevocationBatch("kid1"); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); RevocationBatchEntity entity = createRevocationBatchEntity(existingPayload); - CmsPackageDto dto = new CmsPackageDto("invalidCms", entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); + CmsPackageDto dto = + new CmsPackageDto("invalidCms", entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x260"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x260"))); Optional updatedBatch = - revocationBatchRepository.findById(entity.getId()); + revocationBatchRepository.findById(entity.getId()); Assertions.assertTrue(updatedBatch.isPresent()); Assertions.assertEquals(existingPayload, updatedBatch.get().getSignedBatch()); @@ -605,53 +690,60 @@ void testUpdateRevocationInvalidCMS() throws Exception { @Test void testUpdateRevocationWrongCountry() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); trustedPartyTestHelper.clear(TrustedPartyEntity.CertificateType.UPLOAD, "DE"); - X509Certificate signerCertificate2 = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey2 = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash2 = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate2 = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey2 = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash2 = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); RevocationBatchDto revocationBatch = createRevocationBatch("kid1"); revocationBatch.setCountry("DE"); String existingPayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); RevocationBatchEntity entity = createRevocationBatchEntity(existingPayload, "DE"); String updatePayload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) - .withPayload(objectMapper.writeValueAsString(revocationBatch)) - .buildAsString(); - CmsPackageDto dto = new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate2), signerPrivateKey2) + .withPayload(objectMapper.writeValueAsString(revocationBatch)) + .buildAsString(); + CmsPackageDto dto = + new CmsPackageDto(updatePayload, entity.getId(), CmsPackageDto.CmsPackageTypeDto.REVOCATION_LIST); mockMvc.perform(post("/cms-migration") - .contentType("application/json") - .content(objectMapper.writeValueAsString(dto)) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code", is("0x021"))); + .contentType("application/json") + .content(objectMapper.writeValueAsString(dto)) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash2) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code", is("0x021"))); } private void createSignerInfo(final String cmsBase64, final X509Certificate certDscEu, final String signature) { signerInformationRepository.save(new SignerInformationEntity( - null, ZonedDateTime.now(), null, countryCode, certificateUtils.getCertThumbprint(certDscEu), - cmsBase64, signature, SignerInformationEntity.CertificateType.DSC + null, ZonedDateTime.now(), null, countryCode, certificateUtils.getCertThumbprint(certDscEu), + cmsBase64, signature, SignerInformationEntity.CertificateType.DSC )); } private RevocationBatchEntity createRevocation(final String batchId, final String cmsBase64, boolean deleted) { RevocationBatchEntity revocationBatchEntity = new RevocationBatchEntity( - null, batchId, countryCode, ZonedDateTime.now(), ZonedDateTime.now().plusDays(2), - deleted, RevocationBatchEntity.RevocationHashType.SIGNATURE, "UNKNOWN_KID", cmsBase64); + null, batchId, countryCode, ZonedDateTime.now(), ZonedDateTime.now().plusDays(2), + deleted, RevocationBatchEntity.RevocationHashType.SIGNATURE, "UNKNOWN_KID", cmsBase64); return revocationBatchRepository.save(revocationBatchEntity); } - private SignerInformationEntity createSignerInfoEntity(final String cms, final String signature, final String thumbprint) { + private SignerInformationEntity createSignerInfoEntity(final String cms, final String signature, + final String thumbprint) { SignerInformationEntity signerInformationEntity = new SignerInformationEntity(); signerInformationEntity.setCertificateType(SignerInformationEntity.CertificateType.DSC); signerInformationEntity.setRawData(cms); @@ -702,11 +794,11 @@ private RevocationBatchDto createRevocationBatch(String kid) { revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid(kid); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto("aaaaaaaaaaaaaaaaaaaaaaaa"), - new RevocationBatchDto.BatchEntryDto("bbbbbbbbbbbbbbbbbbbbbbbb"), - new RevocationBatchDto.BatchEntryDto("cccccccccccccccccccccccc"), - new RevocationBatchDto.BatchEntryDto("dddddddddddddddddddddddd"), - new RevocationBatchDto.BatchEntryDto("eeeeeeeeeeeeeeeeeeeeeeee") + new RevocationBatchDto.BatchEntryDto("aaaaaaaaaaaaaaaaaaaaaaaa"), + new RevocationBatchDto.BatchEntryDto("bbbbbbbbbbbbbbbbbbbbbbbb"), + new RevocationBatchDto.BatchEntryDto("cccccccccccccccccccccccc"), + new RevocationBatchDto.BatchEntryDto("dddddddddddddddddddddddd"), + new RevocationBatchDto.BatchEntryDto("eeeeeeeeeeeeeeeeeeeeeeee") )); return revocationBatchDto; } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListIntegrationTest.java index 133bfdf1..5bf18074 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CertificateRevocationListIntegrationTest.java @@ -110,7 +110,7 @@ public void setup() { JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer( - new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX").toFormatter() + new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX").toFormatter() )); objectMapper.registerModule(javaTimeModule); @@ -128,8 +128,10 @@ void testSuccessfulUpload() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto revocationBatchDto = new RevocationBatchDto(); revocationBatchDto.setCountry(countryCode); @@ -137,49 +139,58 @@ void testSuccessfulUpload() throws Exception { revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid("UNKNOWN_KID"); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) )); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); MvcResult mvcResult = mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) ).andReturn(); Assertions.assertEquals(HttpStatus.CREATED.value(), mvcResult.getResponse().getStatus()); Assertions.assertEquals(revocationBatchesInDb + 1, revocationBatchRepository.count()); Optional createdRevocationBatch = - revocationBatchRepository.findAll().stream().findFirst(); + revocationBatchRepository.findAll().stream().findFirst(); Assertions.assertTrue(createdRevocationBatch.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(revocationBatchDto.getExpires().toEpochSecond(), createdRevocationBatch.get().getExpires().toEpochSecond()); + Assertions.assertEquals(revocationBatchDto.getExpires().toEpochSecond(), + createdRevocationBatch.get().getExpires().toEpochSecond()); Assertions.assertTrue( - ZonedDateTime.now().toEpochSecond() - 2 < createdRevocationBatch.get().getChanged().toEpochSecond() - && ZonedDateTime.now().toEpochSecond() + 2 > createdRevocationBatch.get().getChanged().toEpochSecond()); + ZonedDateTime.now().toEpochSecond() - 2 < createdRevocationBatch.get().getChanged().toEpochSecond() + && ZonedDateTime.now().toEpochSecond() + 2 > createdRevocationBatch.get().getChanged().toEpochSecond()); Assertions.assertEquals(countryCode, createdRevocationBatch.get().getCountry()); Assertions.assertEquals(revocationBatchDto.getHashType().name(), createdRevocationBatch.get().getType().name()); Assertions.assertEquals(revocationBatchDto.getKid(), createdRevocationBatch.get().getKid()); - Assertions.assertEquals(createdRevocationBatch.get().getBatchId(), mvcResult.getResponse().getHeader(HttpHeaders.ETAG)); + Assertions.assertEquals(createdRevocationBatch.get().getBatchId(), + mvcResult.getResponse().getHeader(HttpHeaders.ETAG)); Assertions.assertEquals(36, createdRevocationBatch.get().getBatchId().length()); SignedStringMessageParser parser = new SignedStringMessageParser(createdRevocationBatch.get().getSignedBatch()); - RevocationBatchDto parsedRevocationBatch = objectMapper.readValue(parser.getPayload(), RevocationBatchDto.class); + RevocationBatchDto parsedRevocationBatch = + objectMapper.readValue(parser.getPayload(), RevocationBatchDto.class); assertEquals(revocationBatchDto, parsedRevocationBatch); } @@ -189,24 +200,27 @@ void testUploadFailedInvalidJson() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload("randomBadString") - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload("randomBadString") + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); @@ -218,8 +232,10 @@ void testUploadFailedInvalidJsonValues() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto revocationBatchDto = new RevocationBatchDto(); revocationBatchDto.setCountry(countryCode); @@ -227,29 +243,35 @@ void testUploadFailedInvalidJsonValues() throws Exception { revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid("KIDWHICHISWAYTOLONGTOPASS"); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) )); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(header().doesNotExist(HttpHeaders.ETAG)); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(header().doesNotExist(HttpHeaders.ETAG)); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -257,16 +279,18 @@ void testUploadFailedInvalidJsonValues() throws Exception { @ParameterizedTest @ValueSource(strings = { - "ccccccccccccccccccccccccA", - "__thisIsNoValidBase64___", - "CgoKCgoKCgoKCgoKCgoKCgo=" // this base64 string is too long (17 bytes) + "ccccccccccccccccccccccccA", + "__thisIsNoValidBase64___", + "CgoKCgoKCgoKCgoKCgoKCgo=" // this base64 string is too long (17 bytes) }) void testUploadFailedInvalidJsonValuesInHashEntries(String invalidHash) throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto revocationBatchDto = new RevocationBatchDto(); revocationBatchDto.setCountry(countryCode); @@ -274,28 +298,32 @@ void testUploadFailedInvalidJsonValuesInHashEntries(String invalidHash) throws E revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid("UNKNOWN_KID"); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), - new RevocationBatchDto.BatchEntryDto(invalidHash), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})) + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), + new RevocationBatchDto.BatchEntryDto(invalidHash), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})) )); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(header().doesNotExist(HttpHeaders.ETAG)); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()) + .andExpect(header().doesNotExist(HttpHeaders.ETAG)); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -306,8 +334,10 @@ void testUploadFailedInvalidCountry() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto revocationBatchDto = new RevocationBatchDto(); revocationBatchDto.setCountry("XX"); @@ -315,29 +345,35 @@ void testUploadFailedInvalidCountry() throws Exception { revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid("UNKNOWN_KID"); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb, 0xb})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc, 0xc})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd, 0xd})), + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe, 0xe})) )); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()) - .andExpect(header().doesNotExist(HttpHeaders.ETAG)); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()) + .andExpect(header().doesNotExist(HttpHeaders.ETAG)); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -360,26 +396,29 @@ void testDeleteRevocationBatch() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNoContent()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNoContent()); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); @@ -387,8 +426,10 @@ void testDeleteRevocationBatch() throws Exception { RevocationBatchEntity deletedBatch = revocationBatchRepository.findAll().get(0); Assertions.assertNull(deletedBatch.getSignedBatch()); Assertions.assertTrue(deletedBatch.getDeleted()); - Assertions.assertTrue(deletedBatch.getChanged().toEpochSecond() > ZonedDateTime.now().minusSeconds(2).toEpochSecond()); - Assertions.assertTrue(deletedBatch.getChanged().toEpochSecond() < ZonedDateTime.now().plusSeconds(2).toEpochSecond()); + Assertions.assertTrue( + deletedBatch.getChanged().toEpochSecond() > ZonedDateTime.now().minusSeconds(2).toEpochSecond()); + Assertions.assertTrue( + deletedBatch.getChanged().toEpochSecond() < ZonedDateTime.now().plusSeconds(2).toEpochSecond()); } @@ -409,26 +450,29 @@ void testDeleteRevocationBatchAlternativeEndpoint() throws Exception { long revocationBatchesInDb = revocationBatchRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(post("/revocation-list/delete") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNoContent()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNoContent()); Assertions.assertEquals(revocationBatchesInDb, revocationBatchRepository.count()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); @@ -436,8 +480,10 @@ void testDeleteRevocationBatchAlternativeEndpoint() throws Exception { RevocationBatchEntity deletedBatch = revocationBatchRepository.findAll().get(0); Assertions.assertNull(deletedBatch.getSignedBatch()); Assertions.assertTrue(deletedBatch.getDeleted()); - Assertions.assertTrue(deletedBatch.getChanged().toEpochSecond() > ZonedDateTime.now().minusSeconds(2).toEpochSecond()); - Assertions.assertTrue(deletedBatch.getChanged().toEpochSecond() < ZonedDateTime.now().plusSeconds(2).toEpochSecond()); + Assertions.assertTrue( + deletedBatch.getChanged().toEpochSecond() > ZonedDateTime.now().minusSeconds(2).toEpochSecond()); + Assertions.assertTrue( + deletedBatch.getChanged().toEpochSecond() < ZonedDateTime.now().plusSeconds(2).toEpochSecond()); } @Test @@ -455,24 +501,27 @@ void testDeleteRevocationBatchFailedInvalidJson() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload("randomString") - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload("randomString") + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -495,24 +544,27 @@ void testDeleteRevocationBatchFailedInvalidJsonValue() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(new RevocationBatchDeleteRequestDto("ThisIsNotAnUUID"))) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(new RevocationBatchDeleteRequestDto("ThisIsNotAnUUID"))) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -535,24 +587,28 @@ void testDeleteRevocationBatchFailedBatchNotFound() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(new RevocationBatchDeleteRequestDto(UUID.randomUUID().toString()))) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload( + objectMapper.writeValueAsString(new RevocationBatchDeleteRequestDto(UUID.randomUUID().toString()))) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNotFound()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNotFound()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -575,26 +631,28 @@ void testDeleteRevocationBatchFailedInvalidCountry() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, "XX"); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), "C=XX") - ) - .andExpect(status().isForbidden()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), "C=XX") + ) + .andExpect(status().isForbidden()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -617,26 +675,29 @@ void testDeleteRevocationBatchFailedUploadDoesNotMatchAuth() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -659,26 +720,29 @@ void testDeleteRevocationBatchFailedInvalidCmsSignature() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -701,26 +765,29 @@ void testDeleteRevocationBatchFailedGone() throws Exception { long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(entity.getBatchId()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isGone()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isGone()); Assertions.assertEquals(auditEventEntitiesInDb, auditEventRepository.count()); @@ -746,117 +813,129 @@ void testDownloadBatchList() throws Exception { entities.add(revocationBatchRepository.save(entity)); } - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(0).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(true)) - .andExpect(jsonPath("$.batches.length()").value(1000)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(0, 1000))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(0).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(true)) + .andExpect(jsonPath("$.batches.length()").value(1000)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(0, 1000))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(1000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(true)) - .andExpect(jsonPath("$.batches.length()").value(1000)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(1000, 2000))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(1000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(true)) + .andExpect(jsonPath("$.batches.length()").value(1000)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(1000, 2000))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(2000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(true)) - .andExpect(jsonPath("$.batches.length()").value(1000)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(2000, 3000))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(2000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(true)) + .andExpect(jsonPath("$.batches.length()").value(1000)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(2000, 3000))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(3000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(true)) - .andExpect(jsonPath("$.batches.length()").value(1000)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(3000, 4000))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(3000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(true)) + .andExpect(jsonPath("$.batches.length()").value(1000)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(3000, 4000))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(4000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(true)) - .andExpect(jsonPath("$.batches.length()").value(1000)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(4000, 5000))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(4000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(true)) + .andExpect(jsonPath("$.batches.length()").value(1000)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(4000, 5000))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(5000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.more").value(false)) - .andExpect(jsonPath("$.batches.length()").value(500)) - .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(5000, 5500))); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(5000).getChanged().minusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.more").value(false)) + .andExpect(jsonPath("$.batches.length()").value(500)) + .andDo(r -> evaluateDownloadedBatchList(r.getResponse(), entities.subList(5000, 5500))); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, entities.get(5499).getChanged().plusSeconds(1).toOffsetDateTime().toString()) - ) - .andExpect(status().isNoContent()); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, + entities.get(5499).getChanged().plusSeconds(1).toOffsetDateTime().toString()) + ) + .andExpect(status().isNoContent()); } @Test void testDownloadBatchListFailedNoIfModifiedSince() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); } @Test void testDownloadBatchListFailedIfModifiedSinceInFuture() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, OffsetDateTime.now().plusSeconds(1).toString()) - ) - .andExpect(status().isBadRequest()); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, OffsetDateTime.now().plusSeconds(1).toString()) + ) + .andExpect(status().isBadRequest()); } @Test void testDownloadRevocationBatch() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto batchDto = new RevocationBatchDto(); batchDto.setCountry(countryCode); @@ -866,9 +945,9 @@ void testDownloadRevocationBatch() throws Exception { batchDto.setEntries(List.of(new RevocationBatchDto.BatchEntryDto("abcd"))); String signedBatch = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(batchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(batchDto)) + .buildAsString(); RevocationBatchEntity entity = new RevocationBatchEntity(); entity.setType(RevocationBatchEntity.RevocationHashType.SIGNATURE); @@ -881,39 +960,43 @@ void testDownloadRevocationBatch() throws Exception { entity.setCountry(countryCode); revocationBatchRepository.save(entity); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list/" + entity.getBatchId()) - .accept("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andDo(result -> { - SignedStringMessageParser parser = new SignedStringMessageParser(result.getResponse().getContentAsString()); - - Assertions.assertEquals(SignedMessageParser.ParserState.SUCCESS, parser.getParserState()); - Assertions.assertTrue(parser.isSignatureVerified()); - Assertions.assertArrayEquals(signerCertificate.getEncoded(), parser.getSigningCertificate().getEncoded()); - - RevocationBatchDto parsedBatch = objectMapper.readValue(parser.getPayload(), RevocationBatchDto.class); - - assertEquals(batchDto, parsedBatch); - }); + .accept("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isOk()) + .andDo(result -> { + SignedStringMessageParser parser = + new SignedStringMessageParser(result.getResponse().getContentAsString()); + + Assertions.assertEquals(SignedMessageParser.ParserState.SUCCESS, parser.getParserState()); + Assertions.assertTrue(parser.isSignatureVerified()); + Assertions.assertArrayEquals(signerCertificate.getEncoded(), + parser.getSigningCertificate().getEncoded()); + + RevocationBatchDto parsedBatch = objectMapper.readValue(parser.getPayload(), RevocationBatchDto.class); + + assertEquals(batchDto, parsedBatch); + }); } @Test void testDownloadRevocationBatchInvalidBatchId() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list/thisIsNotAnUUID") - .accept("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .accept("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); } @Test @@ -930,34 +1013,38 @@ void testDownloadRevocationBatchGone() throws Exception { entity.setCountry(countryCode); revocationBatchRepository.save(entity); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list/" + entity.getBatchId()) - .accept("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isGone()); + .accept("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isGone()); } @Test void testDownloadRevocationBatchNotFound() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(get("/revocation-list/" + UUID.randomUUID()) - .accept("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNotFound()); + .accept("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isNotFound()); } - private void evaluateDownloadedBatchList(MockHttpServletResponse mockResponse, List expectedBatches) throws UnsupportedEncodingException, JsonProcessingException { + private void evaluateDownloadedBatchList(MockHttpServletResponse mockResponse, + List expectedBatches) + throws UnsupportedEncodingException, JsonProcessingException { RevocationBatchListDto revocationBatchListDto = - objectMapper.readValue(mockResponse.getContentAsString(), RevocationBatchListDto.class); + objectMapper.readValue(mockResponse.getContentAsString(), RevocationBatchListDto.class); Assertions.assertEquals(expectedBatches.size(), revocationBatchListDto.getBatches().size()); @@ -966,7 +1053,8 @@ private void evaluateDownloadedBatchList(MockHttpServletResponse mockResponse, L } } - private static void assertEquals(RevocationBatchEntity expected, RevocationBatchListDto.RevocationBatchListItemDto actual) { + private static void assertEquals(RevocationBatchEntity expected, + RevocationBatchListDto.RevocationBatchListItemDto actual) { Assertions.assertEquals(expected.getBatchId(), actual.getBatchId()); Assertions.assertEquals(expected.getChanged().toEpochSecond(), actual.getDate().toEpochSecond()); Assertions.assertEquals(expected.getCountry(), actual.getCountry()); @@ -997,54 +1085,63 @@ public static void assertEquals(RevocationBatchEntity expected, RevocationBatchE @Test void testDownloadBatchListRequiresCorrectRole() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); - trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER, + TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(get("/revocation-list") - .accept("application/json") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - .header(HttpHeaders.IF_MODIFIED_SINCE, OffsetDateTime.now().toString()) - ) - .andExpect(status().isForbidden()); + .accept("application/json") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + .header(HttpHeaders.IF_MODIFIED_SINCE, OffsetDateTime.now().toString()) + ) + .andExpect(status().isForbidden()); } @Test void testDeleteRevocationBatchRequiresCorrectRole() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - RevocationBatchDeleteRequestDto deleteRequestDto = new RevocationBatchDeleteRequestDto(UUID.randomUUID().toString()); + RevocationBatchDeleteRequestDto deleteRequestDto = + new RevocationBatchDeleteRequestDto(UUID.randomUUID().toString()); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(deleteRequestDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); - trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER, + TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER); mockMvc.perform(delete("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()); mockMvc.perform(post("/revocation-list/delete") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()); } @Test void testUploadRequiresCorrectRole() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); RevocationBatchDto revocationBatchDto = new RevocationBatchDto(); revocationBatchDto.setCountry(countryCode); @@ -1052,36 +1149,41 @@ void testUploadRequiresCorrectRole() throws Exception { revocationBatchDto.setHashType(RevocationHashTypeDto.SIGNATURE); revocationBatchDto.setKid("UNKNOWN_KID"); revocationBatchDto.setEntries(List.of( - new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString(new byte[]{0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})))); + new RevocationBatchDto.BatchEntryDto(Base64.getEncoder().encodeToString( + new byte[] {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa})))); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(revocationBatchDto)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); - trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_LIST_READER, + TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER); mockMvc.perform(post("/revocation-list") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()) - .andExpect(header().doesNotExist(HttpHeaders.ETAG)); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()) + .andExpect(header().doesNotExist(HttpHeaders.ETAG)); } @Test void testDownloadRevocationBatchRequiresCorrectRole() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); - trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER, TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + trustedPartyTestHelper.setRoles(countryCode, TrustedPartyEntity.CertificateRoles.REVOCATION_DELETER, + TrustedPartyEntity.CertificateRoles.REVOCATION_UPLOADER); mockMvc.perform(get("/revocation-list/" + UUID.randomUUID()) - .accept("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()); + .accept("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isForbidden()); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CountryListIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CountryListIntegrationTest.java index 52f85dcc..4eb53498 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CountryListIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/CountryListIntegrationTest.java @@ -69,17 +69,18 @@ void testGetTrustedParties() throws Exception { trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, "AC"); trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, "AD"); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/countrylist") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.length()").value(5)) - .andExpect(jsonPath("$[0]").value("AA")) + ) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.length()").value(5)) + .andExpect(jsonPath("$[0]").value("AA")) .andExpect(jsonPath("$[1]").value("AB")) .andExpect(jsonPath("$[2]").value("AC")) .andExpect(jsonPath("$[3]").value("AD")) diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/SignerCertificateIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/SignerCertificateIntegrationTest.java index 496f85ac..3c1021d8 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/SignerCertificateIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/SignerCertificateIntegrationTest.java @@ -80,14 +80,20 @@ class SignerCertificateIntegrationTest { void testSuccessfulUpload() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) @@ -97,7 +103,8 @@ void testSuccessfulUpload() throws Exception { // immediately parse the message to get the signature from the signed message String signature = new SignedCertificateMessageParser(payload).getSignature(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -114,10 +121,12 @@ void testSuccessfulUpload() throws Exception { Assertions.assertTrue(createdSignerInformationEntity.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, createdSignerInformationEntity.get().getCertificateType()); + Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, + createdSignerInformationEntity.get().getCertificateType()); Assertions.assertEquals(countryCode, createdSignerInformationEntity.get().getCountry()); Assertions.assertEquals(signature, createdSignerInformationEntity.get().getSignature()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), createdSignerInformationEntity.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), + createdSignerInformationEntity.get().getRawData()); } @Test @@ -125,21 +134,28 @@ void testUploadFailedConflict() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -165,22 +181,27 @@ void testUploadFailedInvalidCSCA() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); // sign with TrustAnchor X509Certificate cscaCertificate = dgcTestKeyStore.getTrustAnchor(); PrivateKey cscaPrivateKey = dgcTestKeyStore.getTrustAnchorPrivateKey(); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -198,8 +219,10 @@ void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); // sign with CSCA from another country X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, "XX"); @@ -207,14 +230,17 @@ void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -232,21 +258,28 @@ void testUploadFailedPayloadCertCountryWrong() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -264,21 +297,28 @@ void testUploadFailedWrongSignerCertificate() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -295,14 +335,20 @@ void testUploadFailedWrongSignerCertificate() throws Exception { void testUploadFailedInvalidCmsMessage() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); String payload = new SignedCertificateMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) @@ -312,7 +358,8 @@ void testUploadFailedInvalidCmsMessage() throws Exception { // randomly play a little bit inside the base64 string payload = payload.replace(payload.substring(10, 50), payload.substring(80, 120)); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payload) @@ -332,14 +379,20 @@ void testReupload() throws Exception { /* * Step 0: Prepare DSC */ - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); /* * Step 1: Upload DSC @@ -351,7 +404,8 @@ void testReupload() throws Exception { String signature = new SignedCertificateMessageParser(payloadString).getDetachedSignature(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .content(payloadString) @@ -368,9 +422,11 @@ void testReupload() throws Exception { Assertions.assertTrue(createdSignerInformationEntity.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, createdSignerInformationEntity.get().getCertificateType()); + Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, + createdSignerInformationEntity.get().getCertificateType()); Assertions.assertEquals(countryCode, createdSignerInformationEntity.get().getCountry()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), createdSignerInformationEntity.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), + createdSignerInformationEntity.get().getRawData()); Assertions.assertEquals(signature, createdSignerInformationEntity.get().getSignature()); /* @@ -390,9 +446,11 @@ void testReupload() throws Exception { Assertions.assertTrue(deletedSignerInformationEntity.isPresent()); - Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, deletedSignerInformationEntity.get().getCertificateType()); + Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, + deletedSignerInformationEntity.get().getCertificateType()); Assertions.assertEquals(countryCode, deletedSignerInformationEntity.get().getCountry()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), deletedSignerInformationEntity.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), + deletedSignerInformationEntity.get().getRawData()); Assertions.assertNull(deletedSignerInformationEntity.get().getSignature()); /* @@ -411,9 +469,11 @@ void testReupload() throws Exception { signerInformationRepository.getFirstByThumbprint(certificateUtils.getCertThumbprint(payloadCertificate)); Assertions.assertTrue(reCreatedSignerInformationEntity.isPresent()); - Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, reCreatedSignerInformationEntity.get().getCertificateType()); + Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, + reCreatedSignerInformationEntity.get().getCertificateType()); Assertions.assertEquals(countryCode, reCreatedSignerInformationEntity.get().getCountry()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), reCreatedSignerInformationEntity.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), + reCreatedSignerInformationEntity.get().getRawData()); Assertions.assertEquals(signature, reCreatedSignerInformationEntity.get().getSignature()); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListIntegrationTest.java index 2371b2c2..ab942ed3 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/TrustListIntegrationTest.java @@ -107,7 +107,8 @@ class TrustListIntegrationTest { private static final ZonedDateTime nowMinusOneHour = ZonedDateTime.now(gmt).minusHours(1); X509Certificate certUploadDe, certUploadEu, certCscaDe, certCscaEu, certAuthDe, certAuthEu, certDscDe, certDscEu, - certUploadDe2, certUploadEu2, certCscaDe2, certCscaEu2, certAuthDe2, certAuthEu2, certDscDe2, certDscEu2, certDscEuDeleted; + certUploadDe2, certUploadEu2, certCscaDe2, certCscaEu2, certAuthDe2, certAuthEu2, certDscDe2, certDscEu2, + certDscEuDeleted; @BeforeEach void testData() throws Exception { @@ -139,7 +140,8 @@ void testData() throws Exception { @Test void testTrustListDownloadNoFilterIsSince() throws Exception { prepareTestCertsCreatedAtNowMinusOneHour(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -182,7 +184,8 @@ void testTrustListDownloadNoFilterIsSince() throws Exception { @Test void testTrustListDownloadNoFilterPageable() throws Exception { prepareTestCertsCreatedAtNowMinusOneHour(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList?page=0&pagesize=100") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -213,7 +216,8 @@ void testTrustListDownloadNoFilterPageable() throws Exception { @Test void testTrustListDownloadNoFilterIsSincePageable() throws Exception { prepareTestCertsCreatedAtNowMinusOneHour(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList?page=0&pagesize=10") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -259,7 +263,8 @@ void testTrustListDownloadNoFilterIsSincePageable() throws Exception { @Test void testTrustListDownloadNoFilterByTypeAndCountryIsSincePageable() throws Exception { prepareTestCertsCreatedAtNowMinusOneHour(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/AUTHENTICATION") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -309,7 +314,8 @@ void testTrustListDownloadNoFilterByTypeAndCountryIsSincePageable() throws Excep @Test void testTrustListDownloadNoFilter() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -331,7 +337,8 @@ void testTrustListDownloadNoFilter() throws Exception { @Test void testTrustListDownloadFilterByType() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/AUTHENTICATION") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -380,7 +387,8 @@ void testTrustListDownloadFilterByType() throws Exception { @Test void testTrustListDownloadFilterByTypeCaseInsensitive() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/aUtHeNtiCaTiOn") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -429,7 +437,8 @@ void testTrustListDownloadFilterByTypeCaseInsensitive() throws Exception { @Test void testTrustListDownloadFilterByTypeAndCountry() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/AUTHENTICATION/DE") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -514,7 +523,8 @@ void testTrustListDownloadFilterByTypeAndCountry() throws Exception { @Test void testTrustListDownloadFilterByTypeAndCountryLowercase() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/AUTHENTICATION/de") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -599,7 +609,8 @@ void testTrustListDownloadFilterByTypeAndCountryLowercase() throws Exception { @Test void testTrustListDownloadEmptyList() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); signerInformationRepository.deleteAll(); @@ -615,7 +626,8 @@ void testTrustListDownloadEmptyList() throws Exception { @Test void testTrustedIssuerNoFilter() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/issuers") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) @@ -628,7 +640,8 @@ void testTrustedIssuerNoFilter() throws Exception { @Test void testTrustedIssuerByCountry() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/issuers?country=DE") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) @@ -641,7 +654,8 @@ void testTrustedIssuerByCountry() throws Exception { @Test void testTrustedIssuerByMultipleCountries() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/issuers?country=DE,EU") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) @@ -654,7 +668,8 @@ void testTrustedIssuerByMultipleCountries() throws Exception { @Test void testTrustedIssuerEmpty() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList/issuers?country=XX") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) @@ -672,7 +687,8 @@ void testTrustedIssuerEmpty() throws Exception { "/trustList/issuers?country=DE,XXX" }) void testBadRequests(String url) throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get(url) .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) @@ -684,7 +700,8 @@ void testBadRequests(String url) throws Exception { @Test void testTrustListDownloadPageableDefaultFallback() throws Exception { prepareTestCertsCreatedAtNowMinusOneHour(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/trustList?pagesize=5") .accept(MediaType.APPLICATION_JSON_VALUE) @@ -740,25 +757,43 @@ private void prepareTestCertsCreatedAtNowMinusOneHour() throws Exception { "EU", "EUTestDeleted"); signerInformationTestHelper.createSignerInformationInDB("DE", "sig3", certDscDe2, nowMinusOneHour); signerInformationTestHelper.createSignerInformationInDB("EU", "sig4", certDscEu2, nowMinusOneHour); - signerInformationTestHelper.createSignerInformationInDB("EU", "sig5_deleted", certDscEuDeleted, now.minusHours(2), nowMinusOneHour); - - certUploadDe2 = trustedPartyTestHelper.getTestCert("test1", TrustedPartyEntity.CertificateType.UPLOAD, "DE", nowMinusOneHour); - certCscaDe2 = trustedPartyTestHelper.getTestCert("test2", TrustedPartyEntity.CertificateType.CSCA, "DE", nowMinusOneHour); - certAuthDe2 = trustedPartyTestHelper.getTestCert("test3", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", nowMinusOneHour); - certUploadEu2 = trustedPartyTestHelper.getTestCert("test4", TrustedPartyEntity.CertificateType.UPLOAD, "EU", nowMinusOneHour); - certCscaEu2 = trustedPartyTestHelper.getTestCert("test5", TrustedPartyEntity.CertificateType.CSCA, "EU", nowMinusOneHour); - certAuthEu2 = trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", nowMinusOneHour); + signerInformationTestHelper.createSignerInformationInDB("EU", "sig5_deleted", certDscEuDeleted, + now.minusHours(2), nowMinusOneHour); + + certUploadDe2 = + trustedPartyTestHelper.getTestCert("test1", TrustedPartyEntity.CertificateType.UPLOAD, "DE", + nowMinusOneHour); + certCscaDe2 = + trustedPartyTestHelper.getTestCert("test2", TrustedPartyEntity.CertificateType.CSCA, "DE", + nowMinusOneHour); + certAuthDe2 = + trustedPartyTestHelper.getTestCert("test3", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", + nowMinusOneHour); + certUploadEu2 = + trustedPartyTestHelper.getTestCert("test4", TrustedPartyEntity.CertificateType.UPLOAD, "EU", + nowMinusOneHour); + certCscaEu2 = + trustedPartyTestHelper.getTestCert("test5", TrustedPartyEntity.CertificateType.CSCA, "EU", + nowMinusOneHour); + certAuthEu2 = + trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", + nowMinusOneHour); } - private void assertTrustListItem(MvcResult result, X509Certificate certificate, String country, CertificateTypeDto certificateTypeDto, String signature) throws UnsupportedEncodingException, CertificateEncodingException, JsonProcessingException { + private void assertTrustListItem(MvcResult result, X509Certificate certificate, String country, + CertificateTypeDto certificateTypeDto, String signature) + throws UnsupportedEncodingException, CertificateEncodingException, JsonProcessingException { assertTrustListItem(result, certificate, country, certificateTypeDto, signature, false); } - private void assertTrustListItem(MvcResult result, X509Certificate certificate, String country, CertificateTypeDto certificateTypeDto, String signature, boolean deleted) throws CertificateEncodingException, UnsupportedEncodingException, JsonProcessingException { + private void assertTrustListItem(MvcResult result, X509Certificate certificate, String country, + CertificateTypeDto certificateTypeDto, String signature, boolean deleted) + throws CertificateEncodingException, UnsupportedEncodingException, JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()); - List trustList = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { - }); + List trustList = + objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { + }); Optional trustListOptional = trustList .stream() @@ -776,18 +811,21 @@ private void assertTrustListItem(MvcResult result, X509Certificate certificate, if (deleted) { Assertions.assertNull(trustListItem.getRawData()); } else { - Assertions.assertEquals(Base64.getEncoder().encodeToString(certificate.getEncoded()), trustListItem.getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(certificate.getEncoded()), + trustListItem.getRawData()); } if (signature != null) { Assertions.assertEquals(signature, trustListItem.getSignature()); } } - private void assertTrustListLength(MvcResult result, int expectedLength) throws UnsupportedEncodingException, JsonProcessingException { + private void assertTrustListLength(MvcResult result, int expectedLength) + throws UnsupportedEncodingException, JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()); - List trustList = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { - }); + List trustList = + objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { + }); Assertions.assertEquals(expectedLength, trustList.size()); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleIntegrationTest.java index 49d3f2c6..10048b21 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValidationRuleIntegrationTest.java @@ -132,37 +132,43 @@ void testSuccessfulUpload() throws Exception { long validationRulesInDb = validationRuleRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); Assertions.assertEquals(validationRulesInDb + 1, validationRuleRepository.count()); Optional createdValidationRule = - validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); + validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); Assertions.assertTrue(createdValidationRule.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), createdValidationRule.get().getValidFrom().toEpochSecond()); - Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), createdValidationRule.get().getValidTo().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), + createdValidationRule.get().getValidFrom().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), + createdValidationRule.get().getValidTo().toEpochSecond()); Assertions.assertEquals(validationRule.getCountry(), createdValidationRule.get().getCountry()); - Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), createdValidationRule.get().getValidationRuleType().toString()); + Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), + createdValidationRule.get().getValidationRuleType().toString()); SignedStringMessageParser parser = new SignedStringMessageParser(createdValidationRule.get().getCms()); ValidationRule parsedValidationRule = objectMapper.readValue(parser.getPayload(), ValidationRule.class); @@ -175,8 +181,10 @@ void testSuccessfulUploadWithoutRegionProperty() throws Exception { long validationRulesInDb = validationRuleRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setRegion(null); @@ -184,31 +192,35 @@ void testSuccessfulUploadWithoutRegionProperty() throws Exception { json = json.replace("\"Region\":null,", ""); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(json) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(json) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); Assertions.assertEquals(validationRulesInDb + 1, validationRuleRepository.count()); Optional createdValidationRule = - validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); + validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); Assertions.assertTrue(createdValidationRule.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), createdValidationRule.get().getValidFrom().toEpochSecond()); - Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), createdValidationRule.get().getValidTo().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), + createdValidationRule.get().getValidFrom().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), + createdValidationRule.get().getValidTo().toEpochSecond()); Assertions.assertEquals(validationRule.getCountry(), createdValidationRule.get().getCountry()); - Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), createdValidationRule.get().getValidationRuleType().toString()); + Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), + createdValidationRule.get().getValidationRuleType().toString()); SignedStringMessageParser parser = new SignedStringMessageParser(createdValidationRule.get().getCms()); ValidationRule parsedValidationRule = objectMapper.readValue(parser.getPayload(), ValidationRule.class); @@ -220,25 +232,30 @@ void testSuccessfulUploadWithoutRegionProperty() throws Exception { void testInputOnlyContainsJson() throws Exception { long validationRulesInDb = validationRuleRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule) + "\n" + objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload( + objectMapper.writeValueAsString(validationRule) + "\n" + + objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") - .content(payload) - .contentType("application/cms") - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) - .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()); + .content(payload) + .contentType("application/cms") + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) + .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) + ) + .andExpect(status().isBadRequest()); payload = new SignedStringMessageBuilder() .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) @@ -260,9 +277,12 @@ void testInputOnlyContainsJson() throws Exception { @Test void testJsonSchemaValidation() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); Map invalidValidationRules = new HashMap<>(); @@ -323,7 +343,7 @@ void testJsonSchemaValidation() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x200")); } @@ -331,25 +351,28 @@ void testJsonSchemaValidation() throws Exception { @Test void testValidationCountry() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setIdentifier("GR-DE-0001"); validationRule.setCountry("DE"); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.code").value("0x210")); @@ -365,39 +388,42 @@ void testValidationCountry() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.code").value("0x210")); } @Test void testValidationVersion() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x220")); @@ -413,7 +439,7 @@ void testValidationVersion() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x220")); } @@ -423,45 +449,50 @@ void testValidationUploadCert() throws Exception { ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate( - certificateUtils.convertCertificate(trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, "EU")), - trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, "EU")) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate( + certificateUtils.convertCertificate( + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, "EU")), + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, "EU")) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code").value("0x230")); + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("0x230")); } @Test void testValidationTimestamps() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setValidFrom(ZonedDateTime.now().plus(1, ChronoUnit.DAYS)); validationRule.setValidTo(ZonedDateTime.now().minus(1, ChronoUnit.DAYS)); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x240")); @@ -477,7 +508,7 @@ void testValidationTimestamps() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); validationRule.setVersion("1.0.1"); @@ -493,7 +524,7 @@ void testValidationTimestamps() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x240")); @@ -509,16 +540,19 @@ void testValidationTimestamps() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x240")); } @Test void testValidationTimestamps2() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setIdentifier("IR-EU-0001"); @@ -526,16 +560,16 @@ void testValidationTimestamps2() throws Exception { validationRule.setValidFrom(ZonedDateTime.now().plus(2, ChronoUnit.SECONDS)); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); validationRule = getDummyValidationRule(); @@ -551,26 +585,29 @@ void testValidationTimestamps2() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x240")); } @Test void testValidationTimestamps3() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setValidFrom(ZonedDateTime.now().plus(3, ChronoUnit.DAYS)); validationRule.setValidTo(ZonedDateTime.now() - .plus(6, ChronoUnit.DAYS) - .minus(1, ChronoUnit.SECONDS)); + .plus(6, ChronoUnit.DAYS) + .minus(1, ChronoUnit.SECONDS)); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) .buildAsString(); mockMvc.perform(post("/rules") @@ -578,32 +615,35 @@ void testValidationTimestamps3() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x240")); } @Test void testValidationRuleId() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setIdentifier("GR-EU-0001"); validationRule.setType("Invalidation"); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); @@ -620,7 +660,7 @@ void testValidationRuleId() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); @@ -637,7 +677,7 @@ void testValidationRuleId() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); validationRule.setIdentifier("GR-EU-0001"); @@ -653,31 +693,34 @@ void testValidationRuleId() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); } @Test void testValidationRuleInvalidIdPrefix() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); ValidationRule validationRule = getDummyValidationRule(); validationRule.setIdentifier("TR-EU-0001"); validationRule.setCertificateType("Vaccination"); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); @@ -694,7 +737,7 @@ void testValidationRuleInvalidIdPrefix() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); @@ -711,7 +754,7 @@ void testValidationRuleInvalidIdPrefix() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); @@ -728,7 +771,7 @@ void testValidationRuleInvalidIdPrefix() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.code").value("0x250")); } @@ -737,25 +780,28 @@ void testValidationRuleInvalidIdPrefix() throws Exception { void testDelete() throws Exception { long validationRulesInDb = validationRuleRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); validationRule.setVersion("1.0.1"); @@ -769,7 +815,7 @@ void testDelete() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); Assertions.assertEquals(validationRulesInDb + 2, validationRuleRepository.count()); @@ -784,7 +830,7 @@ void testDelete() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isNoContent()); Assertions.assertEquals(validationRulesInDb, validationRuleRepository.count()); @@ -792,107 +838,122 @@ void testDelete() throws Exception { @Test void testDeleteFailNotFound() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString("IR-EU-0001")) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString("IR-EU-0001")) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(delete("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNotFound()); + ) + .andExpect(status().isNotFound()); } @Test void testDeleteFailInvalidUploadCertificate() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString("IR-EU-0001")) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString("IR-EU-0001")) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(delete("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code").value("0x230")); + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("0x230")); } @Test void testDeleteFailInvalidIdString() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString("XXXX-TESST-!!!!!")) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString("XXXX-TESST-!!!!!")) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(delete("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.code").value("0x250")); + ) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.code").value("0x250")); } @Test void testDeleteFailInvalidCountryCode() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString("IR-DE-0001")) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString("IR-DE-0001")) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(delete("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isForbidden()) - .andExpect(jsonPath("$.code").value("0x210")); + ) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.code").value("0x210")); } @Test void testDownloadReturnAll() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule1 = getDummyValidationRule(); validationRule1.setValidFrom(ZonedDateTime.now().minus(1, ChronoUnit.DAYS)); String payload1 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule1)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule1)) + .buildAsString(); ValidationRuleEntity vr1 = new ValidationRuleEntity(); vr1.setRuleId(validationRule1.getIdentifier()); - vr1.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); + vr1.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); vr1.setValidTo(validationRule1.getValidTo()); vr1.setValidFrom(validationRule1.getValidFrom()); vr1.setCountry(validationRule1.getCountry()); @@ -906,13 +967,14 @@ void testDownloadReturnAll() throws Exception { validationRule2.setVersion("1.0.1"); String payload2 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule2)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule2)) + .buildAsString(); ValidationRuleEntity vr2 = new ValidationRuleEntity(); vr2.setRuleId(validationRule2.getIdentifier()); - vr2.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); + vr2.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); vr2.setValidTo(validationRule2.getValidTo()); vr2.setValidFrom(validationRule2.getValidFrom()); vr2.setCountry(validationRule2.getCountry()); @@ -925,13 +987,14 @@ void testDownloadReturnAll() throws Exception { validationRule3.setIdentifier("GR-EU-0002"); String payload3 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule3)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule3)) + .buildAsString(); ValidationRuleEntity vr3 = new ValidationRuleEntity(); vr3.setRuleId(validationRule3.getIdentifier()); - vr3.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule3.getType().toUpperCase(Locale.ROOT))); + vr3.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule3.getType().toUpperCase(Locale.ROOT))); vr3.setValidTo(validationRule3.getValidTo()); vr3.setValidFrom(validationRule3.getValidFrom()); vr3.setCountry(validationRule3.getCountry()); @@ -941,17 +1004,18 @@ void testDownloadReturnAll() throws Exception { validationRuleRepository.save(vr3); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/rules/EU") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(2)) - .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr2.getVersion())) - .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr2.getCms())) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(2)) + .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr2.getVersion())) + .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr2.getCms())) .andExpect(jsonPath("$.['GR-EU-0001'][0].validTo").value(vr2.getValidTo().format(formatter))) .andExpect(jsonPath("$.['GR-EU-0001'][0].validFrom").value(vr2.getValidFrom().format(formatter))) .andExpect(jsonPath("$.['GR-EU-0001'][1].version").value(vr1.getVersion())) @@ -967,20 +1031,23 @@ void testDownloadReturnAll() throws Exception { @Test void testDownloadReturnOnlyValid() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule1 = getDummyValidationRule(); validationRule1.setValidFrom(ZonedDateTime.now().minus(4, ChronoUnit.DAYS)); String payload1 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule1)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule1)) + .buildAsString(); ValidationRuleEntity vr1 = new ValidationRuleEntity(); vr1.setRuleId(validationRule1.getIdentifier()); - vr1.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); + vr1.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); vr1.setValidTo(validationRule1.getValidTo()); vr1.setValidFrom(validationRule1.getValidFrom()); vr1.setCountry(validationRule1.getCountry()); @@ -994,13 +1061,14 @@ void testDownloadReturnOnlyValid() throws Exception { validationRule2.setVersion("1.0.1"); String payload2 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule2)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule2)) + .buildAsString(); ValidationRuleEntity vr2 = new ValidationRuleEntity(); vr2.setRuleId(validationRule2.getIdentifier()); - vr2.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); + vr2.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); vr2.setValidTo(validationRule2.getValidTo()); vr2.setValidFrom(validationRule2.getValidFrom()); vr2.setCountry(validationRule2.getCountry()); @@ -1009,37 +1077,41 @@ void testDownloadReturnOnlyValid() throws Exception { validationRuleRepository.save(vr2); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/rules/EU") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(1)) - .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr2.getVersion())) - .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr2.getCms())) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(1)) + .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr2.getVersion())) + .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr2.getCms())) .andExpect(jsonPath("$.['GR-EU-0001'][0].validTo").value(vr2.getValidTo().format(formatter))) .andExpect(jsonPath("$.['GR-EU-0001'][0].validFrom").value(vr2.getValidFrom().format(formatter))); } @Test void testDownloadDbContainsOnlyRulesValidInFutureShouldReturnAll() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule1 = getDummyValidationRule(); validationRule1.setValidFrom(ZonedDateTime.now().plus(1, ChronoUnit.DAYS)); String payload1 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule1)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule1)) + .buildAsString(); ValidationRuleEntity vr1 = new ValidationRuleEntity(); vr1.setRuleId(validationRule1.getIdentifier()); - vr1.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); + vr1.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule1.getType().toUpperCase(Locale.ROOT))); vr1.setValidTo(validationRule1.getValidTo()); vr1.setValidFrom(validationRule1.getValidFrom()); vr1.setCountry(validationRule1.getCountry()); @@ -1053,13 +1125,14 @@ void testDownloadDbContainsOnlyRulesValidInFutureShouldReturnAll() throws Except validationRule2.setVersion("1.0.1"); String payload2 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule2)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule2)) + .buildAsString(); ValidationRuleEntity vr2 = new ValidationRuleEntity(); vr2.setRuleId(validationRule2.getIdentifier()); - vr2.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); + vr2.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule2.getType().toUpperCase(Locale.ROOT))); vr2.setValidTo(validationRule2.getValidTo()); vr2.setValidFrom(validationRule2.getValidFrom()); vr2.setCountry(validationRule2.getCountry()); @@ -1073,13 +1146,14 @@ void testDownloadDbContainsOnlyRulesValidInFutureShouldReturnAll() throws Except validationRule3.setVersion("1.1.0"); String payload3 = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule3)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule3)) + .buildAsString(); ValidationRuleEntity vr3 = new ValidationRuleEntity(); vr3.setRuleId(validationRule3.getIdentifier()); - vr3.setValidationRuleType(ValidationRuleEntity.ValidationRuleType.valueOf(validationRule3.getType().toUpperCase(Locale.ROOT))); + vr3.setValidationRuleType( + ValidationRuleEntity.ValidationRuleType.valueOf(validationRule3.getType().toUpperCase(Locale.ROOT))); vr3.setValidTo(validationRule3.getValidTo()); vr3.setValidFrom(validationRule3.getValidFrom()); vr3.setCountry(validationRule3.getCountry()); @@ -1089,17 +1163,18 @@ void testDownloadDbContainsOnlyRulesValidInFutureShouldReturnAll() throws Except validationRuleRepository.save(vr3); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/rules/EU") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(3)) - .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr3.getVersion())) - .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr3.getCms())) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.['GR-EU-0001'].length()").value(3)) + .andExpect(jsonPath("$.['GR-EU-0001'][0].version").value(vr3.getVersion())) + .andExpect(jsonPath("$.['GR-EU-0001'][0].cms").value(vr3.getCms())) .andExpect(jsonPath("$.['GR-EU-0001'][0].validTo").value(vr3.getValidTo().format(formatter))) .andExpect(jsonPath("$.['GR-EU-0001'][0].validFrom").value(vr3.getValidFrom().format(formatter))) .andExpect(jsonPath("$.['GR-EU-0001'][1].version").value(vr2.getVersion())) @@ -1117,25 +1192,28 @@ void testDownloadDbContainsOnlyRulesValidInFutureShouldReturnAll() throws Except void testDeleteAliasEndpoint() throws Exception { long validationRulesInDb = validationRuleRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); validationRule.setVersion("1.0.1"); @@ -1149,7 +1227,7 @@ void testDeleteAliasEndpoint() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isCreated()); Assertions.assertEquals(validationRulesInDb + 2, validationRuleRepository.count()); @@ -1164,7 +1242,7 @@ void testDeleteAliasEndpoint() throws Exception { .contentType("application/cms") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isNoContent()); Assertions.assertEquals(validationRulesInDb, validationRuleRepository.count()); @@ -1175,37 +1253,43 @@ void testSuccessfulUploadWithOldContentType() throws Exception { long validationRulesInDb = validationRuleRepository.count(); long auditEventEntitiesInDb = auditEventRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - PrivateKey signerPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + PrivateKey signerPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); ValidationRule validationRule = getDummyValidationRule(); String payload = new SignedStringMessageBuilder() - .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) - .withPayload(objectMapper.writeValueAsString(validationRule)) - .buildAsString(); + .withSigningCertificate(certificateUtils.convertCertificate(signerCertificate), signerPrivateKey) + .withPayload(objectMapper.writeValueAsString(validationRule)) + .buildAsString(); - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/rules") .content(payload) .contentType("application/cms-text") .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isCreated()); + ) + .andExpect(status().isCreated()); Assertions.assertEquals(validationRulesInDb + 1, validationRuleRepository.count()); Optional createdValidationRule = - validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); + validationRuleRepository.getByRuleIdAndVersion(validationRule.getIdentifier(), validationRule.getVersion()); Assertions.assertTrue(createdValidationRule.isPresent()); Assertions.assertEquals(auditEventEntitiesInDb + 1, auditEventRepository.count()); - Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), createdValidationRule.get().getValidFrom().toEpochSecond()); - Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), createdValidationRule.get().getValidTo().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidFrom().toEpochSecond(), + createdValidationRule.get().getValidFrom().toEpochSecond()); + Assertions.assertEquals(validationRule.getValidTo().toEpochSecond(), + createdValidationRule.get().getValidTo().toEpochSecond()); Assertions.assertEquals(validationRule.getCountry(), createdValidationRule.get().getCountry()); - Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), createdValidationRule.get().getValidationRuleType().toString()); + Assertions.assertEquals(validationRule.getType().toUpperCase(Locale.ROOT), + createdValidationRule.get().getValidationRuleType().toString()); SignedStringMessageParser parser = new SignedStringMessageParser(createdValidationRule.get().getCms()); ValidationRule parsedValidationRule = objectMapper.readValue(parser.getPayload(), ValidationRule.class); diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetIntegrationTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetIntegrationTest.java index bab89016..58f6e7de 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetIntegrationTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/controller/ValuesetIntegrationTest.java @@ -76,39 +76,41 @@ void testData() { @Test void testGetValuesetIds() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/valuesets") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.length()").value(equalTo(3))) - .andExpect(jsonPath("$[0]").value(equalTo(valuesetEntity1.getId()))) + ) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.length()").value(equalTo(3))) + .andExpect(jsonPath("$[0]").value(equalTo(valuesetEntity1.getId()))) .andExpect(jsonPath("$[1]").value(equalTo(valuesetEntity2.getId()))) .andExpect(jsonPath("$[2]").value(equalTo(valuesetEntity3.getId()))); } @Test void testGetValueset() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/valuesets/" + valuesetEntity1.getId()) .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.key1").value(equalTo("content1"))); + ) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.key1").value(equalTo("content1"))); mockMvc.perform(get("/valuesets/" + valuesetEntity2.getId()) .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.key2").value(equalTo("content2"))); @@ -117,7 +119,7 @@ void testGetValueset() throws Exception { .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) + ) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.key3").value(equalTo("content3"))); @@ -125,13 +127,14 @@ void testGetValueset() throws Exception { @Test void testGetValuesetNotFound() throws Exception { - String authCertHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String authCertHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(get("/valuesets/randomId") .accept(MediaType.APPLICATION_JSON_VALUE) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getThumbprint(), authCertHash) .header(dgcConfigProperties.getCertAuth().getHeaderFields().getDistinguishedName(), authCertSubject) - ) - .andExpect(status().isNotFound()); + ) + .andExpect(status().isNotFound()); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/restapi/filter/CertAuthFilterTest.java b/src/test/java/eu/europa/ec/dgc/gateway/restapi/filter/CertAuthFilterTest.java index 83ac521c..c3491cf6 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/restapi/filter/CertAuthFilterTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/restapi/filter/CertAuthFilterTest.java @@ -55,7 +55,8 @@ class CertAuthFilterTest { @Test void testRequestShouldFailIfDNHeaderIsMissing() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") @@ -89,14 +90,16 @@ void testRequestShouldFailIfCertIsNotOnWhitelist() throws Exception { @Test void testFilterShouldAppendCountryAndThumbprintToRequestObject() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), certHash) .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), authDn) ).andExpect(mvcResult -> { - Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); + Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); Assertions.assertEquals( certHash, mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) @@ -106,16 +109,19 @@ void testFilterShouldAppendCountryAndThumbprintToRequestObject() throws Exceptio @Test void testFilterShouldDecodeDnString() throws Exception { - String encodedDnString = "ST%3dSome-State%2c%20C%3dEU%2c%20O%3dInternet%20Widgits%20Pty%20Ltd%2c%20CN%3dTest%20Cert"; + String encodedDnString = + "ST%3dSome-State%2c%20C%3dEU%2c%20O%3dInternet%20Widgits%20Pty%20Ltd%2c%20CN%3dTest%20Cert"; - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), certHash) .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), encodedDnString) ).andExpect(mvcResult -> { - Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); + Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); Assertions.assertEquals( certHash, mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) @@ -125,7 +131,8 @@ void testFilterShouldDecodeDnString() throws Exception { @Test void testFilterShouldDecodeBase64AndUrlEncodedCertThumbprint() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); byte[] certHashBytes = new BigInteger(certHash, 16).toByteArray(); if (certHashBytes[0] == 0) { @@ -140,9 +147,11 @@ void testFilterShouldDecodeBase64AndUrlEncodedCertThumbprint() throws Exception mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), encodedThumbprint) - .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), "O=Test Firma GmbH,C=EU,U=,TR,TT=43") + .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), + "O=Test Firma GmbH,C=EU,U=,TR,TT=43") ).andExpect(mvcResult -> { - Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); + Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); Assertions.assertEquals( certHash, mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) @@ -152,7 +161,8 @@ void testFilterShouldDecodeBase64AndUrlEncodedCertThumbprint() throws Exception @Test void testFilterShouldDecodeBase64EncodedCertThumbprint() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); byte[] certHashBytes = new BigInteger(certHash, 16).toByteArray(); if (certHashBytes[0] == 0) { @@ -166,9 +176,11 @@ void testFilterShouldDecodeBase64EncodedCertThumbprint() throws Exception { mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), encodedThumbprint) - .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), "O=Test Firma GmbH,C=EU,U=,TR,TT=43") + .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), + "O=Test Firma GmbH,C=EU,U=,TR,TT=43") ).andExpect(mvcResult -> { - Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); + Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY)); Assertions.assertEquals( certHash, mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_THUMBPRINT) @@ -179,35 +191,43 @@ void testFilterShouldDecodeBase64EncodedCertThumbprint() throws Exception { @Test void testRequestShouldFailIfCountryIsNotPresentInDnString() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), certHash) - .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), "O=Test Firma GmbH,U=Abteilung XYZ,TR=test") + .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), + "O=Test Firma GmbH,U=Abteilung XYZ,TR=test") ).andExpect(status().isBadRequest()); } @Test void testFilterShouldFindCountryEvenOnMalformedDnString() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), certHash) - .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), "O=Test Firma GmbH,C=EU,U=,TR,TT=43") - ).andExpect(mvcResult -> Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY))); + .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), + "O=Test Firma GmbH,C=EU,U=,TR,TT=43") + ).andExpect(mvcResult -> Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY))); } @Test void testRequestShouldNotFailIfDnStringContainsDuplicatedKeys() throws Exception { - String certHash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); + String certHash = + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); mockMvc.perform(post("/signerCertificate/") .contentType("application/cms") .header(properties.getCertAuth().getHeaderFields().getThumbprint(), certHash) - .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), "O=Test Firma GmbH,O=XXX,C=EU,U=Abteilung XYZ,TR=test") - ).andExpect(mvcResult -> Assertions.assertEquals("EU", mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY))); + .header(properties.getCertAuth().getHeaderFields().getDistinguishedName(), + "O=Test Firma GmbH,O=XXX,C=EU,U=Abteilung XYZ,TR=test") + ).andExpect(mvcResult -> Assertions.assertEquals("EU", + mvcResult.getRequest().getAttribute(CertificateAuthenticationFilter.REQUEST_PROP_COUNTRY))); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/AuditServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/AuditServiceTest.java index 16e48f55..9b5cc580 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/AuditServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/AuditServiceTest.java @@ -86,7 +86,8 @@ void testSuccessfulCreateAuditEventWithCertificate() throws Exception { Assertions.assertEquals(countryCode, auditEvent.getCountry()); Assertions.assertEquals(dummySignature, auditEvent.getAuthenticationSha256Fingerprint()); - Assertions.assertEquals(trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.UPLOAD, countryCode), auditEvent.getUploaderSha256Fingerprint()); + Assertions.assertEquals(trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.UPLOAD, countryCode), + auditEvent.getUploaderSha256Fingerprint()); Assertions.assertEquals(exampleEvent, auditEvent.getEvent()); Assertions.assertEquals(exampleEventDescription, auditEvent.getDescription()); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/RatValuesetUpdateServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/RatValuesetUpdateServiceTest.java index bcd44952..5147fedd 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/RatValuesetUpdateServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/RatValuesetUpdateServiceTest.java @@ -156,8 +156,10 @@ void testRatValuesetUpdateActiveFalse() throws JsonProcessingException { Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not updated."); Assertions.assertEquals(2, updatedValueset.getValue().size(), "Valueset List size has been changed"); Assertions.assertFalse(updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); - Assertions.assertEquals(history2.getListDate().toEpochSecond(), updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(history2.getListDate().toEpochSecond(), + updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); } @Test @@ -198,8 +200,10 @@ void testRatValuesetUpdateActiveTrue() throws JsonProcessingException { Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not updated."); Assertions.assertEquals(2, updatedValueset.getValue().size(), "Valueset List size has been changed"); Assertions.assertTrue(updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); - Assertions.assertEquals(history2.getListDate().toEpochSecond(), updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(history2.getListDate().toEpochSecond(), + updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); } @Test @@ -242,8 +246,10 @@ void testRatValuesetInsertedIfNotExist() throws JsonProcessingException { Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not updated."); Assertions.assertEquals(1, updatedValueset.getValue().size(), "Valueset List size has been changed"); Assertions.assertTrue(updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); - Assertions.assertEquals(history2.getListDate().toEpochSecond(), updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(history2.getListDate().toEpochSecond(), + updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); } @Test @@ -287,8 +293,10 @@ void testRatValuesetUpdatedIfJsonInDbIsInvalid() throws JsonProcessingException Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not set."); Assertions.assertEquals(1, updatedValueset.getValue().size()); Assertions.assertTrue(updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); - Assertions.assertEquals(history2.getListDate().toEpochSecond(), updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(history2.getListDate().toEpochSecond(), + updatedValueset.getValue().get(RAT1_ID).getVersion().toEpochSecond()); } @Test @@ -364,7 +372,8 @@ void testRatValuesetUpdateShouldNotUpdateWhenRequestFails() throws JsonProcessin String updatedValuesetJson = valuesetService.getValueSetById(RAT_VALUESET_ID).orElseThrow(); Valueset updatedValueset = objectMapper.readValue(updatedValuesetJson, typeReference); - Assertions.assertEquals(LocalDate.now().minus(1, ChronoUnit.DAYS), updatedValueset.getDate(), "Valueset Date has been updated."); + Assertions.assertEquals(LocalDate.now().minus(1, ChronoUnit.DAYS), updatedValueset.getDate(), + "Valueset Date has been updated."); Assertions.assertEquals(2, updatedValueset.getValue().size(), "Valueset List size has been changed"); assertEquals(rat1, updatedValueset.getValue().get(RAT1_ID)); assertEquals(rat2, updatedValueset.getValue().get(RAT2_ID)); @@ -408,7 +417,8 @@ void testRatValuesetUpdateLatestAllHistoryEntriesAreInFuture() throws JsonProces Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not updated."); Assertions.assertEquals(2, updatedValueset.getValue().size(), "Valueset List size has been changed"); Assertions.assertNull(updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); Assertions.assertNull(updatedValueset.getValue().get(RAT1_ID).getVersion()); assertEquals(history1.getListDate(), updatedValueset.getValue().get(RAT1_ID).getValidUntil()); } @@ -456,7 +466,8 @@ void testRatValuesetUpdateLatestHistoryEntryNotInFuture() throws JsonProcessingE Assertions.assertEquals(LocalDate.now(), updatedValueset.getDate(), "Valueset Date was not updated."); Assertions.assertEquals(2, updatedValueset.getValue().size(), "Valueset List size has been changed"); Assertions.assertEquals(history2.getInCommonList(), updatedValueset.getValue().get(RAT1_ID).getActive()); - Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), updatedValueset.getValue().get(RAT1_ID).getDisplay()); + Assertions.assertEquals(String.format("%s, %s", manufacturer.getName(), jrcValueset.getCommercialName()), + updatedValueset.getValue().get(RAT1_ID).getDisplay()); assertEquals(history2.getListDate(), updatedValueset.getValue().get(RAT1_ID).getVersion()); assertEquals(history3.getListDate(), updatedValueset.getValue().get(RAT1_ID).getValidUntil()); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpServiceTest.java index 95d37fc6..5ab105ed 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationCleanUpServiceTest.java @@ -24,6 +24,11 @@ import eu.europa.ec.dgc.gateway.repository.SignerInformationRepository; import eu.europa.ec.dgc.gateway.testdata.CertificateTestUtils; import eu.europa.ec.dgc.utils.CertificateUtils; +import java.security.KeyPairGenerator; +import java.security.cert.X509Certificate; +import java.time.ZonedDateTime; +import java.util.Base64; +import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -31,12 +36,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.security.KeyPairGenerator; -import java.security.cert.X509Certificate; -import java.time.ZonedDateTime; -import java.util.Base64; -import java.util.List; - @SpringBootTest(properties = "dgc.signer-information.delete-threshold=14") @Slf4j class SignerInformationCleanUpServiceTest { @@ -61,22 +60,28 @@ public void setup() { void testCleanup() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ec"); - X509Certificate x509Certificate1 = CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest1"); - X509Certificate x509Certificate2 = CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest2"); - X509Certificate x509Certificate3 = CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest3"); + X509Certificate x509Certificate1 = + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest1"); + X509Certificate x509Certificate2 = + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest2"); + X509Certificate x509Certificate3 = + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "DE", "DETest3"); SignerInformationEntity deleted3DaysAgo = createSignerInformationInDB("DE", null, - certificateUtils.getCertThumbprint(x509Certificate2), Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), - ZonedDateTime.now().minusDays(30), ZonedDateTime.now().minusDays(3)); + certificateUtils.getCertThumbprint(x509Certificate2), + Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), + ZonedDateTime.now().minusDays(30), ZonedDateTime.now().minusDays(3)); SignerInformationEntity deleted3WeeksAgo = createSignerInformationInDB("DE", null, - certificateUtils.getCertThumbprint(x509Certificate3), Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), - ZonedDateTime.now().minusDays(40), ZonedDateTime.now().minusDays(21)); + certificateUtils.getCertThumbprint(x509Certificate3), + Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), + ZonedDateTime.now().minusDays(40), ZonedDateTime.now().minusDays(21)); SignerInformationEntity notDeleted = createSignerInformationInDB("DE", "sig3", - certificateUtils.getCertThumbprint(x509Certificate1), Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), - ZonedDateTime.now().minusDays(40), null); + certificateUtils.getCertThumbprint(x509Certificate1), + Base64.getEncoder().encodeToString(x509Certificate1.getEncoded()), + ZonedDateTime.now().minusDays(40), null); underTest.cleanup(); @@ -88,18 +93,19 @@ void testCleanup() throws Exception { } - private SignerInformationEntity createSignerInformationInDB(String countryCode, String signature, - String thumbprint, String encoded, ZonedDateTime createdAt, ZonedDateTime deletedAt) throws Exception { + String thumbprint, String encoded, + ZonedDateTime createdAt, ZonedDateTime deletedAt) + throws Exception { return signerInformationRepository.save(new SignerInformationEntity( - null, - createdAt, - deletedAt, - countryCode, - thumbprint, - encoded, - signature, - SignerInformationEntity.CertificateType.DSC + null, + createdAt, + deletedAt, + countryCode, + thumbprint, + encoded, + signature, + SignerInformationEntity.CertificateType.DSC )); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationServiceTest.java index fd13bf52..abc4d9b7 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/SignerInformationServiceTest.java @@ -93,13 +93,15 @@ void testSuccessfulGetSignerInformationIsSincePageable() throws Exception { signerInformationService.getSignerInformation(null, null, null); // No deleted entries if modified-since is not set Assertions.assertEquals(6, signerInformationEntities.size()); - Assertions.assertFalse(signerInformationEntities.stream().anyMatch(it -> it.getDeletedAt() != null && it.getSignature() == null)); + Assertions.assertFalse( + signerInformationEntities.stream().anyMatch(it -> it.getDeletedAt() != null && it.getSignature() == null)); List signerInformationEntities7 = - signerInformationService.getSignerInformation(nowMinusOneHour, null, null); + signerInformationService.getSignerInformation(nowMinusOneHour, null, null); // Include deleted entries if modified-since is set Assertions.assertEquals(7, signerInformationEntities7.size()); - Assertions.assertTrue(signerInformationEntities7.stream().anyMatch(it -> it.getDeletedAt() != null && it.getSignature() == null)); + Assertions.assertTrue( + signerInformationEntities7.stream().anyMatch(it -> it.getDeletedAt() != null && it.getSignature() == null)); List signerInformationEntities2 = signerInformationService.getSignerInformation( @@ -203,8 +205,8 @@ private void prepareTestSignerInformation() throws Exception { CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), "EU", "EUTest2"), now); signerInformationTestHelper.createSignerInformationInDB("EU", "sig7_deleted", - CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), - "EU", "EUTest3"), now.minusHours(2), nowMinusOneHour); + CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), + "EU", "EUTest3"), now.minusHours(2), nowMinusOneHour); } @@ -212,13 +214,18 @@ private void prepareTestSignerInformation() throws Exception { void testSuccessfulAddingNewSignerInformationAndDelete() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); signerInformationService.addSignerCertificate( new X509CertificateHolder(payloadCertificate.getEncoded()), @@ -233,10 +240,12 @@ void testSuccessfulAddingNewSignerInformationAndDelete() throws Exception { Assertions.assertTrue(createdSignerInformationEntity.isPresent()); - Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, createdSignerInformationEntity.get().getCertificateType()); + Assertions.assertEquals(SignerInformationEntity.CertificateType.DSC, + createdSignerInformationEntity.get().getCertificateType()); Assertions.assertEquals(countryCode, createdSignerInformationEntity.get().getCountry()); Assertions.assertEquals(dummySignature, createdSignerInformationEntity.get().getSignature()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), createdSignerInformationEntity.get().getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(payloadCertificate.getEncoded()), + createdSignerInformationEntity.get().getRawData()); signerInformationService.deleteSignerCertificate( new X509CertificateHolder(payloadCertificate.getEncoded()), @@ -246,19 +255,22 @@ void testSuccessfulAddingNewSignerInformationAndDelete() throws Exception { // Deleted certificate should not be returned in queries without isSince List entitiesByCertificateType = - signerInformationRepository.getByCertificateTypeAndDeletedAtIsNull(SignerInformationEntity.CertificateType.DSC); + signerInformationRepository.getByCertificateTypeAndDeletedAtIsNull( + SignerInformationEntity.CertificateType.DSC); Assertions.assertTrue(entitiesByCertificateType.isEmpty()); List entitiesByCertificateTypeAndCountry = - signerInformationRepository.getByCertificateTypeAndCountryAndDeletedAtIsNull( - SignerInformationEntity.CertificateType.DSC, countryCode); + signerInformationRepository.getByCertificateTypeAndCountryAndDeletedAtIsNull( + SignerInformationEntity.CertificateType.DSC, countryCode); Assertions.assertTrue(entitiesByCertificateTypeAndCountry.isEmpty()); List entities = signerInformationRepository.findAll(); Assertions.assertFalse(entities.isEmpty()); SignerInformationEntity deletedSignerInformationEntity = entities.get(0); - Assertions.assertEquals(createdSignerInformationEntity.get().getThumbprint(), deletedSignerInformationEntity.getThumbprint()); + Assertions.assertEquals(createdSignerInformationEntity.get().getThumbprint(), + deletedSignerInformationEntity.getThumbprint()); Assertions.assertNull(deletedSignerInformationEntity.getSignature()); - Assertions.assertEquals(createdSignerInformationEntity.get().getRawData(), deletedSignerInformationEntity.getRawData()); + Assertions.assertEquals(createdSignerInformationEntity.get().getRawData(), + deletedSignerInformationEntity.getRawData()); Assertions.assertEquals(signerInformationEntitiesInDb + 1, signerInformationRepository.count()); } @@ -266,13 +278,18 @@ void testSuccessfulAddingNewSignerInformationAndDelete() throws Exception { void testAddingFailedConflict() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); signerInformationService.addSignerCertificate( new X509CertificateHolder(payloadCertificate.getEncoded()), @@ -289,7 +306,8 @@ void testAddingFailedConflict() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.ALREADY_EXIST_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.ALREADY_EXIST_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb + 1, signerInformationRepository.count()); @@ -299,13 +317,18 @@ void testAddingFailedConflict() throws Exception { void testAddingFailedKidConflict() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); signerInformationService.addSignerCertificate( new X509CertificateHolder(payloadCertificate.getEncoded()), @@ -314,12 +337,14 @@ void testAddingFailedKidConflict() throws Exception { countryCode ); - Optional certInDbOptional = signerInformationRepository.getFirstByThumbprint(certificateUtils.getCertThumbprint(payloadCertificate)); + Optional certInDbOptional = + signerInformationRepository.getFirstByThumbprint(certificateUtils.getCertThumbprint(payloadCertificate)); Assertions.assertTrue(certInDbOptional.isPresent()); SignerInformationEntity certInDb = certInDbOptional.get(); - certInDb.setThumbprint(certInDb.getThumbprint().substring(0, 40) + "x".repeat(24)); // Generate new Hash with first 40 chars from ogirinal hash and add 24 x + certInDb.setThumbprint(certInDb.getThumbprint().substring(0, 40) + + "x".repeat(24)); // Generate new Hash with first 40 chars from ogirinal hash and add 24 x signerInformationRepository.save(certInDb); @@ -331,7 +356,8 @@ void testAddingFailedKidConflict() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.KID_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.KID_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb + 1, signerInformationRepository.count()); @@ -341,14 +367,17 @@ void testAddingFailedKidConflict() throws Exception { void testUploadFailedInvalidCSCA() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); // sign with TrustAnchor X509Certificate cscaCertificate = dgcTestKeyStore.getTrustAnchor(); PrivateKey cscaPrivateKey = dgcTestKeyStore.getTrustAnchorPrivateKey(); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.addSignerCertificate( @@ -358,7 +387,8 @@ void testUploadFailedInvalidCSCA() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.CSCA_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.CSCA_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); @@ -368,7 +398,8 @@ void testUploadFailedInvalidCSCA() throws Exception { void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); // sign with CSCA from another country X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, "XX"); @@ -376,7 +407,9 @@ void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.addSignerCertificate( @@ -386,7 +419,8 @@ void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.CSCA_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.CSCA_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); @@ -396,13 +430,18 @@ void testUploadFailedInvalidCSCAWrongCountryCode() throws Exception { void testUploadFailedPayloadCertCountryWrong() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.addSignerCertificate( @@ -412,7 +451,8 @@ void testUploadFailedPayloadCertCountryWrong() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.COUNTRY_OF_ORIGIN_CHECK_FAILED, e.getReason()); + Assertions.assertEquals( + SignerInformationService.SignerCertCheckException.Reason.COUNTRY_OF_ORIGIN_CHECK_FAILED, e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); @@ -422,13 +462,18 @@ void testUploadFailedPayloadCertCountryWrong() throws Exception { void testUploadFailedWrongSignerCertificate() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.addSignerCertificate( @@ -438,7 +483,8 @@ void testUploadFailedWrongSignerCertificate() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.UPLOADER_CERT_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.UPLOADER_CERT_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); @@ -446,12 +492,17 @@ void testUploadFailedWrongSignerCertificate() throws Exception { @Test void testDeleteFailedNotExists() throws Exception { - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.deleteSignerCertificate( @@ -460,7 +511,8 @@ void testDeleteFailedNotExists() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.EXIST_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.EXIST_CHECK_FAILED, + e.getReason()); } } @@ -468,12 +520,17 @@ void testDeleteFailedNotExists() throws Exception { void testDeleteFailedPayloadCertCountryWrong() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, "XX", "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.deleteSignerCertificate( @@ -482,7 +539,8 @@ void testDeleteFailedPayloadCertCountryWrong() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.COUNTRY_OF_ORIGIN_CHECK_FAILED, e.getReason()); + Assertions.assertEquals( + SignerInformationService.SignerCertCheckException.Reason.COUNTRY_OF_ORIGIN_CHECK_FAILED, e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); @@ -492,13 +550,18 @@ void testDeleteFailedPayloadCertCountryWrong() throws Exception { void testDeleteFailedWrongSignerCertificate() throws Exception { long signerInformationEntitiesInDb = signerInformationRepository.count(); - X509Certificate signerCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); + X509Certificate signerCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX"); - X509Certificate cscaCertificate = trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); - PrivateKey cscaPrivateKey = trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); + X509Certificate cscaCertificate = + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode); + PrivateKey cscaPrivateKey = + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.CSCA, countryCode); KeyPair payloadKeyPair = KeyPairGenerator.getInstance("ec").generateKeyPair(); - X509Certificate payloadCertificate = CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, cscaPrivateKey); + X509Certificate payloadCertificate = + CertificateTestUtils.generateCertificate(payloadKeyPair, countryCode, "Payload Cert", cscaCertificate, + cscaPrivateKey); try { signerInformationService.deleteSignerCertificate( @@ -507,7 +570,8 @@ void testDeleteFailedWrongSignerCertificate() throws Exception { countryCode ); } catch (SignerInformationService.SignerCertCheckException e) { - Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.UPLOADER_CERT_CHECK_FAILED, e.getReason()); + Assertions.assertEquals(SignerInformationService.SignerCertCheckException.Reason.UPLOADER_CERT_CHECK_FAILED, + e.getReason()); } Assertions.assertEquals(signerInformationEntitiesInDb, signerInformationRepository.count()); diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustListServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustListServiceTest.java index efef5f1c..eac1512e 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustListServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustListServiceTest.java @@ -186,21 +186,25 @@ private void prepareTestCertsCreatedAtNowMinusOneHour() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ec"); signerInformationTestHelper.createSignerInformationInDB("DE", "sig3", CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), - "DE", "DETest"), nowMinusOneHour); + "DE", "DETest"), nowMinusOneHour); signerInformationTestHelper.createSignerInformationInDB("EU", "sig4", CertificateTestUtils.generateCertificate(keyPairGenerator.generateKeyPair(), - "EU", "EUTest"), nowMinusOneHour); + "EU", "EUTest"), nowMinusOneHour); trustedPartyTestHelper.getTestCert("test1", TrustedPartyEntity.CertificateType.UPLOAD, "DE", nowMinusOneHour); trustedPartyTestHelper.getTestCert("test2", TrustedPartyEntity.CertificateType.CSCA, "DE", nowMinusOneHour); - trustedPartyTestHelper.getTestCert("test3", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", nowMinusOneHour); + trustedPartyTestHelper.getTestCert("test3", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", + nowMinusOneHour); trustedPartyTestHelper.getTestCert("test4", TrustedPartyEntity.CertificateType.UPLOAD, "EU", nowMinusOneHour); trustedPartyTestHelper.getTestCert("test5", TrustedPartyEntity.CertificateType.CSCA, "EU", nowMinusOneHour); - trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", nowMinusOneHour); + trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", + nowMinusOneHour); } - private void assertTrustListItem(List trustList, X509Certificate certificate, String country, TrustListType trustListType, String signature) throws CertificateEncodingException { + private void assertTrustListItem(List trustList, X509Certificate certificate, String country, + TrustListType trustListType, String signature) + throws CertificateEncodingException { Optional trustListOptional = trustList .stream() .filter(tl -> tl.getKid().equals(certificateUtils.getCertKid(certificate))) @@ -214,7 +218,8 @@ private void assertTrustListItem(List trustList, X509Certificate cert Assertions.assertEquals(country, trustListItem.getCountry()); Assertions.assertEquals(trustListType, trustListItem.getCertificateType()); Assertions.assertEquals(certificateUtils.getCertThumbprint(certificate), trustListItem.getThumbprint()); - Assertions.assertEquals(Base64.getEncoder().encodeToString(certificate.getEncoded()), trustListItem.getRawData()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(certificate.getEncoded()), + trustListItem.getRawData()); if (signature != null) { Assertions.assertEquals(signature, trustListItem.getSignature()); diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerServiceTest.java index b24b7113..b187575c 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedIssuerServiceTest.java @@ -21,20 +21,19 @@ package eu.europa.ec.dgc.gateway.service; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; + import eu.europa.ec.dgc.gateway.entity.TrustedIssuerEntity; import eu.europa.ec.dgc.gateway.repository.TrustedIssuerRepository; import eu.europa.ec.dgc.gateway.testdata.TrustedIssuerTestHelper; import eu.europa.ec.dgc.gateway.testdata.TrustedPartyTestHelper; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; - @SpringBootTest class TrustedIssuerServiceTest { @@ -55,9 +54,9 @@ void testData() throws Exception { trustedIssuerRepository.deleteAll(); trustedIssuerRepository.saveAll(List.of( - trustedIssuerTestHelper.createTrustedIssuer("EU"), - trustedIssuerTestHelper.createTrustedIssuer("DE"), - trustedIssuerTestHelper.createTrustedIssuer("AT") + trustedIssuerTestHelper.createTrustedIssuer("EU"), + trustedIssuerTestHelper.createTrustedIssuer("DE"), + trustedIssuerTestHelper.createTrustedIssuer("AT") )); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedPartyServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedPartyServiceTest.java index c6a6522a..0b17d639 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedPartyServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/TrustedPartyServiceTest.java @@ -71,8 +71,8 @@ void testSuccessfulGetTrustedPartyListIsSincePageable() throws Exception { Assertions.assertEquals(TEST_CERTIFICATE_LIST_SIZE, trustedPartyEntities.size()); List trustedPartyEntities3 = - trustedPartyService.getCertificates( nowMinusOneMinute, null, null); - Assertions.assertEquals(TEST_CERTIFICATE_LIST_SIZE /2, trustedPartyEntities3.size()); + trustedPartyService.getCertificates(nowMinusOneMinute, null, null); + Assertions.assertEquals(TEST_CERTIFICATE_LIST_SIZE / 2, trustedPartyEntities3.size()); List trustedPartyEntities4 = trustedPartyService.getCertificates(null, 0, 10); @@ -91,11 +91,11 @@ void testSuccessfulGetTrustedPartyListIsSincePageable() throws Exception { Assertions.assertEquals(0, trustedPartyEntities7.size()); List trustedPartyEntities8 = - trustedPartyService.getCertificates( nowMinusOneMinute, 0, 10); - Assertions.assertEquals(TEST_CERTIFICATE_LIST_SIZE /2, trustedPartyEntities8.size()); + trustedPartyService.getCertificates(nowMinusOneMinute, 0, 10); + Assertions.assertEquals(TEST_CERTIFICATE_LIST_SIZE / 2, trustedPartyEntities8.size()); List trustedPartyEntities9 = - trustedPartyService.getCertificates( nowMinusOneMinute, 1, 10); + trustedPartyService.getCertificates(nowMinusOneMinute, 1, 10); Assertions.assertEquals(0, trustedPartyEntities9.size()); } @@ -142,7 +142,7 @@ void testSuccessfulGetTrustedPartyListByTypeAndCountryIsSincePageable() throws E void testFailedGetTrustedPartyListIsSincePageable() { Assertions.assertThrows(IllegalArgumentException.class, () -> trustedPartyService.getCertificates(countryCode, TrustedPartyEntity.CertificateType.CSCA, - null,-1,2)); + null, -1, 2)); Assertions.assertThrows(IllegalArgumentException.class, () -> trustedPartyService.getCertificates(null, 0, 0)); @@ -154,7 +154,8 @@ void testFailedGetTrustedPartyListIsSincePageable() { @Test void trustedPartyServiceShouldReturnCertificate() throws Exception { String hash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.UPLOAD, countryCode); - Optional certOptional = trustedPartyService.getCertificate(hash, countryCode, TrustedPartyEntity.CertificateType.UPLOAD); + Optional certOptional = + trustedPartyService.getCertificate(hash, countryCode, TrustedPartyEntity.CertificateType.UPLOAD); Assertions.assertTrue(certOptional.isPresent()); Assertions.assertEquals(hash, certOptional.get().getThumbprint()); @@ -164,7 +165,8 @@ void trustedPartyServiceShouldReturnCertificate() throws Exception { Assertions.assertEquals(hash, certOptional.get().getThumbprint()); hash = trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode); - certOptional = trustedPartyService.getCertificate(hash, countryCode, TrustedPartyEntity.CertificateType.AUTHENTICATION); + certOptional = + trustedPartyService.getCertificate(hash, countryCode, TrustedPartyEntity.CertificateType.AUTHENTICATION); Assertions.assertTrue(certOptional.isPresent()); Assertions.assertEquals(hash, certOptional.get().getThumbprint()); } @@ -172,10 +174,12 @@ void trustedPartyServiceShouldReturnCertificate() throws Exception { @Test void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfRawDataIsViolated() throws Exception { Optional certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Optional anotherCertOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, TrustedPartyEntity.CertificateType.AUTHENTICATION); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, + TrustedPartyEntity.CertificateType.AUTHENTICATION); Assertions.assertTrue(certOptional.isPresent()); Assertions.assertTrue(anotherCertOptional.isPresent()); @@ -186,17 +190,20 @@ void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfRawDataIsViolated trustedPartyRepository.save(cert); certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Assertions.assertTrue(certOptional.isEmpty()); } @Test void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfSignatureIsViolated() throws Exception { Optional certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Optional anotherCertOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, TrustedPartyEntity.CertificateType.AUTHENTICATION); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, + TrustedPartyEntity.CertificateType.AUTHENTICATION); Assertions.assertTrue(certOptional.isPresent()); Assertions.assertTrue(anotherCertOptional.isPresent()); @@ -207,17 +214,20 @@ void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfSignatureIsViolat trustedPartyRepository.save(cert); certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Assertions.assertTrue(certOptional.isEmpty()); } @Test void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfThumbprintIsViolated() throws Exception { Optional certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Optional anotherCertOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, TrustedPartyEntity.CertificateType.AUTHENTICATION); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.AUTHENTICATION, countryCode), countryCode, + TrustedPartyEntity.CertificateType.AUTHENTICATION); Assertions.assertTrue(certOptional.isPresent()); Assertions.assertTrue(anotherCertOptional.isPresent()); @@ -237,12 +247,16 @@ void trustedPartyServiceShouldNotReturnCertificateIfIntegrityOfThumbprintIsViola @Test void trustedPartyServiceShouldNotReturnCertificateIfSignatureIsFromUnknownTrustAnchor() throws Exception { Optional certOptional = trustedPartyService.getCertificate( - trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, TrustedPartyEntity.CertificateType.CSCA); + trustedPartyTestHelper.getHash(TrustedPartyEntity.CertificateType.CSCA, countryCode), countryCode, + TrustedPartyEntity.CertificateType.CSCA); // Create new signature with a random non TrustAnchor certificate String newSignature = new SignedCertificateMessageBuilder() - .withSigningCertificate(new X509CertificateHolder(trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX").getEncoded()), trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX")) - .withPayload(new X509CertificateHolder(trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode).getEncoded())) + .withSigningCertificate(new X509CertificateHolder( + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.UPLOAD, "XX").getEncoded()), + trustedPartyTestHelper.getPrivateKey(TrustedPartyEntity.CertificateType.UPLOAD, "XX")) + .withPayload(new X509CertificateHolder( + trustedPartyTestHelper.getCert(TrustedPartyEntity.CertificateType.CSCA, countryCode).getEncoded())) .buildAsString(true); Assertions.assertTrue(certOptional.isPresent()); @@ -251,7 +265,8 @@ void trustedPartyServiceShouldNotReturnCertificateIfSignatureIsFromUnknownTrustA trustedPartyEntity.setSignature(newSignature); trustedPartyRepository.save(trustedPartyEntity); - certOptional = trustedPartyService.getCertificate(trustedPartyEntity.getThumbprint(), countryCode, TrustedPartyEntity.CertificateType.CSCA); + certOptional = trustedPartyService.getCertificate(trustedPartyEntity.getThumbprint(), countryCode, + TrustedPartyEntity.CertificateType.CSCA); Assertions.assertTrue(certOptional.isEmpty()); } @@ -261,13 +276,15 @@ private void prepareTestTrustedParty() throws Exception { trustedPartyTestHelper.getTestCert("test3", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", now); trustedPartyTestHelper.getTestCert("test4", TrustedPartyEntity.CertificateType.UPLOAD, "DE", nowMinusOneHour); trustedPartyTestHelper.getTestCert("test5", TrustedPartyEntity.CertificateType.CSCA, "DE", nowMinusOneHour); - trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", nowMinusOneHour); + trustedPartyTestHelper.getTestCert("test6", TrustedPartyEntity.CertificateType.AUTHENTICATION, "DE", + nowMinusOneHour); trustedPartyTestHelper.getTestCert("test7", TrustedPartyEntity.CertificateType.UPLOAD, "EU", now); trustedPartyTestHelper.getTestCert("test8", TrustedPartyEntity.CertificateType.CSCA, "EU", now); trustedPartyTestHelper.getTestCert("test9", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", now); trustedPartyTestHelper.getTestCert("test10", TrustedPartyEntity.CertificateType.UPLOAD, "EU", nowMinusOneHour); trustedPartyTestHelper.getTestCert("test11", TrustedPartyEntity.CertificateType.CSCA, "EU", nowMinusOneHour); - trustedPartyTestHelper.getTestCert("test12", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", nowMinusOneHour); + trustedPartyTestHelper.getTestCert("test12", TrustedPartyEntity.CertificateType.AUTHENTICATION, "EU", + nowMinusOneHour); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/service/ValuesetServiceTest.java b/src/test/java/eu/europa/ec/dgc/gateway/service/ValuesetServiceTest.java index 2e094def..8044967a 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/service/ValuesetServiceTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/service/ValuesetServiceTest.java @@ -77,8 +77,10 @@ void testGetValueset() { valuesetRepository.save(valuesetEntity1); valuesetRepository.save(valuesetEntity2); - Assertions.assertEquals(valuesetEntity1.getJson(), valuesetService.getValueSetById(valuesetEntity1.getId()).orElseThrow()); - Assertions.assertEquals(valuesetEntity2.getJson(), valuesetService.getValueSetById(valuesetEntity2.getId()).orElseThrow()); + Assertions.assertEquals(valuesetEntity1.getJson(), + valuesetService.getValueSetById(valuesetEntity1.getId()).orElseThrow()); + Assertions.assertEquals(valuesetEntity2.getJson(), + valuesetService.getValueSetById(valuesetEntity2.getId()).orElseThrow()); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/testdata/CertificateTestUtils.java b/src/test/java/eu/europa/ec/dgc/gateway/testdata/CertificateTestUtils.java index 91998361..92c6c2e0 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/testdata/CertificateTestUtils.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/testdata/CertificateTestUtils.java @@ -68,21 +68,24 @@ public static ValidationRule getDummyValidationRule() { return validationRule; } - public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName) throws Exception { + public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName) + throws Exception { Date validFrom = Date.from(Instant.now().minus(1, ChronoUnit.DAYS)); Date validTo = Date.from(Instant.now().plus(365, ChronoUnit.DAYS)); return generateCertificate(keyPair, country, commonName, validFrom, validTo); } - public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, X509Certificate ca, PrivateKey caKey) throws Exception { + public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, + X509Certificate ca, PrivateKey caKey) throws Exception { Date validFrom = Date.from(Instant.now().minus(1, ChronoUnit.DAYS)); Date validTo = Date.from(Instant.now().plus(365, ChronoUnit.DAYS)); return generateCertificate(keyPair, country, commonName, validFrom, validTo, ca, caKey); } - public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, Date validFrom, Date validTo) throws Exception { + public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, + Date validFrom, Date validTo) throws Exception { X500Name subject = new X500NameBuilder() .addRDN(X509ObjectIdentifiers.countryName, country) .addRDN(X509ObjectIdentifiers.commonName, commonName) @@ -101,7 +104,9 @@ public static X509Certificate generateCertificate(KeyPair keyPair, String countr return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner)); } - public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, Date validFrom, Date validTo, X509Certificate ca, PrivateKey caKey) throws Exception { + public static X509Certificate generateCertificate(KeyPair keyPair, String country, String commonName, + Date validFrom, Date validTo, X509Certificate ca, + PrivateKey caKey) throws Exception { X500Name subject = new X500NameBuilder() .addRDN(X509ObjectIdentifiers.countryName, country) .addRDN(X509ObjectIdentifiers.commonName, commonName) diff --git a/src/test/java/eu/europa/ec/dgc/gateway/testdata/DgcTestKeyStore.java b/src/test/java/eu/europa/ec/dgc/gateway/testdata/DgcTestKeyStore.java index eb3cf99c..3455537f 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/testdata/DgcTestKeyStore.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/testdata/DgcTestKeyStore.java @@ -98,17 +98,20 @@ public KeyStore testKeyStore() throws IOException, CertificateException, NoSuchA @Bean @Primary @Qualifier("publication") - public KeyStore testPublicationKeyStore() throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { + public KeyStore testPublicationKeyStore() + throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStoreSpi keyStoreSpiMock = mock(KeyStoreSpi.class); KeyStore keyStoreMock = new KeyStore(keyStoreSpiMock, null, "test") { }; keyStoreMock.load(null); doAnswer((x) -> publicationSigner) - .when(keyStoreSpiMock).engineGetCertificate(configProperties.getPublication().getKeystore().getCertificateAlias()); + .when(keyStoreSpiMock) + .engineGetCertificate(configProperties.getPublication().getKeystore().getCertificateAlias()); doAnswer((x) -> publicationSignerPrivateKey) - .when(keyStoreSpiMock).engineGetKey(eq(configProperties.getPublication().getKeystore().getCertificateAlias()), any()); + .when(keyStoreSpiMock) + .engineGetKey(eq(configProperties.getPublication().getKeystore().getCertificateAlias()), any()); return keyStoreMock; } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/testdata/SignerInformationTestHelper.java b/src/test/java/eu/europa/ec/dgc/gateway/testdata/SignerInformationTestHelper.java index eaf63074..cc10e0e3 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/testdata/SignerInformationTestHelper.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/testdata/SignerInformationTestHelper.java @@ -41,6 +41,7 @@ public void createSignerInformationInDB(String countryCode, String signature, X509Certificate certificate, ZonedDateTime createdAt) throws Exception { createSignerInformationInDB(countryCode, signature, certificate, createdAt, null); } + public void createSignerInformationInDB(String countryCode, String signature, X509Certificate certificate, ZonedDateTime createdAt, ZonedDateTime deletedAt) throws Exception { diff --git a/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedIssuerTestHelper.java b/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedIssuerTestHelper.java index 9a6ce805..9aa497b5 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedIssuerTestHelper.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedIssuerTestHelper.java @@ -51,8 +51,8 @@ public TrustedIssuerEntity createTrustedIssuer(final String country) throws Exce private String getHashData(TrustedIssuerEntity entity) { return entity.getCountry() + ";" - + entity.getName() + ";" - + entity.getUrl() + ";" - + entity.getUrlType().name() + ";"; + + entity.getName() + ";" + + entity.getUrl() + ";" + + entity.getUrlType().name() + ";"; } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedPartyTestHelper.java b/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedPartyTestHelper.java index 29df2dae..84cc9991 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedPartyTestHelper.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/testdata/TrustedPartyTestHelper.java @@ -69,8 +69,8 @@ public class TrustedPartyTestHelper { private final DgcTestKeyStore testKeyStore; public X509Certificate getTestCert(String testCertId, TrustedPartyEntity.CertificateType type, - String countryCode,ZonedDateTime createdAt) throws Exception { - return createAndInsertCert(testCertId, type, countryCode,createdAt); + String countryCode, ZonedDateTime createdAt) throws Exception { + return createAndInsertCert(testCertId, type, countryCode, createdAt); } public String getHash(TrustedPartyEntity.CertificateType type, String countryCode) throws Exception { @@ -115,7 +115,7 @@ private void prepareTestCert(TrustedPartyEntity.CertificateType type, String cou if (trustedPartyRepository.getFirstByThumbprintAndCertificateType( hashMap.get(type).get(countryCode), type ).isEmpty()) { - insertCert(type, countryCode, null, certificateMap.get(type).get(countryCode)); + insertCert(type, countryCode, null, certificateMap.get(type).get(countryCode)); } } @@ -143,7 +143,7 @@ private X509Certificate createAndInsertCert(String testCertId, TrustedPartyEntit } private X509Certificate insertCert(TrustedPartyEntity.CertificateType type, String countryCode, - ZonedDateTime createdAt, X509Certificate authCertificate) throws Exception { + ZonedDateTime createdAt, X509Certificate authCertificate) throws Exception { String certRawData = Base64.getEncoder().encodeToString(authCertificate.getEncoded()); String certHash = certificateUtils.getCertThumbprint(authCertificate); @@ -155,7 +155,9 @@ private X509Certificate insertCert(TrustedPartyEntity.CertificateType type, Stri .buildAsString(true); TrustedPartyEntity trustedPartyEntity = new TrustedPartyEntity(); - if(createdAt != null) trustedPartyEntity.setCreatedAt(createdAt); + if (createdAt != null) { + trustedPartyEntity.setCreatedAt(createdAt); + } trustedPartyEntity.setCertificateType(type); trustedPartyEntity.setCountry(countryCode); trustedPartyEntity.setSignature(signature); @@ -168,8 +170,9 @@ private X509Certificate insertCert(TrustedPartyEntity.CertificateType type, Stri public String signString(final String hashdata) throws Exception { return new SignedStringMessageBuilder() - .withPayload(hashdata) - .withSigningCertificate(new X509CertificateHolder(testKeyStore.getTrustAnchor().getEncoded()), testKeyStore.getTrustAnchorPrivateKey()) - .buildAsString(); + .withPayload(hashdata) + .withSigningCertificate(new X509CertificateHolder(testKeyStore.getTrustAnchor().getEncoded()), + testKeyStore.getTrustAnchorPrivateKey()) + .buildAsString(); } }